commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 152 6.66k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
256a86b9cfbf2f78fc913b87997dd89673d177c5 | custom/icds_reports/migrations/0070_ccsrecordmonthly_closed.py | custom/icds_reports/migrations/0070_ccsrecordmonthly_closed.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 14:35
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
from corehq.sql_db.operations import RawSQLMigration
from custom.icds_reports.utils.migrations import get_view_migrations
mi... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 14:35
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
from corehq.sql_db.operations import RawSQLMigration
from custom.icds_reports.utils.migrations import get_view_migrations
mi... | Remove adding field to View model | Remove adding field to View model
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | <DELETE> migrations.AddField(
model_name='CcsRecordMonthlyView',
name='open_in_month',
field=models.SmallIntegerField(blank=True, null=True),
),
<DELETE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 14:35
from __future__ import... | Remove adding field to View model
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 14:35
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
from corehq.sql_db.operations import RawSQLMigration
from custom.icds_reports.utils.migrat... |
aace7956091f10af19dfe9eaaf12aef8b0f9f579 | new_validity.py | new_validity.py | import pandas as pd
import numpy as np
import operator
from sys import argv
import os
def extract( file_name ):
with open(file_name) as f:
for i,line in enumerate(f,1):
if "SCN" in line:
return i
os.system('ltahdr -i'+ argv[1]+ '> lta_fi... | import pandas as pd
import numpy as np
import operator
from sys import argv
import os
def extract( file_name ):
with open(file_name) as f:
for i,line in enumerate(f,1):
if "SCN" in line:
return i
def main(lta_name):
os.system('ltahdr -i'+ lta_name + '> lta_file.txt')
di... | Insert main body of code into function | Insert main body of code into function
| Python | mit | NCRA-TIFR/gadpu,NCRA-TIFR/gadpu | <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <INSERT> return i
def main(lta_name):
<INSERT_END> <INSERT> os.system('ltahdr -i'+ lta_name + '> lta_file.txt')
<INSERT_END> <INSERT> dictionary = {}
<INSERT_END> <INSERT> #lta_file = str(argv[1])
<INSERT_END> <INSERT> skipped... | Insert main body of code into function
import pandas as pd
import numpy as np
import operator
from sys import argv
import os
def extract( file_name ):
with open(file_name) as f:
for i,line in enumerate(f,1):
if "SCN" in line:
return i
o... |
9d1e404eaf8e78efd6117266baf86ff3228915da | src/img2line.py | src/img2line.py | # -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
from pylab import *
import types
from skimage import io, data
# 读取图片,灰度化,并转为数组
im0 = Image.open("test.jpeg").convert('L')
im = array(im0)
# print(type(im[1, 1]))
x = y = 0
m = im.shape[0]
n = im.shape[1]
h = range(m - 2)
k = range(n - 2)
matrix = np.ar... | Convert a image to many lines. | Convert a image to many lines.
| Python | apache-2.0 | xpeng2333/robodraw,xpeng2333/robodraw,xpeng2333/robodraw,xpeng2333/robodraw | <INSERT> # -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
from pylab import *
import types
from skimage import io, data
# 读取图片,灰度化,并转为数组
im0 = Image.open("test.jpeg").convert('L')
im = array(im0)
# print(type(im[1, 1]))
x = y = 0
m = im.shape[0]
n = im.shape[1]
h = range(m - 2)
k = range(n - 2)
matri... | Convert a image to many lines.
| |
719b2ac28e27f8e8b0d0acea315c355e7a34cd25 | cerbero/commands/genvsprops.py | cerbero/commands/genvsprops.py | # cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; eit... | Add command to create VS property sheets for all pkgconfig pacakges | Add command to create VS property sheets for all pkgconfig pacakges
| Python | lgpl-2.1 | nzjrs/cerbero,centricular/cerbero,justinjoy/cerbero,multipath-rtp/cerbero,superdump/cerbero,cee1/cerbero-mac,ylatuya/cerbero,lubosz/cerbero,ford-prefect/cerbero,nzjrs/cerbero,fluendo/cerbero,brion/cerbero,freedesktop-unofficial-mirror/gstreamer__sdk__cerbero,GStreamer/cerbero,AlertMe/cerbero,ylatuya/cerbero,sdroege/cer... | <REPLACE_OLD> <REPLACE_NEW> # cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the ... | Add command to create VS property sheets for all pkgconfig pacakges
| |
bf8ddb49a1043f399a210e05e66e2db4d815cc22 | tests/test_build_chess.py | tests/test_build_chess.py | # -*- coding: utf-8 -*-
from app.chess.chess import Chess
import unittest
class TestBuildChess(unittest.TestCase):
"""
`TestBuildChess()` class is unit-testing the class
Chess().
"""
# ///////////////////////////////////////////////////
def setUp(self):
params = [4, 4]
piece... | # -*- coding: utf-8 -*-
from chess.chess import Chess
import unittest
class TestBuildChess(unittest.TestCase):
"""
`TestBuildChess()` class is unit-testing the class
Chess().
"""
# ///////////////////////////////////////////////////
def setUp(self):
params = [4, 4]
... | Add a TDD function ( queens on chess board) | Add a TDD function ( queens on chess board) | Python | mit | aymguesmi/ChessChallenge | <REPLACE_OLD> app.chess.chess <REPLACE_NEW> chess.chess <REPLACE_END> <REPLACE_OLD> unittest
class <REPLACE_NEW> unittest
class <REPLACE_END> <REPLACE_OLD> 0, <REPLACE_NEW> 1, <REPLACE_END> <REPLACE_OLD> 0, <REPLACE_NEW> 1, <REPLACE_END> <REPLACE_OLD> 0}
<REPLACE_NEW> 1}
<REPLACE_END> <REPLACE_OLD> ... | Add a TDD function ( queens on chess board)
# -*- coding: utf-8 -*-
from app.chess.chess import Chess
import unittest
class TestBuildChess(unittest.TestCase):
"""
`TestBuildChess()` class is unit-testing the class
Chess().
"""
# ///////////////////////////////////////////////////
def setUp(... |
d3d88d628c61a87b1a36f9a25bdea807dd2d12a2 | saleor/dashboard/settings/forms.py | saleor/dashboard/settings/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from ...setting.models import Setting
class SettingForm(forms.ModelForm):
class Meta:
model = Setting
exclude = []
def clean_name(self):
name = self.cleaned_data['name']
if len(name.split()) > 1:
... | from django import forms
from django.utils.translation import ugettext_lazy as _
from ...setting.models import Setting
class SettingForm(forms.ModelForm):
class Meta:
model = Setting
exclude = []
def clean_name(self):
name = self.cleaned_data['name']
if len(name.split()) > 1:... | Add missing newline between imports | Add missing newline between imports
| Python | bsd-3-clause | tfroehlich82/saleor,KenMutemi/saleor,itbabu/saleor,maferelo/saleor,KenMutemi/saleor,jreigel/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,mociepka/saleor,KenMutemi/saleor,itbabu/saleor,mociepka/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor,car3oon/saleor,mociepka/saleor,UITools/saleor,UITools/... | <REPLACE_OLD> _
from <REPLACE_NEW> _
from <REPLACE_END> <|endoftext|> from django import forms
from django.utils.translation import ugettext_lazy as _
from ...setting.models import Setting
class SettingForm(forms.ModelForm):
class Meta:
model = Setting
exclude = []
def clean_name(self):
... | Add missing newline between imports
from django import forms
from django.utils.translation import ugettext_lazy as _
from ...setting.models import Setting
class SettingForm(forms.ModelForm):
class Meta:
model = Setting
exclude = []
def clean_name(self):
name = self.cleaned_data['name... |
daed28559cc16374f85830ef9d939ccddece64a1 | tests/test_parser.py | tests/test_parser.py | # -*- coding: utf-8 -*-
import codecs
import pytest
from poyo import parse_string
@pytest.fixture
def string_data():
with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
return ymlfile.read()
def test_parse_string(string_data):
expected = {
u'default_context': {
u... | # -*- coding: utf-8 -*-
import codecs
import pytest
from poyo import parse_string
@pytest.fixture
def string_data():
with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
return ymlfile.read()
def test_parse_string(string_data):
expected = {
u'default_context': {
u... | Add list to expectation in test | Add list to expectation in test
| Python | mit | hackebrot/poyo | <INSERT> u'doc_tools': [u'mkdocs', u'sphinx', None],
<INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
import codecs
import pytest
from poyo import parse_string
@pytest.fixture
def string_data():
with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
return ymlfile.read()
def ... | Add list to expectation in test
# -*- coding: utf-8 -*-
import codecs
import pytest
from poyo import parse_string
@pytest.fixture
def string_data():
with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
return ymlfile.read()
def test_parse_string(string_data):
expected = {
u'... |
a95b1b2b5331e4248fe1d80244c763df4d3aca41 | taiga/urls.py | taiga/urls.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(... | Set prefix to static url patterm call | Set prefix to static url patterm call
| Python | agpl-3.0 | jeffdwyatt/taiga-back,bdang2012/taiga-back-casting,WALR/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,EvgeneOskin/taiga-back,CoolCloud/taiga-back,WALR/taiga-back,Rademade/taiga-back,seanchen/taiga-back,taigaio/taiga-back,astronaut1712/taiga-back,astronaut1712/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back... | <REPLACE_OLD> staticfiles_urlpatterns()
urlpatterns <REPLACE_NEW> staticfiles_urlpatterns(prefix="/static/")
urlpatterns <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpa... | Set prefix to static url patterm call
# -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = pat... |
3e51aa99f27f5e61737cc900cbbdfe53bd8c212b | docstamp/filenames.py | docstamp/filenames.py | # coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais Vasco UPV/EHU
#
# 2015, Alexandre Manhaes Savio
# Use this at your own risk!
# -----... | Add helpers to manage file names | Add helpers to manage file names
| Python | apache-2.0 | PythonSanSebastian/docstamp | <REPLACE_OLD> <REPLACE_NEW> # coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais Vasco UPV/EHU
#
# 2015, Alexandre Manhaes Savio
# Use t... | Add helpers to manage file names
| |
d2f3ff32e6d0a8c03a76f93669bb1f37d28ae124 | parsl/tests/configs/local_threads_globus.py | parsl/tests/configs/local_threads_globus.py | from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir
# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this a... | from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir
# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this a... | Fix storage_access in the test config | Fix storage_access in the test config
| Python | apache-2.0 | Parsl/parsl,Parsl/parsl,Parsl/parsl,swift-lang/swift-e-lab,Parsl/parsl,swift-lang/swift-e-lab | <REPLACE_OLD> storage_access=GlobusScheme(
<REPLACE_NEW> storage_access=[GlobusScheme(
<REPLACE_END> <REPLACE_OLD> ),
<REPLACE_NEW> )[,
<REPLACE_END> <|endoftext|> from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.te... | Fix storage_access in the test config
from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir
# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If yo... |
4340b4c1719761c7ebfbd0aba7a27a76604e6ddb | test/order/TestOrder.py | test/order/TestOrder.py | """
Test that debug symbols have the correct order as specified by the order file.
"""
import os, time
import re
import unittest
import lldb
import lldbtest
class TestClassTypes(lldbtest.TestBase):
mydir = "order"
def test_order(self):
"""Test debug symbols follow the correct order by the order file... | Test that debug symbols have the correct order as specified by the order file. | Test that debug symbols have the correct order as specified by the order file.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@107844 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb | <REPLACE_OLD> <REPLACE_NEW> """
Test that debug symbols have the correct order as specified by the order file.
"""
import os, time
import re
import unittest
import lldb
import lldbtest
class TestClassTypes(lldbtest.TestBase):
mydir = "order"
def test_order(self):
"""Test debug symbols follow the co... | Test that debug symbols have the correct order as specified by the order file.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@107844 91177308-0d34-0410-b5e6-96231b3b80d8
| |
30674fb6e244373bb8b1ed74b7a38e5cc2ed19a7 | ibmcnx/doc/Documentation.py | ibmcnx/doc/Documentation.py | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
... | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
... | Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | <REPLACE_OLD> sys
sys.stdout <REPLACE_NEW> sys
emp1 <REPLACE_END> <REPLACE_OLD> open("/tmp/documentation.txt", "w")
print <REPLACE_NEW> ibmcnx.filehandle.Ibmcnxfile()
sys.stdout = emp1
print <REPLACE_END> <|endoftext|> ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles... | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@... |
4f4522bfa969a823a240a6ce16bcec395da06cf2 | src/poliastro/twobody/decorators.py | src/poliastro/twobody/decorators.py | """Decorators.
"""
from functools import wraps
from astropy import units as u
from poliastro.bodies import Body
from poliastro.twobody.rv import RVState
u.kms = u.km / u.s
u.km3s2 = u.km ** 3 / u.s ** 2
def state_from_vector(func):
@wraps(func)
def wrapper(t, u_, k, *args, **kwargs):
r, v = u_[:... | """Decorators.
"""
from functools import wraps
from astropy import units as u
from poliastro.bodies import Body
from poliastro.twobody.rv import RVState
u.kms = u.km / u.s
u.km3s2 = u.km ** 3 / u.s ** 2
def state_from_vector(func):
@wraps(func)
def wrapper(t, u_, k, *args, **kwargs):
r, v = u_[:... | Remove extra arguments from decorated function | Remove extra arguments from decorated function
| Python | mit | anhiga/poliastro,poliastro/poliastro,Juanlu001/poliastro,newlawrence/poliastro,newlawrence/poliastro,anhiga/poliastro,newlawrence/poliastro,Juanlu001/poliastro,anhiga/poliastro,Juanlu001/poliastro | <DELETE> r, v, <DELETE_END> <|endoftext|> """Decorators.
"""
from functools import wraps
from astropy import units as u
from poliastro.bodies import Body
from poliastro.twobody.rv import RVState
u.kms = u.km / u.s
u.km3s2 = u.km ** 3 / u.s ** 2
def state_from_vector(func):
@wraps(func)
def wrapper(t, u_... | Remove extra arguments from decorated function
"""Decorators.
"""
from functools import wraps
from astropy import units as u
from poliastro.bodies import Body
from poliastro.twobody.rv import RVState
u.kms = u.km / u.s
u.km3s2 = u.km ** 3 / u.s ** 2
def state_from_vector(func):
@wraps(func)
def wrapper... |
a406e198127d22944340a0c364112684556177f2 | scripts/feature_selection.py | scripts/feature_selection.py | import pandas as pd
import numpy as np
from xgboost.sklearn import XGBClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import KFold
from sklearn.feature_selection import SelectFromModel
from utils.metrics import ndcg_scorer
pa... | Add structure to feature selection script | Add structure to feature selection script
| Python | mit | davidgasquez/kaggle-airbnb | <REPLACE_OLD> <REPLACE_NEW> import pandas as pd
import numpy as np
from xgboost.sklearn import XGBClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import KFold
from sklearn.feature_selection import SelectFromModel
from utils.m... | Add structure to feature selection script
| |
ab158de23187fd0ca838d7f89c2be81cab0cb0a2 | tools/compare_resample.py | tools/compare_resample.py | # Script to plot original wav file against wav file resampled at 16 kHz
# Licensed under Apache v2 (see LICENSE)
from __future__ import division
import sys
import os
import glob
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randint
from scipy.signal import resample
# Problems doing th... | Add script to check resampling of wav files | Add script to check resampling of wav files
| Python | apache-2.0 | voicesauce/opensauce-python,voicesauce/opensauce-python,voicesauce/opensauce-python | <REPLACE_OLD> <REPLACE_NEW> # Script to plot original wav file against wav file resampled at 16 kHz
# Licensed under Apache v2 (see LICENSE)
from __future__ import division
import sys
import os
import glob
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randint
from scipy.signal import ... | Add script to check resampling of wav files
| |
6b04211b42e76f6428fbaac361059fad4bef70de | txircd/modules/conn_join.py | txircd/modules/conn_join.py | from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.chan... | from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.chan... | Fix once again nobody being allowed to connect | Fix once again nobody being allowed to connect
| Python | bsd-3-clause | Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd | <REPLACE_OLD> channel))
class <REPLACE_NEW> channel))
return True
class <REPLACE_END> <REPLACE_OLD> self.conn_join.joinOnConnect
}
}
def <REPLACE_NEW> [self.conn_join.joinOnConnect]
}
}
def <REPLACE_END> <|endoftext|> from txircd.channel import IRCChannel
from txircd.modbase import Module
class Aut... | Fix once again nobody being allowed to connect
from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.irc... |
18e3c3f716863b1cc259800592a07a89844d4bf8 | appvalidator/testcases/scripting.py | appvalidator/testcases/scripting.py | import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
... | import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
... | Add information about JS test status to metadata | Add information about JS test status to metadata | Python | bsd-3-clause | mozilla/app-validator,stasm/app-validator,diox/app-validator,eviljeff/app-validator,eviljeff/app-validator,diox/app-validator,mstriemer/app-validator,diox/app-validator,eviljeff/app-validator,mstriemer/app-validator,mozilla/app-validator,diox/app-validator,mozilla/app-validator,stasm/app-validator,stasm/app-validator,e... | <INSERT> err.metadata.ran_js_tests = "no;missing ast"
<INSERT_END> <INSERT> err.metadata.ran_js_tests = "yes"
<INSERT_END> <|endoftext|> import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator... | Add information about JS test status to metadata
import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a ... |
792d0ace4f84023d1132f8d61a88bd48e3d7775d | test/contrib/test_pyopenssl.py | test/contrib/test_pyopenssl.py | from nose.plugins.skip import SkipTest
from urllib3.packages import six
if six.PY3:
raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTe... | from nose.plugins.skip import SkipTest
from urllib3.packages import six
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTest('Could not import PyOpenSSL: %r' % e)
from ..with_dummyserver.test_... | Enable PyOpenSSL testing on Python 3. | Enable PyOpenSSL testing on Python 3.
| Python | mit | Lukasa/urllib3,haikuginger/urllib3,Disassem/urllib3,urllib3/urllib3,Disassem/urllib3,haikuginger/urllib3,urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3,Lukasa/urllib3 | <REPLACE_OLD> six
if six.PY3:
raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
<REPLACE_NEW> six
try:
<REPLACE_END> <|endoftext|> from nose.plugins.skip import SkipTest
from urllib3.packages import six
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
... | Enable PyOpenSSL testing on Python 3.
from nose.plugins.skip import SkipTest
from urllib3.packages import six
if six.PY3:
raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
ex... |
cb7631303a73e69ffa62811be2ea79e2d4a6d64b | src/main/resources/script_templates/Python/Process_Folder.py | src/main/resources/script_templates/Python/Process_Folder.py | import os
from ij import IJ, ImagePlus
from ij.gui import GenericDialog
def run():
srcDir = IJ.getDirectory("Input_directory")
if not srcDir:
return
dstDir = IJ.getDirectory("Output_directory")
if not dstDir:
return
gd = GenericDialog("Process Folder")
gd.addStringField("File_extension", ".tif")
... | Add python template to process a folder of images | Add python template to process a folder of images | Python | bsd-2-clause | imagej/imagej-legacy,imagej/imagej-legacy,imagej/imagej-legacy,imagej/imagej-legacy | <REPLACE_OLD> <REPLACE_NEW> import os
from ij import IJ, ImagePlus
from ij.gui import GenericDialog
def run():
srcDir = IJ.getDirectory("Input_directory")
if not srcDir:
return
dstDir = IJ.getDirectory("Output_directory")
if not dstDir:
return
gd = GenericDialog("Process Folder")
gd.addStringFie... | Add python template to process a folder of images
| |
c96a2f636b48b065e8404af6d67fbae5986fd34a | tests/basics/subclass_native2_tuple.py | tests/basics/subclass_native2_tuple.py | class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
| class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
a = tuple([1,... | Expand test cases for equality of subclasses. | tests/basics: Expand test cases for equality of subclasses.
| Python | mit | pramasoul/micropython,adafruit/circuitpython,henriknelson/micropython,MrSurly/micropython,bvernoux/micropython,tobbad/micropython,kerneltask/micropython,kerneltask/micropython,tobbad/micropython,tobbad/micropython,pramasoul/micropython,selste/micropython,adafruit/circuitpython,henriknelson/micropython,pozetroninc/micro... | <REPLACE_OLD> 3])
print(len(a))
<REPLACE_NEW> 3])
print(len(a))
a = tuple([1,2,3])
b = Ctuple1([1,2,3])
c = Ctuple2([1,2,3])
print(a == b)
print(b == c)
print(c == a)
<REPLACE_END> <|endoftext|> class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
... | tests/basics: Expand test cases for equality of subclasses.
class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
prin... |
37baf4b9929b7d894cdb090bb4874d7a782a2c38 | solvent/run.py | solvent/run.py | import subprocess
import logging
def run(command, cwd=None):
try:
return subprocess.check_output(
command, cwd=cwd, stderr=subprocess.STDOUT,
stdin=open("/dev/null"), close_fds=True)
except subprocess.CalledProcessError as e:
logging.error("Failed command '%s' output:\n... | import subprocess
import logging
import os
def fix_env_in_case_of_invalid_locale_name(env):
"""See https://github.com/ros-drivers/hokuyo_node/issues/3"""
env["LC_ALL"] = "C"
def run(command, cwd=None):
env = os.environ.copy()
fix_env_in_case_of_invalid_locale_name(env)
try:
return subpro... | Fix env var for osmosis when locale name is invalid | Fix env var for osmosis when locale name is invalid
See https://github.com/ros-drivers/hokuyo_node/issues/3
| Python | apache-2.0 | Stratoscale/solvent,Stratoscale/solvent | <REPLACE_OLD> logging
def <REPLACE_NEW> logging
import os
def fix_env_in_case_of_invalid_locale_name(env):
"""See https://github.com/ros-drivers/hokuyo_node/issues/3"""
env["LC_ALL"] = "C"
def <REPLACE_END> <INSERT> env = os.environ.copy()
fix_env_in_case_of_invalid_locale_name(env)
<INSERT_END> <... | Fix env var for osmosis when locale name is invalid
See https://github.com/ros-drivers/hokuyo_node/issues/3
import subprocess
import logging
def run(command, cwd=None):
try:
return subprocess.check_output(
command, cwd=cwd, stderr=subprocess.STDOUT,
stdin=open("/dev/null"), close... |
c5b2cb667a59cf6fa16c860744fd5978cd3c01a2 | src/lexington/util/paths.py | src/lexington/util/paths.py | from urllib import parse
from werkzeug.wrappers import Request
from lexington.util.di import depends_on
@depends_on(['environ'])
def get_request(environ):
return Request(environ)
# TODO: clean up all of these...
@depends_on(['environ'])
def get_method(environ):
return environ['REQUEST_METHOD']
@depends_on([... | from werkzeug.wrappers import Request
from lexington.util.di import depends_on
@depends_on(['environ'])
def get_request(environ):
return Request(environ)
@depends_on(['request'])
def get_method(request):
return request.method
@depends_on(['request'])
def get_path(request):
return request.path
@depends_... | Reduce direct dependencies on environ | Reduce direct dependencies on environ
| Python | mit | jmikkola/Lexington | <DELETE> urllib import parse
from <DELETE_END> <REPLACE_OLD> Request(environ)
# TODO: clean up all of these...
@depends_on(['environ'])
def get_method(environ):
<REPLACE_NEW> Request(environ)
@depends_on(['request'])
def get_method(request):
<REPLACE_END> <REPLACE_OLD> environ['REQUEST_METHOD']
@depends_on(['envir... | Reduce direct dependencies on environ
from urllib import parse
from werkzeug.wrappers import Request
from lexington.util.di import depends_on
@depends_on(['environ'])
def get_request(environ):
return Request(environ)
# TODO: clean up all of these...
@depends_on(['environ'])
def get_method(environ):
return e... |
6ac87bf5f6b86f507caa7764ed949d5b27d18517 | tools/jinja_pylint.py | tools/jinja_pylint.py | #!/usr/bin/env python
'''
Run pylint on a Jinja 2 template.
'''
import jinja2, os, subprocess, sys, tempfile
# Clagged pieces from the runner.
START_BLOCK = '/*-'
END_BLOCK = '-*/'
START_VARIABLE = '/*?'
END_VARIABLE = '?*/'
START_COMMENT = '/*#'
END_COMMENT = '#*/'
def main(argv, out, err):
if len(argv) < 2 or... | Add a tool for running pylint on Jinja templates. | Add a tool for running pylint on Jinja templates.
Closes JIRA CAMKES-315
| Python | bsd-2-clause | agacek/camkes-tool,agacek/camkes-tool,smaccm/camkes-tool,agacek/camkes-tool,smaccm/camkes-tool,smaccm/camkes-tool,smaccm/camkes-tool | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
'''
Run pylint on a Jinja 2 template.
'''
import jinja2, os, subprocess, sys, tempfile
# Clagged pieces from the runner.
START_BLOCK = '/*-'
END_BLOCK = '-*/'
START_VARIABLE = '/*?'
END_VARIABLE = '?*/'
START_COMMENT = '/*#'
END_COMMENT = '#*/'
def main(argv, out, ... | Add a tool for running pylint on Jinja templates.
Closes JIRA CAMKES-315
| |
479f04ae23227ebb8a3a298d875b73cb1b6de3b6 | ceph_deploy/tests/parser/test_rgw.py | ceph_deploy/tests/parser/test_rgw.py | import pytest
from ceph_deploy.cli import get_parser
class TestParserRGW(object):
def setup(self):
self.parser = get_parser()
def test_rgw_help(self, capsys):
with pytest.raises(SystemExit):
self.parser.parse_args('rgw --help'.split())
out, err = capsys.readouterr()
... | Add argparse tests for rgw module | [RM-11742] Add argparse tests for rgw module
Signed-off-by: Travis Rhoden <e5e44d6dbac12e32e01c3bb8b67940d8b42e225b@redhat.com>
| Python | mit | branto1/ceph-deploy,Vicente-Cheng/ceph-deploy,shenhequnying/ceph-deploy,imzhulei/ceph-deploy,Vicente-Cheng/ceph-deploy,trhoden/ceph-deploy,SUSE/ceph-deploy-to-be-deleted,ceph/ceph-deploy,SUSE/ceph-deploy,zhouyuan/ceph-deploy,imzhulei/ceph-deploy,osynge/ceph-deploy,isyippee/ceph-deploy,ghxandsky/ceph-deploy,shenhequnyin... | <REPLACE_OLD> <REPLACE_NEW> import pytest
from ceph_deploy.cli import get_parser
class TestParserRGW(object):
def setup(self):
self.parser = get_parser()
def test_rgw_help(self, capsys):
with pytest.raises(SystemExit):
self.parser.parse_args('rgw --help'.split())
out, e... | [RM-11742] Add argparse tests for rgw module
Signed-off-by: Travis Rhoden <e5e44d6dbac12e32e01c3bb8b67940d8b42e225b@redhat.com>
| |
190dae03cc027e397c387294075e1a38ad8647da | migrations/versions/2017-07-14_11:37:46__df33f3613823.py | migrations/versions/2017-07-14_11:37:46__df33f3613823.py | """empty message
Revision ID: df33f3613823
Revises: 15741cc426db
Create Date: 2017-07-14 11:37:46.347709
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'df33f3613823'
down_revision = '15741cc426db'
branch_labels = None
depends_on = None
def upgrade():
# ... | Add migration for patient model | :rocket: Add migration for patient model
| Python | mit | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys | <INSERT> """empty message
Revision ID: df33f3613823
Revises: 15741cc426db
Create Date: 2017-07-14 11:37:46.347709
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'df33f3613823'
down_revision = '15741cc426db'
branch_labels = None
depends_on = None
def upgrade(... | :rocket: Add migration for patient model
| |
b627efe0675b2b1965eeac7104cf3a8f2d675539 | rhcephcompose/main.py | rhcephcompose/main.py | """ rhcephcompose CLI """
from argparse import ArgumentParser
import kobo.conf
from rhcephcompose.compose import Compose
class RHCephCompose(object):
""" Main class for rhcephcompose CLI. """
def __init__(self):
parser = ArgumentParser(description='Generate a compose for RHCS.')
parser.add_... | """ rhcephcompose CLI """
from argparse import ArgumentParser
import kobo.conf
from rhcephcompose.compose import Compose
class RHCephCompose(object):
""" Main class for rhcephcompose CLI. """
def __init__(self):
parser = ArgumentParser(description='Generate a compose for RHCS.')
parser.add_... | Add --insecure option to command line to disable SSL certificate verification when communicating with chacra | Add --insecure option to command line to disable SSL certificate verification when communicating with chacra
| Python | mit | red-hat-storage/rhcephcompose,red-hat-storage/rhcephcompose | <INSERT> parser.add_argument('--insecure', action='store_const', const=True,
default=False, help='skip SSL verification')
<INSERT_END> <REPLACE_OLD> conf.load_from_file(args.config_file)
<REPLACE_NEW> conf.load_from_file(args.config_file)
if args.insecure:
conf[... | Add --insecure option to command line to disable SSL certificate verification when communicating with chacra
""" rhcephcompose CLI """
from argparse import ArgumentParser
import kobo.conf
from rhcephcompose.compose import Compose
class RHCephCompose(object):
""" Main class for rhcephcompose CLI. """
def __... |
307e105ff075a4702169ca5b38e3f3307bfdad5a | tools/clean_submitted_plugins.py | tools/clean_submitted_plugins.py | """Prints out submitted plugins that we don't already know about.
Also deletes any empty submissions.
"""
import json
import re
import rethinkdb as r
import db.github_repos
import db.util
r_conn = db.util.r_conn
_GITHUB_LINK_REGEX = re.compile(r'github.com/(.*?)/([^/?#]*)')
def delete_empty_submissions():
... | Add a script to easily view new submitted plugins | Add a script to easily view new submitted plugins
Summary: That is, submitted plugins that we don't already know about and are non-empty.
Test Plan:
- imported the `submitted_plugins` table from prod
- ran `PYTHONPATH=. python tools/clean_submitted_plugins.py`
- saw the output looked reasonable
Reviewers: xymostech,... | Python | mit | divad12/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,shaialon/vim-awesome,jonafato/vim-awesome,shaialon/vim-awesome,starcraftman/vim-awesome,jonafato/vim-awesome,vim-awesome/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,starcraftman/vim-awesome,shaialon/vim-awesome,jonafato/vim-awesome,starcraftman... | <REPLACE_OLD> <REPLACE_NEW> """Prints out submitted plugins that we don't already know about.
Also deletes any empty submissions.
"""
import json
import re
import rethinkdb as r
import db.github_repos
import db.util
r_conn = db.util.r_conn
_GITHUB_LINK_REGEX = re.compile(r'github.com/(.*?)/([^/?#]*)')
def del... | Add a script to easily view new submitted plugins
Summary: That is, submitted plugins that we don't already know about and are non-empty.
Test Plan:
- imported the `submitted_plugins` table from prod
- ran `PYTHONPATH=. python tools/clean_submitted_plugins.py`
- saw the output looked reasonable
Reviewers: xymostech,... | |
93dfefff12569c180e20fefc9380358753c6771e | molo/core/tests/test_import_from_git_view.py | molo/core/tests/test_import_from_git_view.py | import pytest
from django.test import TestCase
from django.core.urlresolvers import reverse
from molo.core.tests.base import MoloTestCaseMixin
@pytest.mark.django_db
class TestImportFromGit(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
self.user = self.login()
def test_wagt... | import pytest
from django.test import TestCase
from django.core.urlresolvers import reverse
from molo.core.tests.base import MoloTestCaseMixin
@pytest.mark.django_db
class TestImportFromGit(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
self.user = self.login()
def test_wagt... | Fix import UI django view's tests | Fix import UI django view's tests
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo | <REPLACE_OLD> self.client.get(reverse("import-from-git"))
<REPLACE_NEW> self.client.get(reverse('import-from-git'))
<REPLACE_END> <REPLACE_OLD> self.assertContains(response, <REPLACE_NEW> self.assertContains(
response, <REPLACE_END> <REPLACE_OLD> Git')
<REPLACE_NEW> a Universal Core site')
<REPLACE_END>... | Fix import UI django view's tests
import pytest
from django.test import TestCase
from django.core.urlresolvers import reverse
from molo.core.tests.base import MoloTestCaseMixin
@pytest.mark.django_db
class TestImportFromGit(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
self.use... |
222cc6a9910f4fc44fd15a64da5db52a94d9a3c3 | setup.py | setup.py | # coding=utf-8
from setuptools import setup, find_packages
setup(
name="git-up",
version="1.3.0",
packages=find_packages(exclude=["tests"]),
scripts=['PyGitUp/gitup.py'],
install_requires=['GitPython==1.0.0', 'colorama==0.3.3',
'termcolor==1.1.0', 'docopt==0.6.2',
... | # coding=utf-8
from setuptools import setup, find_packages
setup(
name="git-up",
version="1.3.0",
packages=find_packages(exclude=["tests"]),
scripts=['PyGitUp/gitup.py'],
install_requires=['GitPython==1.0.0', 'colorama==0.3.3',
'termcolor==1.1.0', 'docopt==0.6.2',
... | Use full module path for entry point | Use full module path for entry point
| Python | mit | christer155/PyGitUp,christer155/PyGitUp,msiemens/PyGitUp | <REPLACE_OLD> gitup:run'
<REPLACE_NEW> PyGitUp.gitup:run'
<REPLACE_END> <|endoftext|> # coding=utf-8
from setuptools import setup, find_packages
setup(
name="git-up",
version="1.3.0",
packages=find_packages(exclude=["tests"]),
scripts=['PyGitUp/gitup.py'],
install_requires=['GitPython==... | Use full module path for entry point
# coding=utf-8
from setuptools import setup, find_packages
setup(
name="git-up",
version="1.3.0",
packages=find_packages(exclude=["tests"]),
scripts=['PyGitUp/gitup.py'],
install_requires=['GitPython==1.0.0', 'colorama==0.3.3',
't... |
e804e2258183d9986f5756327f875735c8234924 | apps/uploads/forms.py | apps/uploads/forms.py | #
# Copyright (C) 2017 Maha Farhat
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distribu... | Add a test form object for testing | Add a test form object for testing
| Python | agpl-3.0 | IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site | <INSERT> #
# Copyright (C) 2017 Maha Farhat
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is... | Add a test form object for testing
| |
f5e36391c253a52fe2bd434caf59c0f5c389cc64 | tests/base.py | tests/base.py | import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()
db.create_all... | import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.drop_all()
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()... | Drop db before each test | Drop db before each test
| Python | agpl-3.0 | Meisterschueler/ogn-python,glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,Meisterschueler/ogn-python | <INSERT> db.drop_all()
<INSERT_END> <|endoftext|> import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.drop_all()
db.session.execute('CREATE EXTE... | Drop db before each test
import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.comm... |
27c614b30eda339ca0c61f35e498be6456f2280f | scoring/__init__.py | scoring/__init__.py | import numpy as np
from sklearn.cross_validation import cross_val_score
from sklearn.externals import joblib as pickle
class scorer(object):
def __init__(self, model, descriptor_generator, model_opts = {}, desc_opts = {}):
self.model = model()
self.descriptor_generator = descriptor_generator(**desc... | import numpy as np
from sklearn.cross_validation import cross_val_score
from sklearn.externals import joblib as pickle
class scorer(object):
def __init__(self, model_instance, descriptor_generator_instance):
self.model = model_instance
self.descriptor_generator = descriptor_generator_instance
... | Make scorer accept instances of model and desc. gen. | Make scorer accept instances of model and desc. gen.
| Python | bsd-3-clause | mwojcikowski/opendrugdiscovery | <REPLACE_OLD> model, descriptor_generator, model_opts = {}, desc_opts = {}):
<REPLACE_NEW> model_instance, descriptor_generator_instance):
<REPLACE_END> <REPLACE_OLD> model()
<REPLACE_NEW> model_instance
<REPLACE_END> <REPLACE_OLD> descriptor_generator(**desc_opts)
<REPLACE_NEW> descriptor_generator_instance
<REP... | Make scorer accept instances of model and desc. gen.
import numpy as np
from sklearn.cross_validation import cross_val_score
from sklearn.externals import joblib as pickle
class scorer(object):
def __init__(self, model, descriptor_generator, model_opts = {}, desc_opts = {}):
self.model = model()
s... |
77a6ff9fa19349bcb9428e79b7a7bf05cb4fb2a2 | demo/apps/catalogue/migrations/0011_auto_20160616_1335.py | demo/apps/catalogue/migrations/0011_auto_20160616_1335.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0013_make_rendition_upload_callable'),
('catalogue', '0010_auto_20160616_1048'),
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0013_make_rendition_upload_callable'),
('catalogue', '0010_auto_20160616_1048'),
... | Add field instead of alter field | Add field instead of alter field
| Python | mit | pgovers/oscar-wagtail-demo,pgovers/oscar-wagtail-demo | <REPLACE_OLD> migrations.AlterField(
<REPLACE_NEW> migrations.AddField(
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtai... | Add field instead of alter field
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0013_make_rendition_upload_callable'),
('catalogu... |
e34bcec834bf4d84168d04a1ea0a98613ad0df4e | corehq/apps/locations/management/commands/migrate_new_location_fixture.py | corehq/apps/locations/management/commands/migrate_new_location_fixture.py | from django.core.management.base import BaseCommand
from toggle.models import Toggle
from corehq.apps.locations.models import LocationFixtureConfiguration, SQLLocation
from corehq.toggles import FLAT_LOCATION_FIXTURE
class Command(BaseCommand):
help = """
To migrate to new flat fixture for locations. Update ... | import json
from django.core.management.base import BaseCommand
from toggle.models import Toggle
from corehq.apps.locations.models import SQLLocation
from corehq.apps.domain.models import Domain
from corehq.toggles import HIERARCHICAL_LOCATION_FIXTURE, NAMESPACE_DOMAIN
class Command(BaseCommand):
help = """
... | Update migration to fetch domains with applications using old location fixture | Update migration to fetch domains with applications using old location fixture | Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | <REPLACE_OLD> from <REPLACE_NEW> import json
from <REPLACE_END> <DELETE> LocationFixtureConfiguration, <DELETE_END> <INSERT> corehq.apps.domain.models import Domain
from <INSERT_END> <REPLACE_OLD> FLAT_LOCATION_FIXTURE
class <REPLACE_NEW> HIERARCHICAL_LOCATION_FIXTURE, NAMESPACE_DOMAIN
class <REPLACE_END> <REPLACE_... | Update migration to fetch domains with applications using old location fixture
from django.core.management.base import BaseCommand
from toggle.models import Toggle
from corehq.apps.locations.models import LocationFixtureConfiguration, SQLLocation
from corehq.toggles import FLAT_LOCATION_FIXTURE
class Command(BaseCom... |
413c3e9e8a093e3f336e27a663f347f5ea9866a6 | performanceplatform/collector/ga/__init__.py | performanceplatform/collector/ga/__init__.py | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performanceplatform.collector.ga.core \
import create_client, query_documents_for, send_data
from performanceplatform.collector.write import DataSet
def main(credentials, data_set_config, query, options, start_at, end_at):
clien... | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performanceplatform.collector.ga.core \
import create_client, query_documents_for, send_data
from performanceplatform.collector.write import DataSet
def main(credentials, data_set_config, query, options, start_at, end_at):
clien... | Allow the 'dataType' field to be overriden | Allow the 'dataType' field to be overriden
The 'dataType' field in records predates data groups and data types. As
such they don't always match the new world order of data types. It's
fine to change in all cases other than Licensing which is run on
limelight, that we don't really want to touch.
| Python | mit | alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector | <REPLACE_OLD> data_set_config['data-type'], start_at, end_at
<REPLACE_NEW> options.get('dataType', data_set_config['data-type']),
<REPLACE_END> <REPLACE_OLD> )
<REPLACE_NEW> start_at, end_at)
<REPLACE_END> <|endoftext|> from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performan... | Allow the 'dataType' field to be overriden
The 'dataType' field in records predates data groups and data types. As
such they don't always match the new world order of data types. It's
fine to change in all cases other than Licensing which is run on
limelight, that we don't really want to touch.
from pkgutil import ex... |
98548ce5da63dc10d31e3d8f93d4ea99ccae1f48 | tests/machines/merge_overlapping_intervals/vim_merge_overlapping_intervals_test.py | tests/machines/merge_overlapping_intervals/vim_merge_overlapping_intervals_test.py | import subprocess
from vim_turing_machine.machines.merge_overlapping_intervals.decode_intervals import decode_intervals
from vim_turing_machine.machines.merge_overlapping_intervals.encode_intervals import encode_intervals
from vim_turing_machine.machines.merge_overlapping_intervals.merge_overlapping_intervals import M... | Add an integration test for the vim machine. | Add an integration test for the vim machine.
| Python | mit | ealter/vim_turing_machine,ealter/vim_turing_machine | <REPLACE_OLD> <REPLACE_NEW> import subprocess
from vim_turing_machine.machines.merge_overlapping_intervals.decode_intervals import decode_intervals
from vim_turing_machine.machines.merge_overlapping_intervals.encode_intervals import encode_intervals
from vim_turing_machine.machines.merge_overlapping_intervals.merge_o... | Add an integration test for the vim machine.
| |
4a32fe3b3735df9ec56a4ca1769268740ef5d8f4 | tests/test_to_html.py | tests/test_to_html.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки."
def setUp(self):
from paka.cmark import to_html
self.func = to_html
def check(self, source, expe... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = (
"Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n"
"<p>Test of <em>HTML</em>.</p>")
def setUp(self):
from paka.cmark import to_html
... | Add HTML fragment to test sample | Add HTML fragment to test sample
| Python | bsd-3-clause | PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark | <INSERT> (
<INSERT_END> <REPLACE_OLD> штуки."
<REPLACE_NEW> штуки.\n\n"
"<p>Test of <em>HTML</em>.</p>")
<REPLACE_END> <REPLACE_OLD> штуки.</p>\n"))
<REPLACE_NEW> штуки.</p>\n"
"<p>Test of <em>HTML</em>.</p>\n"))
<REPLACE_END> <REPLACE_OLD> штуки.</p>\n"),
<REPLACE_NEW> штуки.</... | Add HTML fragment to test sample
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки."
def setUp(self):
from paka.cmark import to_html
self.func = to_html... |
6520fde5be81eb3d1a91662edeef8bd2a1f6389c | stonemason/service/tileserver/helper.py | stonemason/service/tileserver/helper.py | # -*- encoding: utf-8 -*-
__author__ = 'ray'
__date__ = '4/4/15'
from stonemason.mason import Portrayal
from stonemason.mason.theme import Theme
def jsonify_portrayal(portrayal):
assert isinstance(portrayal, Portrayal)
template = {
'name': portrayal.name,
'metadata': {
'version':... | # -*- encoding: utf-8 -*-
__author__ = 'ray'
__date__ = '4/4/15'
from stonemason.mason import Portrayal
from stonemason.mason.theme import Theme
def jsonify_portrayal(portrayal):
assert isinstance(portrayal, Portrayal)
template = {
'name': portrayal.name,
'metadata': {
'title': p... | Add metadata title in portrayal view | FEATURE: Add metadata title in portrayal view
| Python | mit | Kotaimen/stonemason,Kotaimen/stonemason | <INSERT> 'title': portrayal.metadata.title,
<INSERT_END> <|endoftext|> # -*- encoding: utf-8 -*-
__author__ = 'ray'
__date__ = '4/4/15'
from stonemason.mason import Portrayal
from stonemason.mason.theme import Theme
def jsonify_portrayal(portrayal):
assert isinstance(portrayal, Portrayal)
templa... | FEATURE: Add metadata title in portrayal view
# -*- encoding: utf-8 -*-
__author__ = 'ray'
__date__ = '4/4/15'
from stonemason.mason import Portrayal
from stonemason.mason.theme import Theme
def jsonify_portrayal(portrayal):
assert isinstance(portrayal, Portrayal)
template = {
'name': portrayal.nam... |
e46e512fad9bc92c1725711e2800e44bb699d281 | deploy/mirrors/greasyfork.py | deploy/mirrors/greasyfork.py | from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/new'.format(SCRIPT_ID)
b = ... | from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/new'.format(SCRIPT_ID)
b = ... | Fix Greasy Fork deploy script. | Fix Greasy Fork deploy script.
| Python | bsd-2-clause | MNBuyskih/adsbypasser,tablesmit/adsbypasser,xor10/adsbypasser,kehugter/adsbypasser,tosunkaya/adsbypasser,xor10/adsbypasser,MNBuyskih/adsbypasser,tablesmit/adsbypasser,kehugter/adsbypasser,kehugter/adsbypasser,tablesmit/adsbypasser,xor10/adsbypasser,tosunkaya/adsbypasser,MNBuyskih/adsbypasser,tosunkaya/adsbypasser | <REPLACE_OLD> b.select_form(nr=1)
<REPLACE_NEW> b.select_form(nr=2)
<REPLACE_END> <REPLACE_OLD> b.select_form(nr=1)
<REPLACE_NEW> b.select_form(nr=2)
<REPLACE_END> <INSERT> b['script_version[code]'] = script.encode('utf-8')
<INSERT_END> <|endoftext|> from mechanize import Browser
def exec_(config, summary, sc... | Fix Greasy Fork deploy script.
from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/... |
5191055f0cc071ff4dc0a8ea42e598809c519be4 | magnum/db/sqlalchemy/alembic/versions/3b6c4c42adb4_add_unique_constraints.py | magnum/db/sqlalchemy/alembic/versions/3b6c4c42adb4_add_unique_constraints.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Add unique column constraints to db | Add unique column constraints to db
Unique constraints are not being set on the database but they are
defined in the schema. This db upgrade adds the unique constraints.
Change-Id: I0dd1c2190bf7b68e1e0c8c71fbb123d2c82cc0d3
Closes-Bug: 1451761
| Python | apache-2.0 | ChengTiesheng/magnum,hongbin/magnum,eshijia/magnum,Tennyson53/magnum,dimtruck/magnum,eshijia/SUR,ArchiFleKs/magnum,dimtruck/magnum,Tennyson53/magnum,ddepaoli3/magnum,LaynePeng/magnum,ChengTiesheng/magnum,ramielrowe/magnum,mjbrewer/testindex,Tennyson53/SUR,mjbrewer/testindex,ffantast/magnum,annegentle/magnum,ddepaoli3/m... | <REPLACE_OLD> <REPLACE_NEW> # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | Add unique column constraints to db
Unique constraints are not being set on the database but they are
defined in the schema. This db upgrade adds the unique constraints.
Change-Id: I0dd1c2190bf7b68e1e0c8c71fbb123d2c82cc0d3
Closes-Bug: 1451761
| |
0cad0060afcc5936541b3739ff03c06b8a773ec8 | tests/templatetags/test_tags.py | tests/templatetags/test_tags.py | from django import template
from lazy_tags.decorators import lazy_tag
register = template.Library()
@register.simple_tag
def test():
return '<p>hello world</p>'
@register.simple_tag
@lazy_tag
def test_decorator():
return 'Success!'
@register.simple_tag
@lazy_tag
def test_simple_dec_args(arg, kwarg=None... | from django import template
from django.utils.safestring import mark_safe
from lazy_tags.decorators import lazy_tag
register = template.Library()
@register.simple_tag
def test():
return mark_safe('<p>hello world</p>')
@register.simple_tag
@lazy_tag
def test_decorator():
return 'Success!'
@register.simp... | Fix test on Django 1.9 | Fix test on Django 1.9
| Python | mit | grantmcconnaughey/django-lazy-tags,grantmcconnaughey/django-lazy-tags | <REPLACE_OLD> template
from <REPLACE_NEW> template
from django.utils.safestring import mark_safe
from <REPLACE_END> <REPLACE_OLD> '<p>hello world</p>'
@register.simple_tag
@lazy_tag
def <REPLACE_NEW> mark_safe('<p>hello world</p>')
@register.simple_tag
@lazy_tag
def <REPLACE_END> <|endoftext|> from django import ... | Fix test on Django 1.9
from django import template
from lazy_tags.decorators import lazy_tag
register = template.Library()
@register.simple_tag
def test():
return '<p>hello world</p>'
@register.simple_tag
@lazy_tag
def test_decorator():
return 'Success!'
@register.simple_tag
@lazy_tag
def test_simple_... |
64d838897a38398074433ce1e6a50393fc414a03 | test_project/urls.py | test_project/urls.py | from django.conf.urls.defaults import patterns, include, url
import settings
import os
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
'django.views.generic.simple.direct_to_template',
{'template': 'index.html'}
),
url(r'^test/', 'test_app.... | try:
from django.conf.urls.defaults import patterns, include, url
except ImportError:
from django.conf.urls import patterns, url, include
import settings
import os
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
'django.views.generic.simple.direct_to_t... | Fix for 1.6 & 1.7 | Fix for 1.6 & 1.7
| Python | mit | nikolas/django-interval-field,mpasternak/django-interval-field,mpasternak/django-interval-field,nikolas/django-interval-field | <INSERT> try:
<INSERT_END> <REPLACE_OLD> url
import <REPLACE_NEW> url
except ImportError:
from django.conf.urls import patterns, url, include
import <REPLACE_END> <|endoftext|> try:
from django.conf.urls.defaults import patterns, include, url
except ImportError:
from django.conf.urls import patterns, u... | Fix for 1.6 & 1.7
from django.conf.urls.defaults import patterns, include, url
import settings
import os
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
'django.views.generic.simple.direct_to_template',
{'template': 'index.html'}
),
url(r'... |
9591911cf98348a771f7fffc8951bfd578cc02ce | send_sms.py | send_sms.py | # Download the twilio-python library from http://twilio.com/docs/libraries
from twilio.rest import TwilioRestClient
import config
# Find these values at https://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXX"
auth_token = "YYYYYYYYYYYYYYYYYY"
client = TwilioRestClient(account_sid, auth_token)
message = cl... | Add snippet for sending sms. | Add snippet for sending sms.
| Python | mit | mattstibbs/twilio-snippets | <INSERT> # Download the twilio-python library from http://twilio.com/docs/libraries
from twilio.rest import TwilioRestClient
import config
# Find these values at https://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXX"
auth_token = "YYYYYYYYYYYYYYYYYY"
client = TwilioRestClient(account_sid, auth_token)
mes... | Add snippet for sending sms.
| |
03f1f9558b717cd2d6b08db609eb8bd706ad641e | griddedspectra.py | griddedspectra.py | # -*- coding: utf-8 -*-
"""Class to create spectra spaced on a regular grid through the box"""
import numpy as np
import hdfsim
import spectra
class GriddedSpectra(spectra.Spectra):
"""Generate metal line spectra from simulation snapshot. Default parameters are BOSS DR9"""
def __init__(self,num, base, nspec=2... | Add script for generating spectra on a grid | Add script for generating spectra on a grid
| Python | mit | sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
"""Class to create spectra spaced on a regular grid through the box"""
import numpy as np
import hdfsim
import spectra
class GriddedSpectra(spectra.Spectra):
"""Generate metal line spectra from simulation snapshot. Default parameters are BOSS DR9"""
def __i... | Add script for generating spectra on a grid
| |
1a1f0a9bca7458153ef84316fd84dfbe56be08ef | dolo/config.py | dolo/config.py | #from __future__ import print_function
# This module is supposed to be imported first
# it contains global variables used for configuration
# try to register printing methods if IPython is running
save_plots = False
try:
import dolo.misc.printing as printing
from numpy import ndarray
from dolo.symbolic... | #from __future__ import print_function
# This module is supposed to be imported first
# it contains global variables used for configuration
# try to register printing methods if IPython is running
save_plots = False
try:
import dolo.misc.printing as printing
from numpy import ndarray
from dolo.symbolic... | Remove print("failing back on pretty_print") when using dolo-recs | Remove print("failing back on pretty_print") when using dolo-recs
| Python | bsd-2-clause | EconForge/dolo | <REPLACE_OLD> display
except:
<REPLACE_NEW> display
except:
import re
import sys
if not re.search('dolo-recs',sys.argv[0]):
<REPLACE_END> <|endoftext|> #from __future__ import print_function
# This module is supposed to be imported first
# it contains global variables used for configuration
# tr... | Remove print("failing back on pretty_print") when using dolo-recs
#from __future__ import print_function
# This module is supposed to be imported first
# it contains global variables used for configuration
# try to register printing methods if IPython is running
save_plots = False
try:
import dolo.misc.printi... |
f81e409ab1666a8a3bb1ff1806d256644712382f | structures/__init__.py | structures/__init__.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from .base import DBStructure, _Generated
from .files.main import *
from .files.custom import *
from ..locales import L
class StructureError(Exception):
pass
class StructureLoader():
wowfiles = None
@classmethod
def setup(cls):
if cls.wowfiles is None:
cls.wowfile... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from .base import DBStructure, _Generated
from .files.main import *
from .files.custom import *
from ..locales import L
class UnknownStructure(Exception):
pass
class StructureLoader():
wowfiles = None
@classmethod
def setup(cls):
if cls.wowfiles is None:
cls.wowfi... | Raise more appropriate UnknownStructure exception rather than StructureError if a structure is not found. | structures: Raise more appropriate UnknownStructure exception rather than StructureError if a structure is not found.
| Python | cc0-1.0 | jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow | <REPLACE_OLD> StructureError(Exception):
pass
class <REPLACE_NEW> UnknownStructure(Exception):
pass
class <REPLACE_END> <REPLACE_OLD> globals()[name]
@classmethod
def <REPLACE_NEW> globals()[name]
@classmethod
def <REPLACE_END> <REPLACE_OLD> StructureError(L["STRUCTURE_NOT_FOUND"] <REPLACE_NEW> UnknownStr... | structures: Raise more appropriate UnknownStructure exception rather than StructureError if a structure is not found.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from .base import DBStructure, _Generated
from .files.main import *
from .files.custom import *
from ..locales import L
class StructureError(Exception):
pas... |
f48063cfb9674c1e5f1f94e62ff43b239f687abd | examples/plot_tot_histogram.py | examples/plot_tot_histogram.py | """
==================
ToT histogram.
==================
Create a simple histogram of the PMT signals (ToTs) in all events.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import pandas as pd
import matplotlib.pyplot as plt
import km3pipe.style
km3pipe.style.use("km3pipe")
filename = "data/km3net_jul13_9... | """
==================
ToT histogram.
==================
Create a simple histogram of the PMT signals (ToTs) in all events.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import tables as tb
import matplotlib.pyplot as plt
import km3pipe.style
km3pipe.style.use("km3pipe")
filename = "data/km3net_jul13_9... | Fix for new km3hdf5 version 4 | Fix for new km3hdf5 version 4
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe | <REPLACE_OLD> pandas <REPLACE_NEW> tables <REPLACE_END> <REPLACE_OLD> pd
import <REPLACE_NEW> tb
import <REPLACE_END> <REPLACE_OLD> "data/km3net_jul13_90m_muatm50T655.km3_v5r1.JTE_r2356.root.0-499.h5"
hits <REPLACE_NEW> "data/km3net_jul13_90m_muatm50T655.km3_v5r1.JTE_r2356.root.0-499.h5"
with tb.File(filename) as f:
... | Fix for new km3hdf5 version 4
"""
==================
ToT histogram.
==================
Create a simple histogram of the PMT signals (ToTs) in all events.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import pandas as pd
import matplotlib.pyplot as plt
import km3pipe.style
km3pipe.style.use("km3pipe")
... |
1c4429759a3e89ed952b1a025b1470a9e187537f | tests/test_spatial_reference.py | tests/test_spatial_reference.py | # -*- coding: utf-8 -*-
import rasterio
import pytest
from math import pi
from numpy import array
from numpy.testing import assert_array_almost_equal
from gdal2mbtiles.constants import EPSG_WEB_MERCATOR
from gdal2mbtiles.gdal import SpatialReference
# SEMI_MAJOR is a constant referring to the WGS84 Semi Major Ax... | Add test for the EPSG-3857 spatial reference. | Add test for the EPSG-3857 spatial reference.
| Python | apache-2.0 | ecometrica/gdal2mbtiles | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
import rasterio
import pytest
from math import pi
from numpy import array
from numpy.testing import assert_array_almost_equal
from gdal2mbtiles.constants import EPSG_WEB_MERCATOR
from gdal2mbtiles.gdal import SpatialReference
# SEMI_MAJOR is a constant referri... | Add test for the EPSG-3857 spatial reference.
| |
f203602b5c5e901f54895c1872becf0b48438628 | src/pluggy/_result.py | src/pluggy/_result.py | """
Hook wrapper "result" utilities.
"""
import sys
def _raise_wrapfail(wrap_controller, msg):
co = wrap_controller.gi_code
raise RuntimeError(
"wrap_controller at %r %s:%d %s"
% (co.co_name, co.co_filename, co.co_firstlineno, msg)
)
class HookCallError(Exception):
""" Hook was calle... | """
Hook wrapper "result" utilities.
"""
import sys
def _raise_wrapfail(wrap_controller, msg):
co = wrap_controller.gi_code
raise RuntimeError(
"wrap_controller at %r %s:%d %s"
% (co.co_name, co.co_filename, co.co_firstlineno, msg)
)
class HookCallError(Exception):
""" Hook was calle... | Remove explicit inheritance from object | Remove explicit inheritance from object
| Python | mit | pytest-dev/pluggy,RonnyPfannschmidt/pluggy,hpk42/pluggy,pytest-dev/pluggy,RonnyPfannschmidt/pluggy | <REPLACE_OLD> _Result(object):
<REPLACE_NEW> _Result:
<REPLACE_END> <|endoftext|> """
Hook wrapper "result" utilities.
"""
import sys
def _raise_wrapfail(wrap_controller, msg):
co = wrap_controller.gi_code
raise RuntimeError(
"wrap_controller at %r %s:%d %s"
% (co.co_name, co.co_filename, co... | Remove explicit inheritance from object
"""
Hook wrapper "result" utilities.
"""
import sys
def _raise_wrapfail(wrap_controller, msg):
co = wrap_controller.gi_code
raise RuntimeError(
"wrap_controller at %r %s:%d %s"
% (co.co_name, co.co_filename, co.co_firstlineno, msg)
)
class HookCal... |
3a44dbeec871aa057c4d5b42c9089a8d2b649063 | django_agpl/urls.py | django_agpl/urls.py | # -*- coding: utf-8 -*-
#
# django-agpl -- tools to aid releasing Django projects under the AGPL
# Copyright (C) 2008, 2009, 2016 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by t... | # -*- coding: utf-8 -*-
#
# django-agpl -- tools to aid releasing Django projects under the AGPL
# Copyright (C) 2008, 2009, 2016 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by t... | Drop patterns import for Django 1.0 compatibility. | Drop patterns import for Django 1.0 compatibility.
| Python | agpl-3.0 | lamby/django-agpl,lamby/django-agpl | <DELETE> patterns, <DELETE_END> <REPLACE_OLD> patterns('django_agpl.views',
<REPLACE_NEW> (
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
#
# django-agpl -- tools to aid releasing Django projects under the AGPL
# Copyright (C) 2008, 2009, 2016 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free softwar... | Drop patterns import for Django 1.0 compatibility.
# -*- coding: utf-8 -*-
#
# django-agpl -- tools to aid releasing Django projects under the AGPL
# Copyright (C) 2008, 2009, 2016 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... |
21572b5bef09bd60bd61b68241a155ddb2dd4444 | tests/test_children.py | tests/test_children.py | # coding: pyxl
from pyxl import html
def test_no_filter():
children = <div><p>One</p><p>Two</p></div>.children()
assert len(children) == 2
assert str(children[0]) == '<p>One</p>'
assert str(children[1]) == '<p>Two</p>'
def test_class_filter():
div = <div><p class="yo">Hi</p><p>No</p><p class="yo"... | Add tests for children method. | Add tests for children method.
- all children are returned
- filter by tag
- filter by id
- filter by class
- negate filter (exclude)
| Python | apache-2.0 | pyxl4/pyxl4 | <INSERT> # coding: pyxl
from pyxl import html
def test_no_filter():
<INSERT_END> <INSERT> children = <div><p>One</p><p>Two</p></div>.children()
assert len(children) == 2
assert str(children[0]) == '<p>One</p>'
assert str(children[1]) == '<p>Two</p>'
def test_class_filter():
div = <div><p class="yo... | Add tests for children method.
- all children are returned
- filter by tag
- filter by id
- filter by class
- negate filter (exclude)
| |
05e61f1be4005edf2ff439ca2613bce8af217ff7 | pubsubpull/models.py | pubsubpull/models.py | """
Models.
"""
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from pubsubpull.fields import JSONB
class Request(models.Model):
"""A web request.
"""
user = models.ForeignKey(User, null=True, blank=True, related_name='reques... | """
Models.
"""
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from pubsubpull.fields import JSONB
class Request(models.Model):
"""A web request.
"""
user = models.ForeignKey(User, null=True, blank=True, related_name='reques... | Add more useful display of the request data. | Add more useful display of the request data.
| Python | mit | KayEss/django-pubsubpull,KayEss/django-pubsubpull,KayEss/django-pubsubpull | <REPLACE_OLD> models.TextField()
OPERATION_TYPE <REPLACE_NEW> models.TextField()
def __unicode__(self):
return "%s %s" % (self.method, self.path)
OPERATION_TYPE <REPLACE_END> <|endoftext|> """
Models.
"""
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError... | Add more useful display of the request data.
"""
Models.
"""
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from pubsubpull.fields import JSONB
class Request(models.Model):
"""A web request.
"""
user = models.ForeignKey(Use... |
d0c8968766a06e8c426e75edddb9c6ce88d080a0 | fsspec/implementations/tests/test_common.py | fsspec/implementations/tests/test_common.py | import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = ... | import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = ... | Fix typo in test assertion | Fix typo in test assertion
| Python | bsd-3-clause | fsspec/filesystem_spec,intake/filesystem_spec,fsspec/filesystem_spec | <REPLACE_OLD> modified > created
<REPLACE_NEW> isinstance(modified, datetime.datetime)
<REPLACE_END> <REPLACE_OLD> isinstance(created, datetime.datetime)
<REPLACE_NEW> modified > created
<REPLACE_END> <|endoftext|> import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tes... | Fix typo in test assertion
import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(T... |
493314bb1d8778c10033f7011cd865526c34b6ce | boardinghouse/contrib/template/apps.py | boardinghouse/contrib/template/apps.py | from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.template'
def ready(self):
from boardinghouse import signals
from .... | from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.template'
def ready(self):
from boardinghouse import signals
from .... | Debug version to check codeship. | Debug version to check codeship.
--HG--
branch : schema-templates/fix-codeship-issue
| Python | bsd-3-clause | schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse | <INSERT> print schema.schema
print kwargs
<INSERT_END> <|endoftext|> from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardingh... | Debug version to check codeship.
--HG--
branch : schema-templates/fix-codeship-issue
from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.t... |
3d027b8d4d39fcdbc839bd0e186ea225e1c7b976 | tests/__init__.py | tests/__init__.py | from .test_great_expectations import *
from .test_util import *
from .test_dataset import *
from .test_pandas_dataset import *
from tests.pandas.test_pandas_dataset_distributional_expectations import *
from .test_expectation_decorators import *
from .test_cli import *
| # from .test_great_expectations import *
# from .test_util import *
# from .test_dataset import *
# from .test_pandas_dataset import *
# from tests.pandas.test_pandas_dataset_distributional_expectations import *
# from .test_expectation_decorators import *
# from .test_cli import *
| Remove explicit import in tests module. | Remove explicit import in tests module.
| Python | apache-2.0 | great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations | <INSERT> # <INSERT_END> <REPLACE_OLD> *
from <REPLACE_NEW> *
# from <REPLACE_END> <REPLACE_OLD> *
from <REPLACE_NEW> *
# from <REPLACE_END> <REPLACE_OLD> *
from <REPLACE_NEW> *
# from <REPLACE_END> <REPLACE_OLD> *
from <REPLACE_NEW> *
# from <REPLACE_END> <REPLACE_OLD> *
from <REPLACE_NEW> *
# from <REPLACE_END> <REPLA... | Remove explicit import in tests module.
from .test_great_expectations import *
from .test_util import *
from .test_dataset import *
from .test_pandas_dataset import *
from tests.pandas.test_pandas_dataset_distributional_expectations import *
from .test_expectation_decorators import *
from .test_cli import *
|
a65187bebdec6ec99a9b5e967e818948ffb70969 | test_pcalg.py | test_pcalg.py | # -*- coding: utf-8 -*-
'''
Test suite for pcalg
'''
import networkx as nx
import numpy as np
from gsq.ci_tests import ci_test_bin, ci_test_dis
from gsq.gsq_testdata import bin_data, dis_data
import pytest
from pcalg import estimate_cpdag
from pcalg import estimate_skeleton
@pytest.mark.parametrize(('indep_test_fun... | Add test to verify fixed_edges option | test: Add test to verify fixed_edges option
Signed-off-by: limjcst <a207579da1956e43e71ded4d0c18bba514713a1d@163.com>
| Python | bsd-2-clause | keiichishima/pcalg | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
'''
Test suite for pcalg
'''
import networkx as nx
import numpy as np
from gsq.ci_tests import ci_test_bin, ci_test_dis
from gsq.gsq_testdata import bin_data, dis_data
import pytest
from pcalg import estimate_cpdag
from pcalg import estimate_skeleton
@pytest.mark... | test: Add test to verify fixed_edges option
Signed-off-by: limjcst <a207579da1956e43e71ded4d0c18bba514713a1d@163.com>
| |
f4e0254eada3a6dd3aaa794926c5cc82e993b180 | setup/bin/swc-nano-installer.py | setup/bin/swc-nano-installer.py | #!/usr/bin/env python
"""Software Carpentry Nano Installer for Windows
Installs nano and makes it the default editor in msysgit
To use:
1. Install Python
2. Install msysgit
http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git
3. Run swc_nano_installer.py
You should be able to simply d... | Add a Nano installer for Windows | Add a Nano installer for Windows
1. Downloads and installs Nano into the users home directory
2. Adds Nano to the path
3. Makes Nano the default editor
| Python | bsd-2-clause | selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
"""Software Carpentry Nano Installer for Windows
Installs nano and makes it the default editor in msysgit
To use:
1. Install Python
2. Install msysgit
http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git
3. Run swc_nano_installer.py
Y... | Add a Nano installer for Windows
1. Downloads and installs Nano into the users home directory
2. Adds Nano to the path
3. Makes Nano the default editor
| |
a8ef0d416b94c453ea8f3605e8cae7147ae90830 | appengine/isolate/main_frontend.py | appengine/isolate/main_frontend.py | # Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""This modules is imported by AppEngine and defines the 'app' object.
It is a separate file so that application bootstrapping code like ereporter2,
tha... | # Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""This modules is imported by AppEngine and defines the 'app' object.
It is a separate file so that application bootstrapping code like ereporter2,
tha... | Fix typo in commit 4b061a25b579c and 2c2176043b739. | Fix typo in commit 4b061a25b579c and 2c2176043b739.
It's IsolateService, not IsolateServer.
TBR=vadimsh@chromium.org
BUG=
Review URL: https://codereview.appspot.com/221200043
| Python | apache-2.0 | luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py | <REPLACE_OLD> endpoints.api_server([handlers_endpoints.IsolateServer])
<REPLACE_NEW> endpoints.api_server([handlers_endpoints.IsolateService])
<REPLACE_END> <|endoftext|> # Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in... | Fix typo in commit 4b061a25b579c and 2c2176043b739.
It's IsolateService, not IsolateServer.
TBR=vadimsh@chromium.org
BUG=
Review URL: https://codereview.appspot.com/221200043
# Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# fo... |
508ca596d46c08fdc9295769059f5de974b2d1df | base/components/accounts/admin.py | base/components/accounts/admin.py | from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(ContributorMixin, self).save_model(request, obj, form, change)
if not change:
obj.... | from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
o... | Move this to the bottom... | Move this to the bottom...
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | <INSERT> if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
obj.save()
<INSERT_END> <REPLACE_OLD> change)
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
obj.save()
class <REPLACE_NEW> ch... | Move this to the bottom...
from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(ContributorMixin, self).save_model(request, obj, form, change)
if ... |
01949a1f5d8278ab1d577e2d56b1c9fd2f79724c | metpy/plots/tests/test_skewt.py | metpy/plots/tests/test_skewt.py | import tempfile
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
from metpy.plots.skewt import * # noqa
# TODO: Need at some point to do image-based comparison, but that's a lot to
# bite off right now
class TestSkewT(object):
def test_api(self):... | import tempfile
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
from metpy.plots.skewt import * # noqa
# TODO: Need at some point to do image-based comparison, but that's a lot to
# bite off right now
class TestSkewT(object):
def test_api(self):... | Remove test for not passing figure. | Remove test for not passing figure.
This will trigger matplotlib's backend detection, which won't work well
for us on Travis.
| Python | bsd-3-clause | dopplershift/MetPy,ahaberlie/MetPy,Unidata/MetPy,ShawnMurd/MetPy,Unidata/MetPy,jrleeman/MetPy,ahaberlie/MetPy,ahill818/MetPy,deeplycloudy/MetPy,jrleeman/MetPy,dopplershift/MetPy | <REPLACE_OLD> FigureCanvasAgg(fig).print_png(f.name)
def test_no_figure(self):
'Test the SkewT api'
skew = SkewT()
with tempfile.NamedTemporaryFile() as f:
FigureCanvasAgg(skew.ax.figure).print_png(f.name)
<REPLACE_NEW> FigureCanvasAgg(fig).print_png(f.name)
<REPLACE_END> <|en... | Remove test for not passing figure.
This will trigger matplotlib's backend detection, which won't work well
for us on Travis.
import tempfile
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
from metpy.plots.skewt import * # noqa
# TODO: Need at so... |
d97b9f6c508dd24da0f86bc1587ea64708c84a89 | tools/dist/security/mailinglist.py | tools/dist/security/mailinglist.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 not... | Add parser for the advisory mail recipients. | Add parser for the advisory mail recipients.
* tools/dist/security/mailinglist.py: New.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@1717919 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion | <REPLACE_OLD> <REPLACE_NEW> #
# 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 (... | Add parser for the advisory mail recipients.
* tools/dist/security/mailinglist.py: New.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@1717919 13f79535-47bb-0310-9956-ffa450edef68
| |
939ebf2eb4536fd5a6318d6cc4b55a9dc4c8def2 | documentation/compile_documentation.py | documentation/compile_documentation.py | import sys
import os
def find_code(text):
START_TAG = '```lpg'
END_TAG = '```'
first_index = text.find(START_TAG)
if first_index == -1:
return None, None
last_index = text.find(END_TAG, first_index + 1)
return first_index + len(START_TAG), last_index
def process_file(path):
conte... | import sys
import os
def find_code(text):
START_TAG = '```lpg'
END_TAG = '```'
first_index = text.find(START_TAG)
if first_index == -1:
return None, None
last_index = text.find(END_TAG, first_index + 1)
return first_index + len(START_TAG), last_index
def process_file(path):
conte... | Split the documentation compilation into different files | Split the documentation compilation into different files
| Python | mit | TyRoXx/Lpg,TyRoXx/Lpg,TyRoXx/Lpg,mamazu/Lpg,mamazu/Lpg,mamazu/Lpg,TyRoXx/Lpg,mamazu/Lpg,TyRoXx/Lpg | <INSERT> with open(file_name, 'w') as f:
f.write(code)
def write_codeblocks_to_different_files(code_blocks):
<INSERT_END> <REPLACE_OLD> enumerate(code):
print_block = '// %s : %i\n%s\n' <REPLACE_NEW> enumerate(code_blocks):
write_to_file('codeblock%i.lpg' <REPLACE_END> <DELETE> (file_name,... | Split the documentation compilation into different files
import sys
import os
def find_code(text):
START_TAG = '```lpg'
END_TAG = '```'
first_index = text.find(START_TAG)
if first_index == -1:
return None, None
last_index = text.find(END_TAG, first_index + 1)
return first_index + len(... |
d1d668139be98283dc9582c32fadf7de2b30914d | src/identfilter.py | src/identfilter.py | import sys
import re
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
# We only care about Graphene types
if not text.startswith('graphene_') and not text.endswith('_t'):
return text
res = []
for token in text[:-2].split('_'):
uc_token = token.title()
# We need ... | # Copyright 2014 Emmanuele Bassi
#
# 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, modify, merge, publish, distri... | Add licensing to the introspection filter | Add licensing to the introspection filter
It's a small utility script, but it's better to have a license for it
anyway.
| Python | mit | ebassi/graphene,ebassi/graphene | <REPLACE_OLD> import <REPLACE_NEW> # Copyright 2014 Emmanuele Bassi
#
# 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, c... | Add licensing to the introspection filter
It's a small utility script, but it's better to have a license for it
anyway.
import sys
import re
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
# We only care about Graphene types
if not text.startswith('graphene_') and not text.endswith('_t... |
32a02c58a67813417eaa49c80edbdd77f8b2569f | py/minimum-time-difference.py | py/minimum-time-difference.py | class Solution(object):
def findMinDifference(self, timePoints):
"""
:type timePoints: List[str]
:rtype: int
"""
timePoints = map(lambda x:int(x.split(':')[0]) * 60 + int(x.split(':')[1]), timePoints)
MINUTES_IN_A_DAY = 24 * 60
timePoints.sort()
m = ti... | Add py solution for 539. Minimum Time Difference | Add py solution for 539. Minimum Time Difference
539. Minimum Time Difference: https://leetcode.com/problems/minimum-time-difference/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | <INSERT> class Solution(object):
<INSERT_END> <INSERT> def findMinDifference(self, timePoints):
"""
:type timePoints: List[str]
:rtype: int
"""
timePoints = map(lambda x:int(x.split(':')[0]) * 60 + int(x.split(':')[1]), timePoints)
MINUTES_IN_A_DAY = 24 * 60
ti... | Add py solution for 539. Minimum Time Difference
539. Minimum Time Difference: https://leetcode.com/problems/minimum-time-difference/
| |
6ea29a21a2bfd077891fbea1f60b97e92c33a32c | gpxpandas/gpxreader.py | gpxpandas/gpxreader.py | __author__ = 'max'
import gpxpy
import pandas as pd
def parse_gpx(gpx_file_name):
return gpxpy.parse(gpx_file_name)
def data_frame_for_track_segment(segment):
seg_dict = {}
for point in segment.points:
seg_dict[point.time] = [point.latitude, point.longitude,
poi... | __author__ = 'max'
import gpxpy
import pandas as pd
def parse_gpx(gpx_file_name):
return gpxpy.parse(gpx_file_name)
def data_frame_for_track_segment(segment):
seg_dict = {}
for point in segment.points:
seg_dict[point.time] = [point.latitude, point.longitude,
poi... | Return to list generator to enable pandas cmd output | Return to list generator to enable pandas cmd output
| Python | mit | komax/gpx-pandas | <REPLACE_OLD> (data_frame_for_track_segment(segment)
<REPLACE_NEW> [data_frame_for_track_segment(segment)
<REPLACE_END> <REPLACE_OLD> track.segments)
<REPLACE_NEW> track.segments]
<REPLACE_END> <REPLACE_OLD> (track_segment_mapping(track) <REPLACE_NEW> [track_segment_mapping(track) <REPLACE_END> <REPLACE_OLD> gpx.tr... | Return to list generator to enable pandas cmd output
__author__ = 'max'
import gpxpy
import pandas as pd
def parse_gpx(gpx_file_name):
return gpxpy.parse(gpx_file_name)
def data_frame_for_track_segment(segment):
seg_dict = {}
for point in segment.points:
seg_dict[point.time] = [point.latitude... |
8a36070c76d1552e2d2e61c1e5c47202cc28b329 | basket/news/backends/common.py | basket/news/backends/common.py | from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=... | from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=... | Refactor the timing decorator to be less confusing | Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error.
| Python | mpl-2.0 | glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket | <REPLACE_OLD> time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
<REPLACE_NEW> time()
def record_timing():
<REPLACE_END> <INSERT> <INS... | Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error.
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterEx... |
1cc044e601dc6b6d2a5f62c7557a6cd2d5b50986 | homepage/views.py | homepage/views.py | from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api
def index(request):
uid = request.COOKIES.get("uid")
if not uid:
uid, data = api.create_new_user()
else:
data = api.get_saved_cities(uid)
resp... | from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api
def index(request):
uid = request.COOKIES.get("uid")
data = None
if not uid:
uid, _ = api.create_new_user()
else:
data = api.get_saved_cities(u... | Fix create user in homepage view. | Fix create user in homepage view.
api.create_new_user is returning the newly created user record, so we can't pass that as data to the template.
| Python | mit | c17r/tsace,c17r/tsace,c17r/tsace | <INSERT> data = None
<INSERT_END> <REPLACE_OLD> data <REPLACE_NEW> _ <REPLACE_END> <|endoftext|> from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api
def index(request):
uid = request.COOKIES.get("uid")
data = None
... | Fix create user in homepage view.
api.create_new_user is returning the newly created user record, so we can't pass that as data to the template.
from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api
def index(request):
uid ... |
91f503cd99dfa6fc6562afc1b627b6f8b0f1d91b | addons/l10n_ar/models/res_partner_bank.py | addons/l10n_ar/models/res_partner_bank.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
import stdnum.ar.cbu
def validate_cbu(cbu):
return stdnum.ar.cbu.validate(cbu)
class ResPartnerBank(models.Model):
_inherit = 'res.partner.bank'
@api.model
def _get_supported_account_types(se... | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
from odoo.exceptions import ValidationError
import stdnum.ar
import logging
_logger = logging.getLogger(__name__)
def validate_cbu(cbu):
try:
return stdnum.ar.cbu.validate(cbu)
except Exception a... | Fix ImportError: No module named 'stdnum.ar.cbu' | [FIX] l10n_ar: Fix ImportError: No module named 'stdnum.ar.cbu'
Since stdnum.ar.cbu is not available in odoo saas enviroment because is
using an old version of stdnum package, we add a try exept in order to
catch this and manage the error properly which is raise an exception and
leave a message in the log telling the ... | Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | <REPLACE_OLD> _
import stdnum.ar.cbu
def <REPLACE_NEW> _
from odoo.exceptions import ValidationError
import stdnum.ar
import logging
_logger = logging.getLogger(__name__)
def <REPLACE_END> <REPLACE_OLD> return stdnum.ar.cbu.validate(cbu)
class <REPLACE_NEW> try:
return stdnum.ar.cbu.validate(cbu)
exce... | [FIX] l10n_ar: Fix ImportError: No module named 'stdnum.ar.cbu'
Since stdnum.ar.cbu is not available in odoo saas enviroment because is
using an old version of stdnum package, we add a try exept in order to
catch this and manage the error properly which is raise an exception and
leave a message in the log telling the ... |
47348a032bf86aac563dca41703f1e39d03b2360 | aplpy/header.py | aplpy/header.py | from __future__ import absolute_import
def check(header, convention=None, dimensions=[0, 1]):
ix = dimensions[0] + 1
iy = dimensions[1] + 1
ctypex = header['CTYPE%i' % ix]
crvaly = header['CRVAL%i' % iy]
crpixy = header['CRPIX%i' % iy]
cdelty = header['CDELT%i' % iy]
# Check for CRVAL2!... | from __future__ import absolute_import
def check(header, convention=None, dimensions=[0, 1]):
ix = dimensions[0] + 1
iy = dimensions[1] + 1
ctypex = header['CTYPE%i' % ix]
crvaly = header['CRVAL%i' % iy]
# Check for CRVAL2!=0 for CAR projection
if ctypex[4:] == '-CAR' and crvaly != 0:
... | Fix check for Wells/Calabretta convention | Fix check for Wells/Calabretta convention | Python | mit | mwcraig/aplpy,allisony/aplpy | <DELETE> iy]
crpixy = header['CRPIX%i' % iy]
cdelty = header['CDELT%i' % <DELETE_END> <INSERT> try:
crpixy = header['CRPIX%i' % iy]
cdelty = header['CDELT%i' % iy]
except:
raise Exception("Need CDELT to be present for wel... | Fix check for Wells/Calabretta convention
from __future__ import absolute_import
def check(header, convention=None, dimensions=[0, 1]):
ix = dimensions[0] + 1
iy = dimensions[1] + 1
ctypex = header['CTYPE%i' % ix]
crvaly = header['CRVAL%i' % iy]
crpixy = header['CRPIX%i' % iy]
cdelty = heade... |
9fbfaac74b3213601ce48c73cd49a02344ba580b | setup.py | setup.py | from distutils.core import setup
import sisdb
setup (
name='sisdb',
version=sisdb.VERSION,
description='SIS ORM like library',
packages=['sisdb'],
install_requires=['sis >= 0.3.0']
)
| from distutils.core import setup
import sisdb
setup (
name='sisdb',
version=sisdb.VERSION,
description='SIS ORM like library',
packages=['sisdb'],
install_requires=['sispy >= 0.3.0']
)
| Update to require sispy instead of sis | Update to require sispy instead of sis | Python | bsd-3-clause | sis-cmdb/sis-db-python | <REPLACE_OLD> install_requires=['sis <REPLACE_NEW> install_requires=['sispy <REPLACE_END> <|endoftext|> from distutils.core import setup
import sisdb
setup (
name='sisdb',
version=sisdb.VERSION,
description='SIS ORM like library',
packages=['sisdb'],
install_requires=['sispy >= 0.3.0']
)
| Update to require sispy instead of sis
from distutils.core import setup
import sisdb
setup (
name='sisdb',
version=sisdb.VERSION,
description='SIS ORM like library',
packages=['sisdb'],
install_requires=['sis >= 0.3.0']
)
|
f896d0fa40250a580fee584217c5a4c1d39d7388 | snipper/snippet.py | snipper/snippet.py | import os
from os import path
import glob
import json
import subprocess
class Snippet(object):
def __init__(self, config, username, snippet_id):
self.config = config
self.username = username
self.snippet_id = snippet_id
repo_parent = path.join(self.config.get('snippet_home'), use... | import os
from os import path
import glob
import json
import subprocess
class Snippet(object):
def __init__(self, config, username, snippet_id):
self.config = config
self.username = username
self.snippet_id = snippet_id
repo_parent = path.join(self.config.get('snippet_home'), use... | Add doc string to Snippet.get_files | Add doc string to Snippet.get_files
| Python | mit | mesuutt/snipper | <INSERT> """ Return files of snippet """
<INSERT_END> <|endoftext|> import os
from os import path
import glob
import json
import subprocess
class Snippet(object):
def __init__(self, config, username, snippet_id):
self.config = config
self.username = username
self.snippet_id = sni... | Add doc string to Snippet.get_files
import os
from os import path
import glob
import json
import subprocess
class Snippet(object):
def __init__(self, config, username, snippet_id):
self.config = config
self.username = username
self.snippet_id = snippet_id
repo_parent = path.join... |
275c39faa02dc0bd4f8b9d9bd2a012eaee12a338 | nose2/tests/functional/test_coverage.py | nose2/tests/functional/test_coverage.py | import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 ... | import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 ... | Fix regex matching coverage output | Fix regex matching coverage output
The coverage library now returns the file extensions.
| Python | bsd-2-clause | ojengwa/nose2,ptthiem/nose2,ptthiem/nose2,little-dude/nose2,ojengwa/nose2,little-dude/nose2 | <REPLACE_OLD> 'mod1').replace('\\', <REPLACE_NEW> 'mod1.py').replace('\\', <REPLACE_END> <INSERT> <INSERT_END> <|endoftext|> import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_... | Fix regex matching coverage output
The coverage library now returns the file extensions.
import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
... |
d087e0cc47697e6b7f222de90a4143e3bb612a66 | radar/models/forms.py | radar/models/forms.py | from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy.dialects import postgresql
from radar.database import db
from radar.models.common import uuid_pk_column, MetaModelMixin, patient_id_column, patient_relationship
from radar.models.logs import log_cha... | from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy.dialects import postgresql
from radar.database import db
from radar.models.common import uuid_pk_column, MetaModelMixin, patient_id_column, patient_relationship
from radar.models.logs import log_cha... | Add index on patient id | Add index on patient id
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | <REPLACE_OLD> nullable=False)
class <REPLACE_NEW> nullable=False)
Index('entries_patient_idx', Entry.patient_id)
class <REPLACE_END> <|endoftext|> from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy.dialects import postgresql
from radar.da... | Add index on patient id
from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy.dialects import postgresql
from radar.database import db
from radar.models.common import uuid_pk_column, MetaModelMixin, patient_id_column, patient_relationship
from radar.m... |
df98c8bd70f25727810e6eb9d359cf1e14fd6645 | update_prices.py | update_prices.py | import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
ITEMS = [
34, # Tritanium
35, # Pyerite
36, # Mexallon
37, # Isogen
38, # Nocxium
39, # Zydrine
40, # Megacyte
11399, # Morphite
]
def main():
conn = sq... | import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
def main():
conn = sqlite3.connect('everdi.db')
cur = conn.cursor()
# Get all items used in current BlueprintInstances
cur.execute("""
SELECT DISTINCT c.item_id
... | Update prices for all BlueprintInstances we currently have | Update prices for all BlueprintInstances we currently have
| Python | bsd-2-clause | madcowfred/evething,Gillingham/evething,cmptrgeekken/evething,madcowfred/evething,cmptrgeekken/evething,cmptrgeekken/evething,cmptrgeekken/evething,madcowfred/evething,Gillingham/evething,madcowfred/evething,cmptrgeekken/evething,Gillingham/evething,Gillingham/evething | <REPLACE_OLD> 'http://api.eve-central.com/api/marketstat?hours=24&%s'
ITEMS = [
34, # Tritanium
35, # Pyerite
36, # Mexallon
37, # Isogen
38, # Nocxium
39, # Zydrine
40, # Megacyte
11399, # Morphite
]
def <REPLACE_NEW> 'http://api.eve-central.com/api/marketstat?hours=24&%s'
def <REPLACE_EN... | Update prices for all BlueprintInstances we currently have
import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
ITEMS = [
34, # Tritanium
35, # Pyerite
36, # Mexallon
37, # Isogen
38, # Nocxium
39, # Zydrine
40, # ... |
f0d629ae8b4568b2aceaf38779c8b07832e860b0 | teamspeak_web_utils.py | teamspeak_web_utils.py | import re
from bs4 import BeautifulSoup
import cfscrape
def nplstatus():
scraper = cfscrape.create_scraper()
data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
soup = BeautifulSoup(data, 'html.parser')
raw_status = soup.find_all(class_='register_linklabel')[2].span
return not r... | import re
from bs4 import BeautifulSoup
import cfscrape
def nplstatus():
scraper = cfscrape.create_scraper()
data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
soup = BeautifulSoup(data, 'html.parser')
raw_status = soup.find_all(class_='register_linklabel')[2].span
return not r... | Clean string returned by website | Clean string returned by website
=> remove newline-characters and strip
| Python | mit | Thor77/TeamspeakIRC | <REPLACE_OLD> find(class_='version').text
<REPLACE_NEW> find(class_='version').text
def clean(s):
<REPLACE_END> <REPLACE_OLD> search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit')
<REPLACE_NEW> s.replace('\n', '').strip()
return clean(search(r'Client\ 64\-bit')), \
clean(search(r'Server\ 64\-bi... | Clean string returned by website
=> remove newline-characters and strip
import re
from bs4 import BeautifulSoup
import cfscrape
def nplstatus():
scraper = cfscrape.create_scraper()
data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
soup = BeautifulSoup(data, 'html.parser')
raw_st... |
a3dc1ebac114d1591dd9cdb211e6d975a10b0da3 | education/management/commands/reschedule_teacher_weekly_polls.py | education/management/commands/reschedule_teacher_weekly_polls.py | '''
Created on Feb 21, 2013
@author: raybesiga
'''
from django.core.management.base import BaseCommand
from education.models import reschedule_teacher_weekly_polls
from optparse import OptionParser, make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option("-g", "... | Add new reschedule teacher weekly poll | Add new reschedule teacher weekly poll
| Python | bsd-3-clause | unicefuganda/edtrac,unicefuganda/edtrac,unicefuganda/edtrac | <INSERT> '''
Created on Feb 21, 2013
@author: raybesiga
'''
from django.core.management.base import BaseCommand
from education.models import reschedule_teacher_weekly_polls
from optparse import OptionParser, make_option
class Command(BaseCommand):
<INSERT_END> <INSERT>
option_list = BaseCommand.option_list +... | Add new reschedule teacher weekly poll
| |
349bb1ce2c15239ae3f9c066ed774b20369b9c0d | src/ggrc/settings/app_engine.py | src/ggrc/settings/app_engine.py | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FU... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FU... | Enable Calendar integration on App Engine deployments | Enable Calendar integration on App Engine deployments
| Python | apache-2.0 | NejcZupec/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,hyperNURb/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,vladan-m/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,vladan-m/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/... | <INSERT> True
CALENDAR_MECHANISM = <INSERT_END> <|endoftext|> # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
APP_ENGINE = True
EN... | Enable Calendar integration on App Engine deployments
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
APP_ENGINE = True
ENABLE_JA... |
fdc4f3bfc1c3e3aa6f6243f0e6bf200025a79103 | boto/pyami/scriptbase.py | boto/pyami/scriptbase.py | import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if ... | import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if ... | Add missing argument specification for cwd argument. | Add missing argument specification for cwd argument.
| Python | mit | kouk/boto,jamesls/boto,stevenbrichards/boto,serviceagility/boto,nikhilraog/boto,j-carl/boto,ryansb/boto,acourtney2015/boto,drbild/boto,revmischa/boto,ric03uec/boto,alfredodeza/boto,tpodowd/boto,clouddocx/boto,jindongh/boto,Pretio/boto,kouk/boto,lochiiconnectivity/boto,drbild/boto,zachmullen/boto,pfhayes/boto,podhmo/bot... | <REPLACE_OLD> cwd)
<REPLACE_NEW> cwd=cwd)
<REPLACE_END> <|endoftext|> import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
se... | Add missing argument specification for cwd argument.
import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__c... |
f2820ad7022c6db78186d04d11a1ded1f02fa7e6 | landlab/components/stream_power/examples/test_voronoi_sp.py | landlab/components/stream_power/examples/test_voronoi_sp.py | from landlab import VoronoiDelaunayGrid # , RasterModelGrid
from landlab.components.flow_routing.route_flow_dn import FlowRouter
from landlab.components.stream_power.stream_power import StreamPowerEroder
import numpy as np
x, y = np.random.rand(50), np.random.rand(50)
mg = VoronoiDelaunayGrid(x,y)
#mg = RasterModelGr... | Test driver for Voronoi stream power | Test driver for Voronoi stream power
What it says on the tin. Very simple.
| Python | mit | RondaStrauch/landlab,laijingtao/landlab,Carralex/landlab,cmshobe/landlab,Carralex/landlab,amandersillinois/landlab,ManuSchmi88/landlab,cmshobe/landlab,ManuSchmi88/landlab,SiccarPoint/landlab,SiccarPoint/landlab,landlab/landlab,landlab/landlab,Carralex/landlab,RondaStrauch/landlab,ManuSchmi88/landlab,csherwood-usgs/land... | <INSERT> from landlab import VoronoiDelaunayGrid <INSERT_END> <INSERT> # , RasterModelGrid
from landlab.components.flow_routing.route_flow_dn import FlowRouter
from landlab.components.stream_power.stream_power import StreamPowerEroder
import numpy as np
x, y = np.random.rand(50), np.random.rand(50)
mg = VoronoiDelauna... | Test driver for Voronoi stream power
What it says on the tin. Very simple.
| |
c64149d3b1bb4998bddd6c05c85f0b3129f47020 | pydbus/bus.py | pydbus/bus.py | from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin
class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, Pub... | from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin
class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, Pub... | Increase the default timeout to 1s. | Increase the default timeout to 1s.
| Python | lgpl-2.1 | LEW21/pydbus,LEW21/pydbus | <REPLACE_OLD> timeout=10):
self.con <REPLACE_NEW> timeout=1000):
self.con <REPLACE_END> <|endoftext|> from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication impo... | Increase the default timeout to 1s.
from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin
class Bus(ProxyMixin, OwnMixin, WatchMixin, Subs... |
8d35dad5fc63de919936d0407d105c36c87a1b14 | tests/test_no_extra_queries.py | tests/test_no_extra_queries.py | from nose.tools import assert_false
from mock import Mock, PropertyMock, patch
from .models import Photo
def test_dont_access_source():
"""
Touching the source may trigger an unneeded query.
See <https://github.com/matthewwithanm/django-imagekit/issues/295>
"""
pmock = PropertyMock()
pmock.__... | Add test to illustrate GH-295 | Add test to illustrate GH-295
| Python | bsd-3-clause | FundedByMe/django-imagekit,tawanda/django-imagekit,tawanda/django-imagekit,FundedByMe/django-imagekit | <INSERT> from nose.tools import assert_false
from mock import Mock, PropertyMock, patch
from .models import Photo
def test_dont_access_source():
<INSERT_END> <INSERT> """
Touching the source may trigger an unneeded query.
See <https://github.com/matthewwithanm/django-imagekit/issues/295>
"""
pmock... | Add test to illustrate GH-295
| |
b7f153a383dad71f272d8ef211deeb1c1a149f51 | kerze.py | kerze.py | from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
fillcolor(FARBE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward(GROESSE*30)
back(GROESSE*30)
left(90)
forward... | from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"
fillcolor(FARBE)
shape(SHAPE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward(GROESSE*30)
back(GROESS... | Resolve NameError, add changeable turtle shape constant. | Resolve NameError, add changeable turtle shape constant.
| Python | mit | luforst/adventskranz | <REPLACE_OLD> True
fillcolor(FARBE)
def <REPLACE_NEW> True
SHAPE = "turtle"
fillcolor(FARBE)
shape(SHAPE)
def <REPLACE_END> <REPLACE_OLD> Kerze
zeichneKerze(True)
hide()
<REPLACE_NEW> Kerze
zeichneKerze(True)
hideturtle()
<REPLACE_END> <|endoftext|> from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True... | Resolve NameError, add changeable turtle shape constant.
from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
fillcolor(FARBE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward... |
f4f65dd62e5f70a17cecbddf960fa7a0c9699820 | setup.py | setup.py | from setuptools import setup
long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files. It optimizes images without changing their look or visual quality
("losslessly").
It works on images in JPEG, GIF and PNG formats and will leave others
unchanged. Provides a seeml... | from setuptools import setup
long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files. It optimizes images without changing their look or visual quality
("losslessly").
It works on images in JPEG, GIF and PNG formats and will leave others
unchanged. Provides a seeml... | Use version 0.9 of pyimagediet | Use version 0.9 of pyimagediet
| Python | mit | samastur/image-diet2 | <REPLACE_OLD> 'pyimagediet>=0.5',
<REPLACE_NEW> 'pyimagediet>=0.9',
<REPLACE_END> <|endoftext|> from setuptools import setup
long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files. It optimizes images without changing their look or visual quality
("losslessly").
... | Use version 0.9 of pyimagediet
from setuptools import setup
long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files. It optimizes images without changing their look or visual quality
("losslessly").
It works on images in JPEG, GIF and PNG formats and will leave ot... |
d70f19106a7dc63182a3a0ea4fe6702eedc23322 | mlog/db.py | mlog/db.py | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TE... | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TE... | Add index to the message_id column | Add index to the message_id column
| Python | agpl-3.0 | fajran/mlog | <INSERT> c.execute(
'''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
ON email_log (message_id)
''')
<INSERT_END> <|endoftext|> import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
... | Add index to the message_id column
import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INT... |
34fbab0a31956af0572c31612f359608a8819360 | models/phase3_eval/assemble_cx.py | models/phase3_eval/assemble_cx.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assembler."""
stmts = ac.filter_belief(stm... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assembler."""
stmts = ac.filter_belief(stm... | Remove strip context for CX assembly | Remove strip context for CX assembly
| Python | bsd-2-clause | pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy | <REPLACE_OLD> ac.filter_top_level(stmts)
stmts = ac.strip_agent_context(stmts)
<REPLACE_NEW> ac.filter_top_level(stmts)
<REPLACE_END> <|endoftext|> from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers impor... | Remove strip context for CX assembly
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assemble... |
be70b1528f51385c8221b7337cdc8669f53fa1c6 | textblob/decorators.py | textblob/decorators.py | # -*- coding: utf-8 -*-
'''Custom decorators.'''
from __future__ import absolute_import
from textblob.exceptions import MissingCorpusException
class cached_property(object):
'''A property that is only computed once per instance and then replaces
itself with an ordinary attribute. Deleting the attribute reset... | # -*- coding: utf-8 -*-
'''Custom decorators.'''
from __future__ import absolute_import
from functools import wraps
from textblob.exceptions import MissingCorpusException
class cached_property(object):
'''A property that is only computed once per instance and then replaces
itself with an ordinary attribute. ... | Use wraps decorator for requires_nltk_corpus | Use wraps decorator for requires_nltk_corpus
| Python | mit | jcalbert/TextBlob,freakynit/TextBlob,nvoron23/TextBlob,IrisSteenhout/TextBlob,adelq/TextBlob,beni55/TextBlob,jonmcoe/TextBlob,dipeshtech/TextBlob,sargam111/python,sloria/TextBlob,Windy-Ground/TextBlob,laugustyniak/TextBlob | <INSERT> functools import wraps
from <INSERT_END> <INSERT> @wraps(func)
<INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
'''Custom decorators.'''
from __future__ import absolute_import
from functools import wraps
from textblob.exceptions import MissingCorpusException
class cached_property(object):
'''A pro... | Use wraps decorator for requires_nltk_corpus
# -*- coding: utf-8 -*-
'''Custom decorators.'''
from __future__ import absolute_import
from textblob.exceptions import MissingCorpusException
class cached_property(object):
'''A property that is only computed once per instance and then replaces
itself with an or... |
443456f94a92f1844b99965ffcf3679bd939d42c | tests/test_moving_eddies.py | tests/test_moving_eddies.py | from parcels import Particle, ParticleSet, JITParticle, JITParticleSet
from parcels import NEMOGrid, ParticleFile, AdvectionRK4
from argparse import ArgumentParser
pclasses = {'scipy': (Particle, ParticleSet),
'jit': (JITParticle, JITParticleSet)}
def moving_eddies(grid, npart, mode='jit', verbose=False... | Add simple test setup that follows two particles | MovingEddies: Add simple test setup that follows two particles
| Python | mit | OceanPARCELS/parcels,OceanPARCELS/parcels | <REPLACE_OLD> <REPLACE_NEW> from parcels import Particle, ParticleSet, JITParticle, JITParticleSet
from parcels import NEMOGrid, ParticleFile, AdvectionRK4
from argparse import ArgumentParser
pclasses = {'scipy': (Particle, ParticleSet),
'jit': (JITParticle, JITParticleSet)}
def moving_eddies(grid, npa... | MovingEddies: Add simple test setup that follows two particles
| |
02937272206a526ff62b164fc54a14c385eb6970 | common/lib/xmodule/xmodule/hidden_module.py | common/lib/xmodule/xmodule/hidden_module.py | from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
class HiddenModule(XModule):
def get_html(self):
if self.system.user_is_staff:
return "ERROR: This module is unknown--students will not see it at all"
else:
return ""
class HiddenDescriptor(... | from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
class HiddenModule(XModule):
def get_html(self):
if self.system.user_is_staff:
return u"ERROR: This module is unknown--students will not see it at all"
else:
return u""
class HiddenDescripto... | Return unicode string to pass assertion | hidden-module-unicode: Return unicode string to pass assertion
XBlock Fragments expect unicode strings, and fail on an assertion when
it isn't:
```
2013-11-14 07:55:50,774 ERROR 3788 [django.request] base.py:215 - Internal Server Error: /courses/TestU/TST101/now/courseware/41d55c576a574fde99319420228f7f88/5fef5794e34... | Python | agpl-3.0 | louyihua/edx-platform,Endika/edx-platform,mushtaqak/edx-platform,shubhdev/openedx,valtech-mooc/edx-platform,a-parhom/edx-platform,Livit/Livit.Learn.EdX,longmen21/edx-platform,knehez/edx-platform,shurihell/testasia,mbareta/edx-platform-ft,hkawasaki/kawasaki-aio8-1,Softmotions/edx-platform,kursitet/edx-platform,dsajkl/re... | <REPLACE_OLD> "ERROR: <REPLACE_NEW> u"ERROR: <REPLACE_END> <REPLACE_OLD> ""
class <REPLACE_NEW> u""
class <REPLACE_END> <|endoftext|> from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
class HiddenModule(XModule):
def get_html(self):
if self.system.user_is_staff:
... | hidden-module-unicode: Return unicode string to pass assertion
XBlock Fragments expect unicode strings, and fail on an assertion when
it isn't:
```
2013-11-14 07:55:50,774 ERROR 3788 [django.request] base.py:215 - Internal Server Error: /courses/TestU/TST101/now/courseware/41d55c576a574fde99319420228f7f88/5fef5794e34... |
c4278b404b313c4fa5fad67a5703b7368d1c4428 | fileapi/tests/test_qunit.py | fileapi/tests/test_qunit.py | import os
from django.conf import settings
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import override_settings
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriv... | import os
from django.conf import settings
from django.contrib.staticfiles import finders, storage
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import override_settings
from django.utils.functional import empty
from selenium import webdriver
from selenium.webdriver.co... | Clear global state/caching handled by Django so the test passes when run in the full suite. | Clear global state/caching handled by Django so the test passes when run in the full suite.
| Python | bsd-2-clause | mlavin/fileapi,mlavin/fileapi,mlavin/fileapi | <INSERT> django.contrib.staticfiles import finders, storage
from <INSERT_END> <REPLACE_OLD> override_settings
from <REPLACE_NEW> override_settings
from django.utils.functional import empty
from <REPLACE_END> <INSERT> def setUp(self):
# Clear the cache versions of the staticfiles finders and storage
... | Clear global state/caching handled by Django so the test passes when run in the full suite.
import os
from django.conf import settings
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import override_settings
from selenium import webdriver
from selenium.webdriver.common.... |
43d5c85a1b91719cabbc4a92bfd65feceb6cedfc | py/random-pick-index.py | py/random-pick-index.py | from random import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
meet = 0
choice =... | Add py solution for 398. Random Pick Index | Add py solution for 398. Random Pick Index
398. Random Pick Index: https://leetcode.com/problems/random-pick-index/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | <REPLACE_OLD> <REPLACE_NEW> from random import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
... | Add py solution for 398. Random Pick Index
398. Random Pick Index: https://leetcode.com/problems/random-pick-index/
| |
d7d9fcb260b85a3f785852239acaea6ccda1725a | what_meta/views.py | what_meta/views.py | from django.core import serializers
from django.http.response import HttpResponse
from what_meta.models import WhatTorrentGroup
def search_torrent_groups(request, query):
return HttpResponse(
serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)),
content_type='text... | from django.core import serializers
from django.http.response import HttpResponse
from what_meta.models import WhatTorrentGroup
def search_torrent_groups(request, query):
response = HttpResponse(
serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)),
content_type='... | Support for super simple player. | Support for super simple player.
| Python | mit | grandmasterchef/WhatManager2,davols/WhatManager2,MADindustries/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,karamanolev/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,karamanolev/WhatManager2,karamanolev/W... | <REPLACE_OLD> return <REPLACE_NEW> response = <REPLACE_END> <REPLACE_OLD> content_type='text/plain',
<REPLACE_NEW> content_type='text/json',
<REPLACE_END> <INSERT> response['Access-Control-Allow-Origin'] = '*'
return response
<INSERT_END> <|endoftext|> from django.core import serializers
from django.http.resp... | Support for super simple player.
from django.core import serializers
from django.http.response import HttpResponse
from what_meta.models import WhatTorrentGroup
def search_torrent_groups(request, query):
return HttpResponse(
serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=q... |
3750cc97ac69c160f908b9e47b52ed831c8d9170 | ka_find_missing_descs.py | ka_find_missing_descs.py | #!/usr/bin/env python3
from kapi import *
import utils
import argparse, sys
import time
import json
def read_cmd():
"""Reading command line options."""
desc = "Program for finding KA content without descriptions."
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-s','--subject', dest... | Add script for finding missing descriptions in KA content | Add script for finding missing descriptions in KA content
| Python | mit | danielhollas/AmaraUpload,danielhollas/AmaraUpload | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python3
from kapi import *
import utils
import argparse, sys
import time
import json
def read_cmd():
"""Reading command line options."""
desc = "Program for finding KA content without descriptions."
parser = argparse.ArgumentParser(description=desc)
parser.add_ar... | Add script for finding missing descriptions in KA content
| |
76edf4ea679ca3c117c7cff21e05f18044b5f51a | education/management/commands/schedule_all_scripts.py | education/management/commands/schedule_all_scripts.py | from django.core.management.base import BaseCommand
from education.scheduling import schedule_script
from script.models import Script
class Command(BaseCommand):
def handle(self, **options):
for script in Script.objects.all():
schedule_script(script)
self.stdout.write('Done!\n')
| Add a command for scheduling all scripts. | Add a command for scheduling all scripts.
| Python | bsd-3-clause | unicefuganda/edtrac,unicefuganda/edtrac,unicefuganda/edtrac | <INSERT> from django.core.management.base import BaseCommand
from education.scheduling import schedule_script
from script.models import Script
class Command(BaseCommand):
<INSERT_END> <INSERT> def handle(self, **options):
for script in Script.objects.all():
schedule_script(script)
self.... | Add a command for scheduling all scripts.
| |
1a776b7fd58f7936cf37ee5e0e4e1b2a4bf5ff3e | src/tempel/utils.py | src/tempel/utils.py | from django.conf import settings
languages = dict([(item['name'], item) for item in settings.TEMPEL_LANGUAGES])
def get_languages():
return sorted([(item['name'], item['label']) for item in languages.values()])
def get_language(name):
return languages[name]['label']
def get_mimetype(name):
return langua... | Add utility functions to query the languages | Add utility functions to query the languages
| Python | agpl-3.0 | fajran/tempel | <INSERT> from django.conf import settings
languages = dict([(item['name'], item) for item in settings.TEMPEL_LANGUAGES])
def get_languages():
<INSERT_END> <INSERT> return sorted([(item['name'], item['label']) for item in languages.values()])
def get_language(name):
return languages[name]['label']
def get_mim... | Add utility functions to query the languages
| |
ed8bf4ce4c8901af093e494cb6811a1ccf4660ba | website/tests/test_blog.py | website/tests/test_blog.py | ##
# Copyright (C) 2014 Jessica Tallon & Matt Molyneaux
#
# This file is part of Inboxen.
#
# Inboxen is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, o... | Test blog rendering and posting | Test blog rendering and posting
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen | <REPLACE_OLD> <REPLACE_NEW> ##
# Copyright (C) 2014 Jessica Tallon & Matt Molyneaux
#
# This file is part of Inboxen.
#
# Inboxen is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, eithe... | Test blog rendering and posting
| |
eef8498388c672b25344a3f6fd8c05166e4ed4f6 | xea_core/urls.py | xea_core/urls.py | """xea_core 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-ba... | """xea_core 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-ba... | Add namespace to jwt_knox URLs | Add namespace to jwt_knox URLs
| Python | agpl-3.0 | gpul-org/xea-core | <REPLACE_OLD> include('jwt_knox.urls')),
<REPLACE_NEW> include('jwt_knox.urls', namespace='jwt_knox')),
<REPLACE_END> <|endoftext|> """xea_core 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:
Funct... | Add namespace to jwt_knox URLs
"""xea_core 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'^$', v... |
cd0b6af73dd49b4da851a75232b5829b91b9030c | genome_designer/conf/demo_settings.py | genome_designer/conf/demo_settings.py | """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
... | """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
... | Allow refresh materialized view in DEMO_MODE. | Allow refresh materialized view in DEMO_MODE.
| Python | mit | woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone,churchlab/millstone,churchlab/millstone | <INSERT> 'main.xhr_handlers.refresh_materialized_variant_table',
<INSERT_END> <|endoftext|> """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.pro... | Allow refresh materialized view in DEMO_MODE.
"""
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
... |
bba016305982967610ee7bd8e08bd45a176dbc7e | alpha-vantage/alphavantage.py | alpha-vantage/alphavantage.py | try:
# Python 3 import
from urllib.request import urlopen
except ImportError:
# Python 2.* import
from urllib2 import urlopen
from simplejson import loads
class AlphaVantage:
"""
This class is in charge of creating a python interface between the Alpha
Vantage restful API and your p... | Create data request function to get json from the API | feat: Create data request function to get json from the API
| Python | mit | RomelTorres/alpha_vantage | <INSERT> try:
<INSERT_END> <INSERT> # Python 3 import
from urllib.request import urlopen
except ImportError:
# Python 2.* import
from urllib2 import urlopen
from simplejson import loads
class AlphaVantage:
"""
This class is in charge of creating a python interface between the Alpha
... | feat: Create data request function to get json from the API
| |
8337575314ae02e99eeded1ffb537a87a423b2c0 | spam/ansiInventory.py | spam/ansiInventory.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
AnsibleInventory:
INTRO:
USAGE:
"""
import os
import ansible.inventory
class AnsibleInventory(object):
'''
Ansible Inventory wrapper class.
'''
def __init__(self, inventory_filename):
'''
Initialize Inventory
'''
if... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
AnsibleInventory:
INTRO:
USAGE:
"""
import os
import ansible.inventory
class AnsibleInventory(object):
'''
Ansible Inventory wrapper class.
'''
def __init__(self, inventory_filename):
'''
Initialize Inventory
'''
if... | Make changes to get_hosts() to return a list of dict | Make changes to get_hosts() to return a list of dict
| Python | apache-2.0 | bdastur/spam,bdastur/spam | <REPLACE_OLD> if not group:
return self.inventory.hosts.keys()
<REPLACE_NEW> hostlist = []
for group in self.inventory.groups:
groupdict = {}
groupdict['group'] = group
groupdict['hostlist'] = []
<REPLACE_END> <REPLACE_OLD> self.inventory.groups.get(group, ... | Make changes to get_hosts() to return a list of dict
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
AnsibleInventory:
INTRO:
USAGE:
"""
import os
import ansible.inventory
class AnsibleInventory(object):
'''
Ansible Inventory wrapper class.
'''
def __init__(self, inventory_filename):
'... |
0451142ecede6f899b97b28114843413332e3f0b | scripts/nplm-training/averageNullEmbedding_baseline.py | scripts/nplm-training/averageNullEmbedding_baseline.py | #!/usr/bin/env python2
import sys
import numpy
import optparse
#sys.path.append('/data/tools/nplm/python')
parser = optparse.OptionParser("%prog [options]")
parser.add_option("-p", "--nplm-python-path", type="string", dest="nplm_python_path")
parser.add_option("-i", "--input-model", type="string", dest="input_model")
... | Add null token normalization for models to be used with the chart decoder. | Add null token normalization for models to be used with the chart decoder.
| Python | lgpl-2.1 | alvations/mosesdecoder,emjotde/mosesdecoder_nmt,moses-smt/mosesdecoder,alvations/mosesdecoder,moses-smt/mosesdecoder,KonceptGeek/mosesdecoder,moses-smt/mosesdecoder,KonceptGeek/mosesdecoder,KonceptGeek/mosesdecoder,hychyc07/mosesdecoder,KonceptGeek/mosesdecoder,moses-smt/mosesdecoder,alvations/mosesdecoder,tofula/moses... | <INSERT> #!/usr/bin/env python2
import sys
import numpy
import optparse
#sys.path.append('/data/tools/nplm/python')
parser = optparse.OptionParser("%prog [options]")
parser.add_option("-p", "--nplm-python-path", type="string", dest="nplm_python_path")
parser.add_option("-i", "--input-model", type="string", dest="input... | Add null token normalization for models to be used with the chart decoder.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.