commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 51
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
80524970b9e802787918af9ce6d25110be825df4 | moderngl/__init__.py | moderngl/__init__.py | '''
ModernGL: PyOpenGL alternative
'''
from .error import *
from .buffer import *
from .compute_shader import *
from .conditional_render import *
from .context import *
from .framebuffer import *
from .program import *
from .program_members import *
from .query import *
from .renderbuffer import *
from .scope import *
from .texture import *
from .texture_3d import *
from .texture_array import *
from .texture_cube import *
from .vertex_array import *
from .sampler import *
__version__ = '5.6.1'
| '''
ModernGL: High performance rendering for Python 3
'''
from .error import *
from .buffer import *
from .compute_shader import *
from .conditional_render import *
from .context import *
from .framebuffer import *
from .program import *
from .program_members import *
from .query import *
from .renderbuffer import *
from .scope import *
from .texture import *
from .texture_3d import *
from .texture_array import *
from .texture_cube import *
from .vertex_array import *
from .sampler import *
__version__ = '5.6.1'
| Update module level description of moderngl | Update module level description of moderngl
| Python | mit | cprogrammer1994/ModernGL,cprogrammer1994/ModernGL,cprogrammer1994/ModernGL | '''
- ModernGL: PyOpenGL alternative
+ ModernGL: High performance rendering for Python 3
'''
from .error import *
from .buffer import *
from .compute_shader import *
from .conditional_render import *
from .context import *
from .framebuffer import *
from .program import *
from .program_members import *
from .query import *
from .renderbuffer import *
from .scope import *
from .texture import *
from .texture_3d import *
from .texture_array import *
from .texture_cube import *
from .vertex_array import *
from .sampler import *
__version__ = '5.6.1'
| Update module level description of moderngl | ## Code Before:
'''
ModernGL: PyOpenGL alternative
'''
from .error import *
from .buffer import *
from .compute_shader import *
from .conditional_render import *
from .context import *
from .framebuffer import *
from .program import *
from .program_members import *
from .query import *
from .renderbuffer import *
from .scope import *
from .texture import *
from .texture_3d import *
from .texture_array import *
from .texture_cube import *
from .vertex_array import *
from .sampler import *
__version__ = '5.6.1'
## Instruction:
Update module level description of moderngl
## Code After:
'''
ModernGL: High performance rendering for Python 3
'''
from .error import *
from .buffer import *
from .compute_shader import *
from .conditional_render import *
from .context import *
from .framebuffer import *
from .program import *
from .program_members import *
from .query import *
from .renderbuffer import *
from .scope import *
from .texture import *
from .texture_3d import *
from .texture_array import *
from .texture_cube import *
from .vertex_array import *
from .sampler import *
__version__ = '5.6.1'
|
e4d5fa8c70dd283d4511f155da5be5835b1836f7 | tests/unit/test_validate.py | tests/unit/test_validate.py | import pytest
import mock
import synapseclient
from genie import validate
center = "SAGE"
syn = mock.create_autospec(synapseclient.Synapse)
@pytest.fixture(params=[
# tuple with (input, expectedOutput)
(["data_CNA_SAGE.txt"], "cna"),
(["data_clinical_supp_SAGE.txt"], "clinical"),
(["data_clinical_supp_sample_SAGE.txt",
"data_clinical_supp_patient_SAGE.txt"], "clinical")])
def filename_fileformat_map(request):
return request.param
def test_perfect_get_filetype(filename_fileformat_map):
(filepath_list, fileformat) = filename_fileformat_map
assert validate.determine_filetype(
syn, filepath_list, center) == fileformat
# def test_wrongfilename_get_filetype():
# assert input_to_database.get_filetype(syn, ['wrong.txt'], center) is None
| import pytest
import mock
import synapseclient
import pytest
from genie import validate
center = "SAGE"
syn = mock.create_autospec(synapseclient.Synapse)
@pytest.fixture(params=[
# tuple with (input, expectedOutput)
(["data_CNA_SAGE.txt"], "cna"),
(["data_clinical_supp_SAGE.txt"], "clinical"),
(["data_clinical_supp_sample_SAGE.txt",
"data_clinical_supp_patient_SAGE.txt"], "clinical")])
def filename_fileformat_map(request):
return request.param
def test_perfect_get_filetype(filename_fileformat_map):
(filepath_list, fileformat) = filename_fileformat_map
assert validate.determine_filetype(
syn, filepath_list, center) == fileformat
def test_wrongfilename_get_filetype():
with pytest.raises(
ValueError,
match="Your filename is incorrect! "
"Please change your filename before you run "
"the validator or specify --filetype if you are "
"running the validator locally"):
validate.determine_filetype(syn, ['wrong.txt'], center)
| Add in unit tests for validate.py | Add in unit tests for validate.py
| Python | mit | thomasyu888/Genie,thomasyu888/Genie,thomasyu888/Genie,thomasyu888/Genie | import pytest
import mock
import synapseclient
+ import pytest
from genie import validate
center = "SAGE"
syn = mock.create_autospec(synapseclient.Synapse)
@pytest.fixture(params=[
# tuple with (input, expectedOutput)
(["data_CNA_SAGE.txt"], "cna"),
(["data_clinical_supp_SAGE.txt"], "clinical"),
(["data_clinical_supp_sample_SAGE.txt",
"data_clinical_supp_patient_SAGE.txt"], "clinical")])
def filename_fileformat_map(request):
return request.param
def test_perfect_get_filetype(filename_fileformat_map):
(filepath_list, fileformat) = filename_fileformat_map
assert validate.determine_filetype(
syn, filepath_list, center) == fileformat
- # def test_wrongfilename_get_filetype():
+ def test_wrongfilename_get_filetype():
- # assert input_to_database.get_filetype(syn, ['wrong.txt'], center) is None
+ with pytest.raises(
+ ValueError,
+ match="Your filename is incorrect! "
+ "Please change your filename before you run "
+ "the validator or specify --filetype if you are "
+ "running the validator locally"):
+ validate.determine_filetype(syn, ['wrong.txt'], center)
| Add in unit tests for validate.py | ## Code Before:
import pytest
import mock
import synapseclient
from genie import validate
center = "SAGE"
syn = mock.create_autospec(synapseclient.Synapse)
@pytest.fixture(params=[
# tuple with (input, expectedOutput)
(["data_CNA_SAGE.txt"], "cna"),
(["data_clinical_supp_SAGE.txt"], "clinical"),
(["data_clinical_supp_sample_SAGE.txt",
"data_clinical_supp_patient_SAGE.txt"], "clinical")])
def filename_fileformat_map(request):
return request.param
def test_perfect_get_filetype(filename_fileformat_map):
(filepath_list, fileformat) = filename_fileformat_map
assert validate.determine_filetype(
syn, filepath_list, center) == fileformat
# def test_wrongfilename_get_filetype():
# assert input_to_database.get_filetype(syn, ['wrong.txt'], center) is None
## Instruction:
Add in unit tests for validate.py
## Code After:
import pytest
import mock
import synapseclient
import pytest
from genie import validate
center = "SAGE"
syn = mock.create_autospec(synapseclient.Synapse)
@pytest.fixture(params=[
# tuple with (input, expectedOutput)
(["data_CNA_SAGE.txt"], "cna"),
(["data_clinical_supp_SAGE.txt"], "clinical"),
(["data_clinical_supp_sample_SAGE.txt",
"data_clinical_supp_patient_SAGE.txt"], "clinical")])
def filename_fileformat_map(request):
return request.param
def test_perfect_get_filetype(filename_fileformat_map):
(filepath_list, fileformat) = filename_fileformat_map
assert validate.determine_filetype(
syn, filepath_list, center) == fileformat
def test_wrongfilename_get_filetype():
with pytest.raises(
ValueError,
match="Your filename is incorrect! "
"Please change your filename before you run "
"the validator or specify --filetype if you are "
"running the validator locally"):
validate.determine_filetype(syn, ['wrong.txt'], center)
|
0180aead701820d2de140791c3e271b4b8a7d231 | tests/__init__.py | tests/__init__.py | import os
def fixture_response(path):
return open(os.path.join(
os.path.dirname(__file__),
'fixtures',
path)).read()
| import os
def fixture_response(path):
with open(os.path.join(os.path.dirname(__file__),
'fixtures',
path)) as fixture:
return fixture.read()
| Fix file handlers being left open for fixtures | Fix file handlers being left open for fixtures
| Python | mit | accepton/accepton-python | import os
def fixture_response(path):
- return open(os.path.join(
- os.path.dirname(__file__),
- 'fixtures',
- path)).read()
+ with open(os.path.join(os.path.dirname(__file__),
+ 'fixtures',
+ path)) as fixture:
+ return fixture.read()
| Fix file handlers being left open for fixtures | ## Code Before:
import os
def fixture_response(path):
return open(os.path.join(
os.path.dirname(__file__),
'fixtures',
path)).read()
## Instruction:
Fix file handlers being left open for fixtures
## Code After:
import os
def fixture_response(path):
with open(os.path.join(os.path.dirname(__file__),
'fixtures',
path)) as fixture:
return fixture.read()
|
d07bf029b7ba9b5ef1f494d119a2eca004c1818a | tests/basics/list_slice_3arg.py | tests/basics/list_slice_3arg.py | x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
| x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
x = list(range(9))
print(x[::-1])
print(x[::2])
print(x[::-2])
| Add small testcase for 3-arg slices. | tests: Add small testcase for 3-arg slices.
| Python | mit | neilh10/micropython,danicampora/micropython,tuc-osg/micropython,noahchense/micropython,ahotam/micropython,alex-march/micropython,SungEun-Steve-Kim/test-mp,suda/micropython,SungEun-Steve-Kim/test-mp,noahwilliamsson/micropython,neilh10/micropython,aethaniel/micropython,noahwilliamsson/micropython,chrisdearman/micropython,redbear/micropython,AriZuu/micropython,praemdonck/micropython,ceramos/micropython,firstval/micropython,rubencabrera/micropython,selste/micropython,pozetroninc/micropython,galenhz/micropython,omtinez/micropython,dmazzella/micropython,turbinenreiter/micropython,vriera/micropython,toolmacher/micropython,kostyll/micropython,hiway/micropython,SungEun-Steve-Kim/test-mp,ernesto-g/micropython,xyb/micropython,ernesto-g/micropython,dxxb/micropython,kostyll/micropython,vitiral/micropython,PappaPeppar/micropython,dmazzella/micropython,TDAbboud/micropython,matthewelse/micropython,lbattraw/micropython,xyb/micropython,stonegithubs/micropython,orionrobots/micropython,kerneltask/micropython,ChuckM/micropython,selste/micropython,omtinez/micropython,rubencabrera/micropython,xuxiaoxin/micropython,alex-march/micropython,xhat/micropython,jlillest/micropython,kostyll/micropython,cloudformdesign/micropython,infinnovation/micropython,blazewicz/micropython,deshipu/micropython,hosaka/micropython,feilongfl/micropython,henriknelson/micropython,adafruit/micropython,Peetz0r/micropython-esp32,mgyenik/micropython,hiway/micropython,Vogtinator/micropython,alex-robbins/micropython,mianos/micropython,martinribelotta/micropython,jmarcelino/pycom-micropython,pfalcon/micropython,pramasoul/micropython,HenrikSolver/micropython,skybird6672/micropython,suda/micropython,kostyll/micropython,pfalcon/micropython,puuu/micropython,tralamazza/micropython,blazewicz/micropython,ruffy91/micropython,Timmenem/micropython,heisewangluo/micropython,Timmenem/micropython,xuxiaoxin/micropython,jmarcelino/pycom-micropython,pfalcon/micropython,oopy/micropython,puuu/micropython,adafruit/circuitpython,tdautc19841202/micropython,torwag/micropython,paul-xxx/micropython,KISSMonX/micropython,suda/micropython,PappaPeppar/micropython,skybird6672/micropython,orionrobots/micropython,dxxb/micropython,skybird6672/micropython,lbattraw/micropython,alex-robbins/micropython,xuxiaoxin/micropython,drrk/micropython,cloudformdesign/micropython,slzatz/micropython,ruffy91/micropython,danicampora/micropython,heisewangluo/micropython,SungEun-Steve-Kim/test-mp,emfcamp/micropython,ericsnowcurrently/micropython,hosaka/micropython,ahotam/micropython,MrSurly/micropython-esp32,misterdanb/micropython,xuxiaoxin/micropython,lowRISC/micropython,xyb/micropython,deshipu/micropython,cwyark/micropython,jimkmc/micropython,trezor/micropython,supergis/micropython,kostyll/micropython,deshipu/micropython,jmarcelino/pycom-micropython,mgyenik/micropython,AriZuu/micropython,praemdonck/micropython,ganshun666/micropython,rubencabrera/micropython,trezor/micropython,vitiral/micropython,danicampora/micropython,EcmaXp/micropython,ceramos/micropython,TDAbboud/micropython,micropython/micropython-esp32,orionrobots/micropython,lbattraw/micropython,supergis/micropython,galenhz/micropython,redbear/micropython,toolmacher/micropython,ceramos/micropython,cnoviello/micropython,paul-xxx/micropython,dhylands/micropython,EcmaXp/micropython,tralamazza/micropython,Vogtinator/micropython,rubencabrera/micropython,noahwilliamsson/micropython,bvernoux/micropython,hosaka/micropython,mhoffma/micropython,selste/micropython,heisewangluo/micropython,xhat/micropython,warner83/micropython,methoxid/micropystat,vitiral/micropython,supergis/micropython,praemdonck/micropython,utopiaprince/micropython,noahchense/micropython,tdautc19841202/micropython,oopy/micropython,pozetroninc/micropython,torwag/micropython,deshipu/micropython,HenrikSolver/micropython,feilongfl/micropython,ganshun666/micropython,swegener/micropython,torwag/micropython,aethaniel/micropython,EcmaXp/micropython,oopy/micropython,swegener/micropython,xhat/micropython,tdautc19841202/micropython,heisewangluo/micropython,tdautc19841202/micropython,deshipu/micropython,ryannathans/micropython,paul-xxx/micropython,danicampora/micropython,toolmacher/micropython,ryannathans/micropython,blazewicz/micropython,galenhz/micropython,xhat/micropython,hosaka/micropython,noahwilliamsson/micropython,mgyenik/micropython,toolmacher/micropython,mpalomer/micropython,xyb/micropython,ChuckM/micropython,Timmenem/micropython,supergis/micropython,ernesto-g/micropython,misterdanb/micropython,MrSurly/micropython-esp32,ryannathans/micropython,swegener/micropython,KISSMonX/micropython,vriera/micropython,alex-robbins/micropython,matthewelse/micropython,danicampora/micropython,mgyenik/micropython,KISSMonX/micropython,suda/micropython,tuc-osg/micropython,warner83/micropython,blazewicz/micropython,slzatz/micropython,mhoffma/micropython,AriZuu/micropython,dxxb/micropython,Vogtinator/micropython,drrk/micropython,tuc-osg/micropython,tuc-osg/micropython,cnoviello/micropython,tobbad/micropython,jimkmc/micropython,blmorris/micropython,alex-march/micropython,adamkh/micropython,heisewangluo/micropython,adamkh/micropython,cloudformdesign/micropython,pramasoul/micropython,firstval/micropython,stonegithubs/micropython,torwag/micropython,ChuckM/micropython,Peetz0r/micropython-esp32,ganshun666/micropython,MrSurly/micropython,AriZuu/micropython,methoxid/micropystat,swegener/micropython,adafruit/circuitpython,skybird6672/micropython,blazewicz/micropython,ceramos/micropython,Timmenem/micropython,neilh10/micropython,mhoffma/micropython,paul-xxx/micropython,emfcamp/micropython,EcmaXp/micropython,neilh10/micropython,lbattraw/micropython,Peetz0r/micropython-esp32,infinnovation/micropython,galenhz/micropython,kerneltask/micropython,cnoviello/micropython,feilongfl/micropython,toolmacher/micropython,emfcamp/micropython,EcmaXp/micropython,praemdonck/micropython,alex-robbins/micropython,matthewelse/micropython,utopiaprince/micropython,vriera/micropython,adafruit/micropython,micropython/micropython-esp32,blmorris/micropython,stonegithubs/micropython,ericsnowcurrently/micropython,lowRISC/micropython,emfcamp/micropython,tdautc19841202/micropython,dhylands/micropython,bvernoux/micropython,dinau/micropython,oopy/micropython,PappaPeppar/micropython,MrSurly/micropython,alex-march/micropython,warner83/micropython,aethaniel/micropython,TDAbboud/micropython,Timmenem/micropython,aethaniel/micropython,SungEun-Steve-Kim/test-mp,dxxb/micropython,mianos/micropython,ernesto-g/micropython,jlillest/micropython,trezor/micropython,tobbad/micropython,redbear/micropython,cnoviello/micropython,xuxiaoxin/micropython,HenrikSolver/micropython,redbear/micropython,omtinez/micropython,hiway/micropython,SHA2017-badge/micropython-esp32,ganshun666/micropython,blmorris/micropython,dinau/micropython,emfcamp/micropython,cnoviello/micropython,ryannathans/micropython,kerneltask/micropython,redbear/micropython,infinnovation/micropython,adafruit/micropython,henriknelson/micropython,ericsnowcurrently/micropython,paul-xxx/micropython,kerneltask/micropython,misterdanb/micropython,jlillest/micropython,pramasoul/micropython,vriera/micropython,noahwilliamsson/micropython,ceramos/micropython,dinau/micropython,dmazzella/micropython,swegener/micropython,ernesto-g/micropython,mgyenik/micropython,mpalomer/micropython,ahotam/micropython,skybird6672/micropython,noahchense/micropython,ahotam/micropython,pfalcon/micropython,mhoffma/micropython,blmorris/micropython,xyb/micropython,micropython/micropython-esp32,dinau/micropython,noahchense/micropython,lbattraw/micropython,puuu/micropython,jmarcelino/pycom-micropython,misterdanb/micropython,turbinenreiter/micropython,matthewelse/micropython,martinribelotta/micropython,tobbad/micropython,warner83/micropython,adamkh/micropython,tobbad/micropython,alex-march/micropython,bvernoux/micropython,slzatz/micropython,ruffy91/micropython,adafruit/micropython,chrisdearman/micropython,SHA2017-badge/micropython-esp32,praemdonck/micropython,mianos/micropython,mpalomer/micropython,MrSurly/micropython-esp32,HenrikSolver/micropython,feilongfl/micropython,turbinenreiter/micropython,torwag/micropython,jlillest/micropython,drrk/micropython,henriknelson/micropython,alex-robbins/micropython,firstval/micropython,AriZuu/micropython,SHA2017-badge/micropython-esp32,cwyark/micropython,puuu/micropython,orionrobots/micropython,pramasoul/micropython,martinribelotta/micropython,feilongfl/micropython,adafruit/circuitpython,TDAbboud/micropython,mhoffma/micropython,hosaka/micropython,MrSurly/micropython-esp32,TDAbboud/micropython,puuu/micropython,firstval/micropython,misterdanb/micropython,Peetz0r/micropython-esp32,utopiaprince/micropython,pozetroninc/micropython,lowRISC/micropython,infinnovation/micropython,mianos/micropython,trezor/micropython,drrk/micropython,dinau/micropython,neilh10/micropython,adafruit/circuitpython,PappaPeppar/micropython,micropython/micropython-esp32,HenrikSolver/micropython,adafruit/circuitpython,mianos/micropython,methoxid/micropystat,adafruit/micropython,jimkmc/micropython,chrisdearman/micropython,Vogtinator/micropython,cwyark/micropython,ericsnowcurrently/micropython,utopiaprince/micropython,chrisdearman/micropython,MrSurly/micropython,slzatz/micropython,henriknelson/micropython,aethaniel/micropython,blmorris/micropython,MrSurly/micropython,matthewelse/micropython,cwyark/micropython,dhylands/micropython,kerneltask/micropython,vitiral/micropython,selste/micropython,ahotam/micropython,vitiral/micropython,suda/micropython,orionrobots/micropython,ChuckM/micropython,dxxb/micropython,cloudformdesign/micropython,mpalomer/micropython,adamkh/micropython,adafruit/circuitpython,chrisdearman/micropython,supergis/micropython,jlillest/micropython,stonegithubs/micropython,selste/micropython,trezor/micropython,ruffy91/micropython,jimkmc/micropython,xhat/micropython,mpalomer/micropython,pfalcon/micropython,cwyark/micropython,tobbad/micropython,micropython/micropython-esp32,MrSurly/micropython,omtinez/micropython,pozetroninc/micropython,ruffy91/micropython,infinnovation/micropython,SHA2017-badge/micropython-esp32,omtinez/micropython,dhylands/micropython,oopy/micropython,adamkh/micropython,martinribelotta/micropython,ChuckM/micropython,bvernoux/micropython,henriknelson/micropython,Peetz0r/micropython-esp32,turbinenreiter/micropython,matthewelse/micropython,KISSMonX/micropython,methoxid/micropystat,dhylands/micropython,dmazzella/micropython,PappaPeppar/micropython,jmarcelino/pycom-micropython,firstval/micropython,hiway/micropython,ryannathans/micropython,lowRISC/micropython,tralamazza/micropython,lowRISC/micropython,vriera/micropython,turbinenreiter/micropython,warner83/micropython,utopiaprince/micropython,pozetroninc/micropython,drrk/micropython,bvernoux/micropython,martinribelotta/micropython,ganshun666/micropython,rubencabrera/micropython,MrSurly/micropython-esp32,galenhz/micropython,noahchense/micropython,cloudformdesign/micropython,tuc-osg/micropython,SHA2017-badge/micropython-esp32,KISSMonX/micropython,methoxid/micropystat,pramasoul/micropython,Vogtinator/micropython,hiway/micropython,ericsnowcurrently/micropython,slzatz/micropython,stonegithubs/micropython,tralamazza/micropython,jimkmc/micropython | x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
+ x = list(range(9))
+ print(x[::-1])
+ print(x[::2])
+ print(x[::-2])
+ | Add small testcase for 3-arg slices. | ## Code Before:
x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
## Instruction:
Add small testcase for 3-arg slices.
## Code After:
x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
x = list(range(9))
print(x[::-1])
print(x[::2])
print(x[::-2])
|
2a43183f5d2c14bacb92fe563d3c2ddf61b116da | tests/testMain.py | tests/testMain.py | import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Install/toolbox', '../Install']
addLocalPaths(import_paths)
class TestBpiScript(unittest.TestCase):
from scripts import bpi
def testBpiImport(self, method=bpi):
self.assertRaises(ValueError, method.main(), None)
def testBpiRun(self):
pass
class TestStandardizeBpiGridsScript(unittest.TestCase):
from scripts import standardize_bpi_grids
def testStdImport(self, method=standardize_bpi_grids):
pass
def testStdRun(self):
pass
class TestBtmDocument(unittest.TestCase):
# XXX this won't automatically get the right thing... how can we fix it?
import utils
def testXMLDocumentExists(self):
self.assertTrue(os.path.exists(xml_doc))
if __name__ == '__main__':
unittest.main()
| import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Install/toolbox', '../Install']
addLocalPaths(import_paths)
class TestBpiScript(unittest.TestCase):
from scripts import bpi
def testBpiImport(self, method=bpi):
self.assertRaises(ValueError, method.main(), None)
def testBpiRun(self):
pass
class TestStandardizeBpiGridsScript(unittest.TestCase):
from scripts import standardize_bpi_grids
def testStdImport(self, method=standardize_bpi_grids):
pass
def testStdRun(self):
pass
class TestBtmDocument(unittest.TestCase):
# XXX this won't automatically get the right thing... how can we fix it?
import utils
def testXmlDocumentExists(self):
self.assertTrue(os.path.exists(xml_doc))
def testCsvDocumentExists(self):
self.assertTrue(os.path.exists(csv_doc))
if __name__ == '__main__':
unittest.main()
| Make naming consistent with our standard (camelcase always, even with acronymn) | Make naming consistent with our standard (camelcase always, even with acronymn)
| Python | mpl-2.0 | EsriOceans/btm | import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Install/toolbox', '../Install']
addLocalPaths(import_paths)
class TestBpiScript(unittest.TestCase):
from scripts import bpi
def testBpiImport(self, method=bpi):
self.assertRaises(ValueError, method.main(), None)
def testBpiRun(self):
pass
class TestStandardizeBpiGridsScript(unittest.TestCase):
from scripts import standardize_bpi_grids
def testStdImport(self, method=standardize_bpi_grids):
pass
def testStdRun(self):
pass
class TestBtmDocument(unittest.TestCase):
# XXX this won't automatically get the right thing... how can we fix it?
import utils
- def testXMLDocumentExists(self):
+ def testXmlDocumentExists(self):
self.assertTrue(os.path.exists(xml_doc))
+
+ def testCsvDocumentExists(self):
+ self.assertTrue(os.path.exists(csv_doc))
if __name__ == '__main__':
unittest.main()
| Make naming consistent with our standard (camelcase always, even with acronymn) | ## Code Before:
import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Install/toolbox', '../Install']
addLocalPaths(import_paths)
class TestBpiScript(unittest.TestCase):
from scripts import bpi
def testBpiImport(self, method=bpi):
self.assertRaises(ValueError, method.main(), None)
def testBpiRun(self):
pass
class TestStandardizeBpiGridsScript(unittest.TestCase):
from scripts import standardize_bpi_grids
def testStdImport(self, method=standardize_bpi_grids):
pass
def testStdRun(self):
pass
class TestBtmDocument(unittest.TestCase):
# XXX this won't automatically get the right thing... how can we fix it?
import utils
def testXMLDocumentExists(self):
self.assertTrue(os.path.exists(xml_doc))
if __name__ == '__main__':
unittest.main()
## Instruction:
Make naming consistent with our standard (camelcase always, even with acronymn)
## Code After:
import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Install/toolbox', '../Install']
addLocalPaths(import_paths)
class TestBpiScript(unittest.TestCase):
from scripts import bpi
def testBpiImport(self, method=bpi):
self.assertRaises(ValueError, method.main(), None)
def testBpiRun(self):
pass
class TestStandardizeBpiGridsScript(unittest.TestCase):
from scripts import standardize_bpi_grids
def testStdImport(self, method=standardize_bpi_grids):
pass
def testStdRun(self):
pass
class TestBtmDocument(unittest.TestCase):
# XXX this won't automatically get the right thing... how can we fix it?
import utils
def testXmlDocumentExists(self):
self.assertTrue(os.path.exists(xml_doc))
def testCsvDocumentExists(self):
self.assertTrue(os.path.exists(csv_doc))
if __name__ == '__main__':
unittest.main()
|
3bce013c51c454721de3a868ea6d8e8c6d335112 | cycli/neo4j.py | cycli/neo4j.py | import requests
from py2neo import Graph, authenticate
class Neo4j:
def __init__(self, host, port, username=None, password=None):
self.host = host
self.port = port
self.username = username
self.password = password
self.host_port = "{host}:{port}".format(host=host, port=port)
self.url = "http://{host_port}/db/data/".format(host_port=self.host_port)
def connection(self):
if self.username and self.password:
authenticate(self.host_port, self.username, self.password)
graph = Graph(self.url)
return graph
def cypher(self, query):
tx = self.connection().cypher.begin()
try:
tx.append(query)
results = tx.process()
tx.commit()
except Exception as e:
results = e
except KeyboardInterrupt:
tx.rollback()
results = ""
return results
def labels(self):
return sorted(list(self.connection().node_labels))
def relationship_types(self):
return sorted(list(self.connection().relationship_types))
def properties(self):
url = self.url + "propertykeys"
r = requests.get(url, auth=(self.username, self.password))
props = r.json()
return sorted(props)
| import requests
from py2neo import Graph, authenticate
class Neo4j:
def __init__(self, host, port, username=None, password=None):
self.username = username
self.password = password
self.host_port = "{host}:{port}".format(host=host, port=port)
self.url = "http://{host_port}/db/data/".format(host_port=self.host_port)
def connection(self):
if self.username and self.password:
authenticate(self.host_port, self.username, self.password)
graph = Graph(self.url)
return graph
def cypher(self, query):
tx = self.connection().cypher.begin()
try:
tx.append(query)
results = tx.process()
tx.commit()
except Exception as e:
results = e
except KeyboardInterrupt:
tx.rollback()
results = ""
return results
def labels(self):
return sorted(list(self.connection().node_labels))
def relationship_types(self):
return sorted(list(self.connection().relationship_types))
def properties(self):
url = self.url + "propertykeys"
r = requests.get(url, auth=(self.username, self.password))
props = r.json()
return sorted(props)
| Remove host and port attributes from Neo4j | Remove host and port attributes from Neo4j
| Python | mit | nicolewhite/cycli,nicolewhite/cycli | import requests
from py2neo import Graph, authenticate
class Neo4j:
def __init__(self, host, port, username=None, password=None):
- self.host = host
- self.port = port
self.username = username
self.password = password
self.host_port = "{host}:{port}".format(host=host, port=port)
self.url = "http://{host_port}/db/data/".format(host_port=self.host_port)
def connection(self):
if self.username and self.password:
authenticate(self.host_port, self.username, self.password)
graph = Graph(self.url)
return graph
def cypher(self, query):
tx = self.connection().cypher.begin()
try:
tx.append(query)
results = tx.process()
tx.commit()
except Exception as e:
results = e
except KeyboardInterrupt:
tx.rollback()
results = ""
return results
def labels(self):
return sorted(list(self.connection().node_labels))
def relationship_types(self):
return sorted(list(self.connection().relationship_types))
def properties(self):
url = self.url + "propertykeys"
r = requests.get(url, auth=(self.username, self.password))
props = r.json()
return sorted(props)
| Remove host and port attributes from Neo4j | ## Code Before:
import requests
from py2neo import Graph, authenticate
class Neo4j:
def __init__(self, host, port, username=None, password=None):
self.host = host
self.port = port
self.username = username
self.password = password
self.host_port = "{host}:{port}".format(host=host, port=port)
self.url = "http://{host_port}/db/data/".format(host_port=self.host_port)
def connection(self):
if self.username and self.password:
authenticate(self.host_port, self.username, self.password)
graph = Graph(self.url)
return graph
def cypher(self, query):
tx = self.connection().cypher.begin()
try:
tx.append(query)
results = tx.process()
tx.commit()
except Exception as e:
results = e
except KeyboardInterrupt:
tx.rollback()
results = ""
return results
def labels(self):
return sorted(list(self.connection().node_labels))
def relationship_types(self):
return sorted(list(self.connection().relationship_types))
def properties(self):
url = self.url + "propertykeys"
r = requests.get(url, auth=(self.username, self.password))
props = r.json()
return sorted(props)
## Instruction:
Remove host and port attributes from Neo4j
## Code After:
import requests
from py2neo import Graph, authenticate
class Neo4j:
def __init__(self, host, port, username=None, password=None):
self.username = username
self.password = password
self.host_port = "{host}:{port}".format(host=host, port=port)
self.url = "http://{host_port}/db/data/".format(host_port=self.host_port)
def connection(self):
if self.username and self.password:
authenticate(self.host_port, self.username, self.password)
graph = Graph(self.url)
return graph
def cypher(self, query):
tx = self.connection().cypher.begin()
try:
tx.append(query)
results = tx.process()
tx.commit()
except Exception as e:
results = e
except KeyboardInterrupt:
tx.rollback()
results = ""
return results
def labels(self):
return sorted(list(self.connection().node_labels))
def relationship_types(self):
return sorted(list(self.connection().relationship_types))
def properties(self):
url = self.url + "propertykeys"
r = requests.get(url, auth=(self.username, self.password))
props = r.json()
return sorted(props)
|
70c9deb44cbbce13fbe094640786398cb4683b08 | ldap_sync/tasks.py | ldap_sync/tasks.py | from django.core.management import call_command
from celery import task
@task
def syncldap():
"""
Call the appropriate management command to synchronize the LDAP users
with the local database.
"""
call_command('syncldap')
| from django.core.management import call_command
from celery import shared_task
@shared_task
def syncldap():
"""
Call the appropriate management command to synchronize the LDAP users
with the local database.
"""
call_command('syncldap')
| Change Celery task to shared task | Change Celery task to shared task
| Python | bsd-3-clause | alexsilva/django-ldap-sync,jbittel/django-ldap-sync,PGower/django-ldap3-sync,alexsilva/django-ldap-sync | from django.core.management import call_command
- from celery import task
+ from celery import shared_task
- @task
+ @shared_task
def syncldap():
"""
Call the appropriate management command to synchronize the LDAP users
with the local database.
"""
call_command('syncldap')
| Change Celery task to shared task | ## Code Before:
from django.core.management import call_command
from celery import task
@task
def syncldap():
"""
Call the appropriate management command to synchronize the LDAP users
with the local database.
"""
call_command('syncldap')
## Instruction:
Change Celery task to shared task
## Code After:
from django.core.management import call_command
from celery import shared_task
@shared_task
def syncldap():
"""
Call the appropriate management command to synchronize the LDAP users
with the local database.
"""
call_command('syncldap')
|
026fade3f064f0185fa3a6f2075d43353e041970 | whois-scraper.py | whois-scraper.py | from lxml import html
from PIL import Image
import requests
def enlarge_image(image_file):
image = Image.open(image_file)
enlarged_size = map(lambda x: x*2, image.size)
enlarged_image = image.resize(enlarged_size)
return enlarged_image
def extract_text(image_file):
image = enlarge_image(image_file)
# Use Tesseract to extract text from the enlarged image. Then Return it.
domain = 'speedtest.net'
page = requests.get('http://www.whois.com/whois/{}'.format(domain))
tree = html.fromstring(page.content)
| from lxml import html
from PIL import Image
import requests
import urllib.request
def enlarge_image(image_file):
image = Image.open(image_file)
enlarged_size = map(lambda x: x*2, image.size)
enlarged_image = image.resize(enlarged_size)
return enlarged_image
def extract_text(image_file):
image = enlarge_image(image_file)
# Use Tesseract to extract text from the enlarged image. Then Return it.
def fix_emails(whois_data, image_urls):
count = 0
for index, item in enumerate(whois_data):
if item.startswith('@'):
with urllib.request.urlopen(image_urls[count]) as response:
email_username = extract_text(image_urls[count])
whois_data[index-1:index+1] = [whois_data[index-1] + email_username + whois_data[index]]
count += 1
return whois_data
def scrape_whois(domain):
domain = 'speedtest.net'
page = requests.get('http://www.whois.com/whois/{}'.format(domain))
tree = html.fromstring(page.content)
registrar_data = tree.xpath('//*[@id="registrarData"]/text()')
registrar_images = list(map(lambda x: 'http://www.whois.com' + x, tree.xpath('//*[@id="registrarData"]/img/@src')))
registry_data = tree.xpath('//*[@id="registryData"]/text()')
registry_images = list(map(lambda x: 'http://www.whois.com' + x, tree.xpath('//*[@id="registryData"]/img/@src'))) | Add functions to scrape whois data and fix the e-mails in it | Add functions to scrape whois data and fix the e-mails in it
- Add function scrape_whois which scrapes the raw whois information for a given domain from http://www.whois.com/whois.
- Add function fix_emails. http://www.whois.com hides the username-part of the contact e-mails from the whois info by displaying it as an image. This function fixes that using the extract_text function.
| Python | mit | SkullTech/whois-scraper | from lxml import html
from PIL import Image
import requests
+ import urllib.request
def enlarge_image(image_file):
image = Image.open(image_file)
enlarged_size = map(lambda x: x*2, image.size)
enlarged_image = image.resize(enlarged_size)
return enlarged_image
def extract_text(image_file):
image = enlarge_image(image_file)
# Use Tesseract to extract text from the enlarged image. Then Return it.
- domain = 'speedtest.net'
+ def fix_emails(whois_data, image_urls):
+ count = 0
- page = requests.get('http://www.whois.com/whois/{}'.format(domain))
- tree = html.fromstring(page.content)
+ for index, item in enumerate(whois_data):
+ if item.startswith('@'):
+ with urllib.request.urlopen(image_urls[count]) as response:
+ email_username = extract_text(image_urls[count])
+
+ whois_data[index-1:index+1] = [whois_data[index-1] + email_username + whois_data[index]]
+ count += 1
+ return whois_data
+
+ def scrape_whois(domain):
+ domain = 'speedtest.net'
+
+ page = requests.get('http://www.whois.com/whois/{}'.format(domain))
+ tree = html.fromstring(page.content)
+
+ registrar_data = tree.xpath('//*[@id="registrarData"]/text()')
+ registrar_images = list(map(lambda x: 'http://www.whois.com' + x, tree.xpath('//*[@id="registrarData"]/img/@src')))
+ registry_data = tree.xpath('//*[@id="registryData"]/text()')
+ registry_images = list(map(lambda x: 'http://www.whois.com' + x, tree.xpath('//*[@id="registryData"]/img/@src'))) | Add functions to scrape whois data and fix the e-mails in it | ## Code Before:
from lxml import html
from PIL import Image
import requests
def enlarge_image(image_file):
image = Image.open(image_file)
enlarged_size = map(lambda x: x*2, image.size)
enlarged_image = image.resize(enlarged_size)
return enlarged_image
def extract_text(image_file):
image = enlarge_image(image_file)
# Use Tesseract to extract text from the enlarged image. Then Return it.
domain = 'speedtest.net'
page = requests.get('http://www.whois.com/whois/{}'.format(domain))
tree = html.fromstring(page.content)
## Instruction:
Add functions to scrape whois data and fix the e-mails in it
## Code After:
from lxml import html
from PIL import Image
import requests
import urllib.request
def enlarge_image(image_file):
image = Image.open(image_file)
enlarged_size = map(lambda x: x*2, image.size)
enlarged_image = image.resize(enlarged_size)
return enlarged_image
def extract_text(image_file):
image = enlarge_image(image_file)
# Use Tesseract to extract text from the enlarged image. Then Return it.
def fix_emails(whois_data, image_urls):
count = 0
for index, item in enumerate(whois_data):
if item.startswith('@'):
with urllib.request.urlopen(image_urls[count]) as response:
email_username = extract_text(image_urls[count])
whois_data[index-1:index+1] = [whois_data[index-1] + email_username + whois_data[index]]
count += 1
return whois_data
def scrape_whois(domain):
domain = 'speedtest.net'
page = requests.get('http://www.whois.com/whois/{}'.format(domain))
tree = html.fromstring(page.content)
registrar_data = tree.xpath('//*[@id="registrarData"]/text()')
registrar_images = list(map(lambda x: 'http://www.whois.com' + x, tree.xpath('//*[@id="registrarData"]/img/@src')))
registry_data = tree.xpath('//*[@id="registryData"]/text()')
registry_images = list(map(lambda x: 'http://www.whois.com' + x, tree.xpath('//*[@id="registryData"]/img/@src'))) |
b89f6981d4f55790aa919f36e02a6312bd5f1583 | tests/__init__.py | tests/__init__.py | import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
from flask.ext.images import Images, ImageSize, resized_img_src
import flask
flask_version = tuple(map(int, flask.__version__.split('.')))
class TestCase(unittest.TestCase):
def setUp(self):
self.app = self.create_app()
self.app_ctx = self.app.app_context()
self.app_ctx.push()
self.req_ctx = self.app.test_request_context('http://localhost:8000/')
self.req_ctx.push()
self.client = self.app.test_client()
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'localhost'
app.config['SECRET_KEY'] = 'secret secret'
app.config['IMAGES_PATH'] = ['assets']
self.images = Images(app)
return app
def assert200(self, res):
self.assertEqual(res.status_code, 200)
| import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
import flask
from flask_images import Images, ImageSize, resized_img_src
flask_version = tuple(map(int, flask.__version__.split('.')))
class TestCase(unittest.TestCase):
def setUp(self):
self.app = self.create_app()
self.app_ctx = self.app.app_context()
self.app_ctx.push()
self.req_ctx = self.app.test_request_context('http://localhost:8000/')
self.req_ctx.push()
self.client = self.app.test_client()
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'localhost'
app.config['SECRET_KEY'] = 'secret secret'
app.config['IMAGES_PATH'] = ['assets']
self.images = Images(app)
return app
def assert200(self, res):
self.assertEqual(res.status_code, 200)
| Stop using `flask.ext.*` in tests. | Stop using `flask.ext.*` in tests.
| Python | bsd-3-clause | mikeboers/Flask-Images | import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
- from flask.ext.images import Images, ImageSize, resized_img_src
import flask
+
+ from flask_images import Images, ImageSize, resized_img_src
+
flask_version = tuple(map(int, flask.__version__.split('.')))
class TestCase(unittest.TestCase):
def setUp(self):
self.app = self.create_app()
self.app_ctx = self.app.app_context()
self.app_ctx.push()
self.req_ctx = self.app.test_request_context('http://localhost:8000/')
self.req_ctx.push()
self.client = self.app.test_client()
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'localhost'
app.config['SECRET_KEY'] = 'secret secret'
app.config['IMAGES_PATH'] = ['assets']
self.images = Images(app)
return app
def assert200(self, res):
self.assertEqual(res.status_code, 200)
| Stop using `flask.ext.*` in tests. | ## Code Before:
import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
from flask.ext.images import Images, ImageSize, resized_img_src
import flask
flask_version = tuple(map(int, flask.__version__.split('.')))
class TestCase(unittest.TestCase):
def setUp(self):
self.app = self.create_app()
self.app_ctx = self.app.app_context()
self.app_ctx.push()
self.req_ctx = self.app.test_request_context('http://localhost:8000/')
self.req_ctx.push()
self.client = self.app.test_client()
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'localhost'
app.config['SECRET_KEY'] = 'secret secret'
app.config['IMAGES_PATH'] = ['assets']
self.images = Images(app)
return app
def assert200(self, res):
self.assertEqual(res.status_code, 200)
## Instruction:
Stop using `flask.ext.*` in tests.
## Code After:
import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
import flask
from flask_images import Images, ImageSize, resized_img_src
flask_version = tuple(map(int, flask.__version__.split('.')))
class TestCase(unittest.TestCase):
def setUp(self):
self.app = self.create_app()
self.app_ctx = self.app.app_context()
self.app_ctx.push()
self.req_ctx = self.app.test_request_context('http://localhost:8000/')
self.req_ctx.push()
self.client = self.app.test_client()
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'localhost'
app.config['SECRET_KEY'] = 'secret secret'
app.config['IMAGES_PATH'] = ['assets']
self.images = Images(app)
return app
def assert200(self, res):
self.assertEqual(res.status_code, 200)
|
211972701d8dbd39e42ec5a8d10b9c56be858d3e | tests/conftest.py | tests/conftest.py | import string
import pytest
@pytest.fixture
def identity_fixures():
l = []
for i, c in enumerate(string.ascii_uppercase):
l.append(dict(
name='identity_{0}'.format(i),
access_key_id='someaccesskey_{0}'.format(c),
secret_access_key='notasecret_{0}_{1}'.format(i, c),
))
return l
@pytest.fixture
def identity_store(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
def fin():
identity_store.identities.clear()
identity_store.save_to_config()
return identity_store
@pytest.fixture
def identity_store_with_data(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
for data in identity_fixures():
identity_store.add_identity(data)
def fin():
identity_store.identities.clear()
identity_store.save_to_config()
return identity_store
| import string
import pytest
@pytest.fixture
def identity_fixures():
l = []
for i, c in enumerate(string.ascii_uppercase):
l.append(dict(
name='identity_{0}'.format(i),
access_key_id='someaccesskey_{0}'.format(c),
secret_access_key='notasecret_{0}_{1}'.format(i, c),
))
return l
@pytest.fixture
def identity_store(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
return identity_store
@pytest.fixture
def identity_store_with_data(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
for data in identity_fixures():
identity_store.add_identity(data)
return identity_store
| Remove fixture teardown since nothing should be saved (tmpdir) | Remove fixture teardown since nothing should be saved (tmpdir)
| Python | mit | nocarryr/AWS-Identity-Manager | import string
import pytest
@pytest.fixture
def identity_fixures():
l = []
for i, c in enumerate(string.ascii_uppercase):
l.append(dict(
name='identity_{0}'.format(i),
access_key_id='someaccesskey_{0}'.format(c),
secret_access_key='notasecret_{0}_{1}'.format(i, c),
))
return l
@pytest.fixture
def identity_store(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
- def fin():
- identity_store.identities.clear()
- identity_store.save_to_config()
return identity_store
@pytest.fixture
def identity_store_with_data(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
for data in identity_fixures():
identity_store.add_identity(data)
- def fin():
- identity_store.identities.clear()
- identity_store.save_to_config()
return identity_store
| Remove fixture teardown since nothing should be saved (tmpdir) | ## Code Before:
import string
import pytest
@pytest.fixture
def identity_fixures():
l = []
for i, c in enumerate(string.ascii_uppercase):
l.append(dict(
name='identity_{0}'.format(i),
access_key_id='someaccesskey_{0}'.format(c),
secret_access_key='notasecret_{0}_{1}'.format(i, c),
))
return l
@pytest.fixture
def identity_store(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
def fin():
identity_store.identities.clear()
identity_store.save_to_config()
return identity_store
@pytest.fixture
def identity_store_with_data(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
for data in identity_fixures():
identity_store.add_identity(data)
def fin():
identity_store.identities.clear()
identity_store.save_to_config()
return identity_store
## Instruction:
Remove fixture teardown since nothing should be saved (tmpdir)
## Code After:
import string
import pytest
@pytest.fixture
def identity_fixures():
l = []
for i, c in enumerate(string.ascii_uppercase):
l.append(dict(
name='identity_{0}'.format(i),
access_key_id='someaccesskey_{0}'.format(c),
secret_access_key='notasecret_{0}_{1}'.format(i, c),
))
return l
@pytest.fixture
def identity_store(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
return identity_store
@pytest.fixture
def identity_store_with_data(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
for data in identity_fixures():
identity_store.add_identity(data)
return identity_store
|
debdc71a1c22412c46d8bf74315a5467c1e228ee | magnum/tests/unit/common/test_exception.py | magnum/tests/unit/common/test_exception.py |
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", ex.message)
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", ex.message)
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
|
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", str(ex))
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", str(ex))
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
| Stop using deprecated 'message' attribute in Exception | Stop using deprecated 'message' attribute in Exception
The 'message' attribute has been deprecated and removed
from Python3.
For more details, please check:
https://www.python.org/dev/peps/pep-0352/
Change-Id: Id952e4f59a911df7ccc1d64e7a8a2d5e9ee353dd
| Python | apache-2.0 | ArchiFleKs/magnum,ArchiFleKs/magnum,openstack/magnum,openstack/magnum |
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
- self.assertEqual("templated NAME", ex.message)
+ self.assertEqual("templated NAME", str(ex))
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
- self.assertEqual("custom templated NAME", ex.message)
+ self.assertEqual("custom templated NAME", str(ex))
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
| Stop using deprecated 'message' attribute in Exception | ## Code Before:
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", ex.message)
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", ex.message)
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
## Instruction:
Stop using deprecated 'message' attribute in Exception
## Code After:
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", str(ex))
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", str(ex))
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
|
4d1b96792f73777adaa0a79341901ca82f57839b | use/functional.py | use/functional.py | def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
| import collections
import functools
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
class memoize(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
| Add a simple memoize function | Add a simple memoize function
| Python | mit | log0ymxm/corgi | + import collections
+ import functools
+
+
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
+
+ class memoize(object):
+ '''Decorator. Caches a function's return value each time it is called.
+ If called later with the same arguments, the cached value is returned
+ (not reevaluated).
+ '''
+
+ def __init__(self, func):
+ self.func = func
+ self.cache = {}
+
+ def __call__(self, *args):
+ if not isinstance(args, collections.Hashable):
+ # uncacheable. a list, for instance.
+ # better to not cache than blow up.
+ return self.func(*args)
+ if args in self.cache:
+ return self.cache[args]
+ else:
+ value = self.func(*args)
+ self.cache[args] = value
+ return value
+
+ def __repr__(self):
+ '''Return the function's docstring.'''
+ return self.func.__doc__
+
+ def __get__(self, obj, objtype):
+ '''Support instance methods.'''
+ return functools.partial(self.__call__, obj)
+ | Add a simple memoize function | ## Code Before:
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
## Instruction:
Add a simple memoize function
## Code After:
import collections
import functools
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
class memoize(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
|
3f2b4236bdb5199d4830a893c7b511f7875dc501 | plata/utils.py | plata/utils.py | from decimal import Decimal
import simplejson
from django.core.serializers.json import DjangoJSONEncoder
try:
simplejson.dumps([42], use_decimal=True)
except TypeError:
raise Exception('simplejson>=2.1 with support for use_decimal required.')
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
setattr(obj, cache_field, simplejson.loads(getattr(obj, self.field),
use_decimal=True))
except (TypeError, ValueError):
setattr(obj, cache_field, {})
return getattr(obj, cache_field)
def __set__(self, obj, value):
setattr(obj, '_cached_jsonfield_%s' % self.field, value)
setattr(obj, self.field, simplejson.dumps(value, use_decimal=True,
cls=DjangoJSONEncoder))
| from decimal import Decimal
import simplejson
from django.core.serializers.json import DjangoJSONEncoder
try:
simplejson.dumps([42], use_decimal=True)
except TypeError:
raise Exception('simplejson>=2.1 with support for use_decimal required.')
class CallbackOnUpdateDict(dict):
"""Dict which executes a callback on every update"""
def __init__(self, *args, **kwargs):
self.callback = kwargs.pop('callback')
super(CallbackOnUpdateDict, self).__init__(*args, **kwargs)
def __setitem__(self, key, value):
ret = super(CallbackOnUpdateDict, self).__setitem__(key, value)
self.callback(self)
return ret
def update(self, d):
ret = super(CallbackOnUpdateDict, self).update(d)
self.callback(self)
return ret
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
value = simplejson.loads(getattr(obj, self.field), use_decimal=True)
except (TypeError, ValueError):
value = {}
self.__set__(obj, value)
return getattr(obj, cache_field)
def __set__(self, obj, value):
if not isinstance(value, CallbackOnUpdateDict):
value = CallbackOnUpdateDict(value,
# Update cached and serialized value on every write to the data dict
callback=lambda d: self.__set__(obj, d))
setattr(obj, '_cached_jsonfield_%s' % self.field, value)
setattr(obj, self.field, simplejson.dumps(value, use_decimal=True,
cls=DjangoJSONEncoder))
| Make working with JSONDataDescriptor easier | Make working with JSONDataDescriptor easier
| Python | bsd-3-clause | allink/plata,armicron/plata,armicron/plata,armicron/plata,stefanklug/plata | from decimal import Decimal
import simplejson
from django.core.serializers.json import DjangoJSONEncoder
try:
simplejson.dumps([42], use_decimal=True)
except TypeError:
raise Exception('simplejson>=2.1 with support for use_decimal required.')
+ class CallbackOnUpdateDict(dict):
+ """Dict which executes a callback on every update"""
+
+ def __init__(self, *args, **kwargs):
+ self.callback = kwargs.pop('callback')
+ super(CallbackOnUpdateDict, self).__init__(*args, **kwargs)
+
+ def __setitem__(self, key, value):
+ ret = super(CallbackOnUpdateDict, self).__setitem__(key, value)
+ self.callback(self)
+ return ret
+
+ def update(self, d):
+ ret = super(CallbackOnUpdateDict, self).update(d)
+ self.callback(self)
+ return ret
+
+
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
+ value = simplejson.loads(getattr(obj, self.field), use_decimal=True)
- setattr(obj, cache_field, simplejson.loads(getattr(obj, self.field),
- use_decimal=True))
except (TypeError, ValueError):
- setattr(obj, cache_field, {})
+ value = {}
+
+ self.__set__(obj, value)
+
return getattr(obj, cache_field)
def __set__(self, obj, value):
+ if not isinstance(value, CallbackOnUpdateDict):
+ value = CallbackOnUpdateDict(value,
+ # Update cached and serialized value on every write to the data dict
+ callback=lambda d: self.__set__(obj, d))
+
setattr(obj, '_cached_jsonfield_%s' % self.field, value)
setattr(obj, self.field, simplejson.dumps(value, use_decimal=True,
cls=DjangoJSONEncoder))
| Make working with JSONDataDescriptor easier | ## Code Before:
from decimal import Decimal
import simplejson
from django.core.serializers.json import DjangoJSONEncoder
try:
simplejson.dumps([42], use_decimal=True)
except TypeError:
raise Exception('simplejson>=2.1 with support for use_decimal required.')
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
setattr(obj, cache_field, simplejson.loads(getattr(obj, self.field),
use_decimal=True))
except (TypeError, ValueError):
setattr(obj, cache_field, {})
return getattr(obj, cache_field)
def __set__(self, obj, value):
setattr(obj, '_cached_jsonfield_%s' % self.field, value)
setattr(obj, self.field, simplejson.dumps(value, use_decimal=True,
cls=DjangoJSONEncoder))
## Instruction:
Make working with JSONDataDescriptor easier
## Code After:
from decimal import Decimal
import simplejson
from django.core.serializers.json import DjangoJSONEncoder
try:
simplejson.dumps([42], use_decimal=True)
except TypeError:
raise Exception('simplejson>=2.1 with support for use_decimal required.')
class CallbackOnUpdateDict(dict):
"""Dict which executes a callback on every update"""
def __init__(self, *args, **kwargs):
self.callback = kwargs.pop('callback')
super(CallbackOnUpdateDict, self).__init__(*args, **kwargs)
def __setitem__(self, key, value):
ret = super(CallbackOnUpdateDict, self).__setitem__(key, value)
self.callback(self)
return ret
def update(self, d):
ret = super(CallbackOnUpdateDict, self).update(d)
self.callback(self)
return ret
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
value = simplejson.loads(getattr(obj, self.field), use_decimal=True)
except (TypeError, ValueError):
value = {}
self.__set__(obj, value)
return getattr(obj, cache_field)
def __set__(self, obj, value):
if not isinstance(value, CallbackOnUpdateDict):
value = CallbackOnUpdateDict(value,
# Update cached and serialized value on every write to the data dict
callback=lambda d: self.__set__(obj, d))
setattr(obj, '_cached_jsonfield_%s' % self.field, value)
setattr(obj, self.field, simplejson.dumps(value, use_decimal=True,
cls=DjangoJSONEncoder))
|
131f266e73139f1148ee3e9fcce8db40842afb88 | sale_channel/models/account.py | sale_channel/models/account.py |
from openerp import models, fields, api, _, exceptions
class AccountTax(models.Model):
_inherit = 'account.tax'
@api.model
def _get_sales_channel_domain(self):
ids = self.env.ref('res_partner_category.sales_channel').ids
return [('category_id', 'in', ids)]
sales_channel_id = fields.Many2one('res.partner', string="Sales channel",
ondelete='set null', domain=_get_sales_channel_domain)
|
from openerp import models, fields, api, _, exceptions
class AccountTax(models.Model):
_inherit = 'account.tax'
@api.model
def _get_sales_channel_domain(self):
ids = self.env.ref('res_partner_category.sales_channel').ids
return [('category_id', 'in', ids)]
sales_channel_id = fields.Many2one('res.partner', string="Sales channel",
ondelete='set null', domain=_get_sales_channel_domain)
_sql_constraints = [
('name_company_uniq', 'unique(name, company_id, sales_channel_id)', 'Tax Name must be unique per company and sales channel!'),
]
| Add constraint, tax name must be unique for each company and sales channel | [IMP] Add constraint, tax name must be unique for each company and sales channel
| Python | agpl-3.0 | 1200wd/1200wd_addons,1200wd/1200wd_addons |
from openerp import models, fields, api, _, exceptions
class AccountTax(models.Model):
_inherit = 'account.tax'
@api.model
def _get_sales_channel_domain(self):
ids = self.env.ref('res_partner_category.sales_channel').ids
return [('category_id', 'in', ids)]
sales_channel_id = fields.Many2one('res.partner', string="Sales channel",
ondelete='set null', domain=_get_sales_channel_domain)
+ _sql_constraints = [
+ ('name_company_uniq', 'unique(name, company_id, sales_channel_id)', 'Tax Name must be unique per company and sales channel!'),
+ ]
+ | Add constraint, tax name must be unique for each company and sales channel | ## Code Before:
from openerp import models, fields, api, _, exceptions
class AccountTax(models.Model):
_inherit = 'account.tax'
@api.model
def _get_sales_channel_domain(self):
ids = self.env.ref('res_partner_category.sales_channel').ids
return [('category_id', 'in', ids)]
sales_channel_id = fields.Many2one('res.partner', string="Sales channel",
ondelete='set null', domain=_get_sales_channel_domain)
## Instruction:
Add constraint, tax name must be unique for each company and sales channel
## Code After:
from openerp import models, fields, api, _, exceptions
class AccountTax(models.Model):
_inherit = 'account.tax'
@api.model
def _get_sales_channel_domain(self):
ids = self.env.ref('res_partner_category.sales_channel').ids
return [('category_id', 'in', ids)]
sales_channel_id = fields.Many2one('res.partner', string="Sales channel",
ondelete='set null', domain=_get_sales_channel_domain)
_sql_constraints = [
('name_company_uniq', 'unique(name, company_id, sales_channel_id)', 'Tax Name must be unique per company and sales channel!'),
]
|
999d243fbc9908255ae292186bf8b17eb67e42e8 | planner/forms.py | planner/forms.py | from django import forms
class LoginForm(forms.Form):
email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password',
'class': 'form-control',
}))
class SearchTrip(forms.Form):
origin_id = forms.IntegerField()
destination_id = forms.IntegerField()
datetime = forms.DateTimeField()
| from django.contrib.auth.forms import AuthenticationForm
from django import forms
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password',
'class': 'form-control',
}))
class SearchTrip(forms.Form):
origin_id = forms.IntegerField()
destination_id = forms.IntegerField()
datetime = forms.DateTimeField()
| Fix LoginForm to be conformant to builtin AuthenticationForm | Fix LoginForm to be conformant to builtin AuthenticationForm
| Python | mit | livingsilver94/getaride,livingsilver94/getaride,livingsilver94/getaride | + from django.contrib.auth.forms import AuthenticationForm
from django import forms
- class LoginForm(forms.Form):
+ class LoginForm(AuthenticationForm):
- email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
+ username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password',
'class': 'form-control',
}))
class SearchTrip(forms.Form):
origin_id = forms.IntegerField()
destination_id = forms.IntegerField()
datetime = forms.DateTimeField()
| Fix LoginForm to be conformant to builtin AuthenticationForm | ## Code Before:
from django import forms
class LoginForm(forms.Form):
email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password',
'class': 'form-control',
}))
class SearchTrip(forms.Form):
origin_id = forms.IntegerField()
destination_id = forms.IntegerField()
datetime = forms.DateTimeField()
## Instruction:
Fix LoginForm to be conformant to builtin AuthenticationForm
## Code After:
from django.contrib.auth.forms import AuthenticationForm
from django import forms
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password',
'class': 'form-control',
}))
class SearchTrip(forms.Form):
origin_id = forms.IntegerField()
destination_id = forms.IntegerField()
datetime = forms.DateTimeField()
|
e1240aa33b286ba52507128458fc6d6b3b68dfb3 | statsmodels/stats/multicomp.py | statsmodels/stats/multicomp.py |
from statsmodels.sandbox.stats.multicomp import MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapper around tukeyhsd method of MultiComparison
Parameters
----------
endog : ndarray, float, 1d
response variable
groups : ndarray, 1d
array with groups, can be string or integers
alpha : float
significance level for the test
Returns
-------
results : TukeyHSDResults instance
A results class containing relevant data and some post-hoc
calculations
See Also
--------
MultiComparison
tukeyhsd
statsmodels.sandbox.stats.multicomp.TukeyHSDResults
'''
return MultiComparison(endog, groups).tukeyhsd(alpha=alpha)
|
from statsmodels.sandbox.stats.multicomp import tukeyhsd, MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapper around tukeyhsd method of MultiComparison
Parameters
----------
endog : ndarray, float, 1d
response variable
groups : ndarray, 1d
array with groups, can be string or integers
alpha : float
significance level for the test
Returns
-------
results : TukeyHSDResults instance
A results class containing relevant data and some post-hoc
calculations
See Also
--------
MultiComparison
tukeyhsd
statsmodels.sandbox.stats.multicomp.TukeyHSDResults
'''
return MultiComparison(endog, groups).tukeyhsd(alpha=alpha)
| Put back an import that my IDE incorrectly flagged as unused | Put back an import that my IDE incorrectly flagged as unused
| Python | bsd-3-clause | gef756/statsmodels,detrout/debian-statsmodels,detrout/debian-statsmodels,bzero/statsmodels,YihaoLu/statsmodels,wzbozon/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,musically-ut/statsmodels,josef-pkt/statsmodels,cbmoore/statsmodels,rgommers/statsmodels,hlin117/statsmodels,ChadFulton/statsmodels,edhuckle/statsmodels,hainm/statsmodels,musically-ut/statsmodels,gef756/statsmodels,edhuckle/statsmodels,saketkc/statsmodels,jseabold/statsmodels,jstoxrocky/statsmodels,adammenges/statsmodels,waynenilsen/statsmodels,bzero/statsmodels,nvoron23/statsmodels,wdurhamh/statsmodels,huongttlan/statsmodels,alekz112/statsmodels,adammenges/statsmodels,nguyentu1602/statsmodels,waynenilsen/statsmodels,yl565/statsmodels,phobson/statsmodels,alekz112/statsmodels,wzbozon/statsmodels,huongttlan/statsmodels,saketkc/statsmodels,hainm/statsmodels,hlin117/statsmodels,kiyoto/statsmodels,YihaoLu/statsmodels,waynenilsen/statsmodels,bashtage/statsmodels,wzbozon/statsmodels,jseabold/statsmodels,gef756/statsmodels,phobson/statsmodels,bashtage/statsmodels,YihaoLu/statsmodels,rgommers/statsmodels,astocko/statsmodels,bsipocz/statsmodels,edhuckle/statsmodels,bzero/statsmodels,jseabold/statsmodels,bert9bert/statsmodels,hlin117/statsmodels,saketkc/statsmodels,statsmodels/statsmodels,wdurhamh/statsmodels,edhuckle/statsmodels,wkfwkf/statsmodels,nvoron23/statsmodels,DonBeo/statsmodels,ChadFulton/statsmodels,wdurhamh/statsmodels,ChadFulton/statsmodels,jseabold/statsmodels,wwf5067/statsmodels,bsipocz/statsmodels,nguyentu1602/statsmodels,kiyoto/statsmodels,josef-pkt/statsmodels,adammenges/statsmodels,wkfwkf/statsmodels,ChadFulton/statsmodels,detrout/debian-statsmodels,hainm/statsmodels,wwf5067/statsmodels,phobson/statsmodels,wkfwkf/statsmodels,bert9bert/statsmodels,alekz112/statsmodels,nguyentu1602/statsmodels,hainm/statsmodels,bert9bert/statsmodels,yl565/statsmodels,nguyentu1602/statsmodels,Averroes/statsmodels,bzero/statsmodels,kiyoto/statsmodels,wwf5067/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,YihaoLu/statsmodels,bashtage/statsmodels,rgommers/statsmodels,bert9bert/statsmodels,bashtage/statsmodels,bert9bert/statsmodels,saketkc/statsmodels,DonBeo/statsmodels,musically-ut/statsmodels,Averroes/statsmodels,cbmoore/statsmodels,kiyoto/statsmodels,nvoron23/statsmodels,jseabold/statsmodels,statsmodels/statsmodels,ChadFulton/statsmodels,Averroes/statsmodels,astocko/statsmodels,huongttlan/statsmodels,wkfwkf/statsmodels,wdurhamh/statsmodels,rgommers/statsmodels,josef-pkt/statsmodels,wdurhamh/statsmodels,josef-pkt/statsmodels,nvoron23/statsmodels,bzero/statsmodels,wzbozon/statsmodels,jstoxrocky/statsmodels,YihaoLu/statsmodels,phobson/statsmodels,hlin117/statsmodels,alekz112/statsmodels,astocko/statsmodels,musically-ut/statsmodels,gef756/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,DonBeo/statsmodels,ChadFulton/statsmodels,josef-pkt/statsmodels,adammenges/statsmodels,yl565/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,rgommers/statsmodels,astocko/statsmodels,bashtage/statsmodels,phobson/statsmodels,Averroes/statsmodels,huongttlan/statsmodels,yl565/statsmodels,jstoxrocky/statsmodels,wkfwkf/statsmodels,bsipocz/statsmodels,cbmoore/statsmodels,gef756/statsmodels,wwf5067/statsmodels,jstoxrocky/statsmodels,DonBeo/statsmodels,DonBeo/statsmodels,bsipocz/statsmodels,kiyoto/statsmodels,wzbozon/statsmodels,detrout/debian-statsmodels,yl565/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,waynenilsen/statsmodels,statsmodels/statsmodels |
- from statsmodels.sandbox.stats.multicomp import MultiComparison
+ from statsmodels.sandbox.stats.multicomp import tukeyhsd, MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapper around tukeyhsd method of MultiComparison
Parameters
----------
endog : ndarray, float, 1d
response variable
groups : ndarray, 1d
array with groups, can be string or integers
alpha : float
significance level for the test
Returns
-------
results : TukeyHSDResults instance
A results class containing relevant data and some post-hoc
calculations
See Also
--------
MultiComparison
tukeyhsd
statsmodels.sandbox.stats.multicomp.TukeyHSDResults
'''
return MultiComparison(endog, groups).tukeyhsd(alpha=alpha)
| Put back an import that my IDE incorrectly flagged as unused | ## Code Before:
from statsmodels.sandbox.stats.multicomp import MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapper around tukeyhsd method of MultiComparison
Parameters
----------
endog : ndarray, float, 1d
response variable
groups : ndarray, 1d
array with groups, can be string or integers
alpha : float
significance level for the test
Returns
-------
results : TukeyHSDResults instance
A results class containing relevant data and some post-hoc
calculations
See Also
--------
MultiComparison
tukeyhsd
statsmodels.sandbox.stats.multicomp.TukeyHSDResults
'''
return MultiComparison(endog, groups).tukeyhsd(alpha=alpha)
## Instruction:
Put back an import that my IDE incorrectly flagged as unused
## Code After:
from statsmodels.sandbox.stats.multicomp import tukeyhsd, MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapper around tukeyhsd method of MultiComparison
Parameters
----------
endog : ndarray, float, 1d
response variable
groups : ndarray, 1d
array with groups, can be string or integers
alpha : float
significance level for the test
Returns
-------
results : TukeyHSDResults instance
A results class containing relevant data and some post-hoc
calculations
See Also
--------
MultiComparison
tukeyhsd
statsmodels.sandbox.stats.multicomp.TukeyHSDResults
'''
return MultiComparison(endog, groups).tukeyhsd(alpha=alpha)
|
68046b638b5d2a9d9a0c9c588a6c2b833442e01b | plinth/modules/ikiwiki/forms.py | plinth/modules/ikiwiki/forms.py |
from django import forms
from django.utils.translation import ugettext_lazy as _
class IkiwikiCreateForm(forms.Form):
"""Form to create a wiki or blog."""
site_type = forms.ChoiceField(
label=_('Type'),
choices=[('wiki', 'Wiki'), ('blog', 'Blog')])
name = forms.CharField(label=_('Name'))
admin_name = forms.CharField(label=_('Admin Account Name'))
admin_password = forms.CharField(
label=_('Admin Account Password'),
widget=forms.PasswordInput())
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
class IkiwikiCreateForm(forms.Form):
"""Form to create a wiki or blog."""
site_type = forms.ChoiceField(
label=_('Type'),
choices=[('wiki', 'Wiki'), ('blog', 'Blog')])
name = forms.CharField(label=_('Name'),
validators=[RegexValidator(regex='^[a-zA-Z0-9]+$')])
admin_name = forms.CharField(label=_('Admin Account Name'))
admin_password = forms.CharField(
label=_('Admin Account Password'),
widget=forms.PasswordInput())
| Allow only alphanumerics in wiki/blog name | ikiwiki: Allow only alphanumerics in wiki/blog name
| Python | agpl-3.0 | harry-7/Plinth,kkampardi/Plinth,freedomboxtwh/Plinth,vignanl/Plinth,kkampardi/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth,vignanl/Plinth,vignanl/Plinth,kkampardi/Plinth,vignanl/Plinth,freedomboxtwh/Plinth,freedomboxtwh/Plinth,freedomboxtwh/Plinth,harry-7/Plinth,freedomboxtwh/Plinth,harry-7/Plinth,harry-7/Plinth,kkampardi/Plinth |
from django import forms
from django.utils.translation import ugettext_lazy as _
+ from django.core.validators import RegexValidator
class IkiwikiCreateForm(forms.Form):
"""Form to create a wiki or blog."""
site_type = forms.ChoiceField(
label=_('Type'),
choices=[('wiki', 'Wiki'), ('blog', 'Blog')])
- name = forms.CharField(label=_('Name'))
+ name = forms.CharField(label=_('Name'),
+ validators=[RegexValidator(regex='^[a-zA-Z0-9]+$')])
admin_name = forms.CharField(label=_('Admin Account Name'))
admin_password = forms.CharField(
label=_('Admin Account Password'),
widget=forms.PasswordInput())
| Allow only alphanumerics in wiki/blog name | ## Code Before:
from django import forms
from django.utils.translation import ugettext_lazy as _
class IkiwikiCreateForm(forms.Form):
"""Form to create a wiki or blog."""
site_type = forms.ChoiceField(
label=_('Type'),
choices=[('wiki', 'Wiki'), ('blog', 'Blog')])
name = forms.CharField(label=_('Name'))
admin_name = forms.CharField(label=_('Admin Account Name'))
admin_password = forms.CharField(
label=_('Admin Account Password'),
widget=forms.PasswordInput())
## Instruction:
Allow only alphanumerics in wiki/blog name
## Code After:
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
class IkiwikiCreateForm(forms.Form):
"""Form to create a wiki or blog."""
site_type = forms.ChoiceField(
label=_('Type'),
choices=[('wiki', 'Wiki'), ('blog', 'Blog')])
name = forms.CharField(label=_('Name'),
validators=[RegexValidator(regex='^[a-zA-Z0-9]+$')])
admin_name = forms.CharField(label=_('Admin Account Name'))
admin_password = forms.CharField(
label=_('Admin Account Password'),
widget=forms.PasswordInput())
|
65fcfbfae9ef1a68d324aea932f983f7edd00cdf | mopidy/__init__.py | mopidy/__init__.py | import logging
from mopidy import settings as raw_settings
logger = logging.getLogger('mopidy')
def get_version():
return u'0.1.dev'
def get_mpd_protocol_version():
return u'0.16.0'
def get_class(name):
module_name = name[:name.rindex('.')]
class_name = name[name.rindex('.') + 1:]
logger.info('Loading: %s from %s', class_name, module_name)
module = __import__(module_name, globals(), locals(), [class_name], -1)
class_object = getattr(module, class_name)
return class_object
class SettingsError(Exception):
pass
class Settings(object):
def __getattr__(self, attr):
if not hasattr(raw_settings, attr):
raise SettingsError(u'Setting "%s" is not set.' % attr)
value = getattr(raw_settings, attr)
if type(value) != bool and not value:
raise SettingsError(u'Setting "%s" is empty.' % attr)
return value
settings = Settings()
| import logging
from multiprocessing.reduction import reduce_connection
import pickle
from mopidy import settings as raw_settings
logger = logging.getLogger('mopidy')
def get_version():
return u'0.1.dev'
def get_mpd_protocol_version():
return u'0.16.0'
def get_class(name):
module_name = name[:name.rindex('.')]
class_name = name[name.rindex('.') + 1:]
logger.info('Loading: %s from %s', class_name, module_name)
module = __import__(module_name, globals(), locals(), [class_name], -1)
class_object = getattr(module, class_name)
return class_object
def pickle_connection(connection):
return pickle.dumps(reduce_connection(connection))
def unpickle_connection(pickled_connection):
# From http://stackoverflow.com/questions/1446004
unpickled = pickle.loads(pickled_connection)
func = unpickled[0]
args = unpickled[1]
return func(*args)
class SettingsError(Exception):
pass
class Settings(object):
def __getattr__(self, attr):
if not hasattr(raw_settings, attr):
raise SettingsError(u'Setting "%s" is not set.' % attr)
value = getattr(raw_settings, attr)
if type(value) != bool and not value:
raise SettingsError(u'Setting "%s" is empty.' % attr)
return value
settings = Settings()
| Add util functions for pickling and unpickling multiprocessing.Connection | Add util functions for pickling and unpickling multiprocessing.Connection
| Python | apache-2.0 | SuperStarPL/mopidy,pacificIT/mopidy,swak/mopidy,hkariti/mopidy,dbrgn/mopidy,jmarsik/mopidy,diandiankan/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,quartz55/mopidy,ali/mopidy,pacificIT/mopidy,adamcik/mopidy,rawdlite/mopidy,swak/mopidy,dbrgn/mopidy,jodal/mopidy,hkariti/mopidy,priestd09/mopidy,dbrgn/mopidy,jmarsik/mopidy,quartz55/mopidy,liamw9534/mopidy,mokieyue/mopidy,mokieyue/mopidy,tkem/mopidy,jcass77/mopidy,woutervanwijk/mopidy,dbrgn/mopidy,ali/mopidy,SuperStarPL/mopidy,woutervanwijk/mopidy,ali/mopidy,swak/mopidy,diandiankan/mopidy,ZenithDK/mopidy,abarisain/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,quartz55/mopidy,bacontext/mopidy,hkariti/mopidy,vrs01/mopidy,ZenithDK/mopidy,vrs01/mopidy,glogiotatidis/mopidy,abarisain/mopidy,jodal/mopidy,adamcik/mopidy,rawdlite/mopidy,vrs01/mopidy,adamcik/mopidy,jcass77/mopidy,pacificIT/mopidy,glogiotatidis/mopidy,mokieyue/mopidy,rawdlite/mopidy,tkem/mopidy,jcass77/mopidy,jmarsik/mopidy,mopidy/mopidy,priestd09/mopidy,ZenithDK/mopidy,ali/mopidy,kingosticks/mopidy,tkem/mopidy,bencevans/mopidy,priestd09/mopidy,swak/mopidy,mopidy/mopidy,bacontext/mopidy,bencevans/mopidy,diandiankan/mopidy,mopidy/mopidy,pacificIT/mopidy,liamw9534/mopidy,SuperStarPL/mopidy,tkem/mopidy,vrs01/mopidy,bacontext/mopidy,bencevans/mopidy,quartz55/mopidy,bencevans/mopidy,diandiankan/mopidy,bacontext/mopidy,mokieyue/mopidy,hkariti/mopidy,glogiotatidis/mopidy,rawdlite/mopidy,ZenithDK/mopidy,jodal/mopidy,kingosticks/mopidy | import logging
+ from multiprocessing.reduction import reduce_connection
+ import pickle
from mopidy import settings as raw_settings
logger = logging.getLogger('mopidy')
def get_version():
return u'0.1.dev'
def get_mpd_protocol_version():
return u'0.16.0'
def get_class(name):
module_name = name[:name.rindex('.')]
class_name = name[name.rindex('.') + 1:]
logger.info('Loading: %s from %s', class_name, module_name)
module = __import__(module_name, globals(), locals(), [class_name], -1)
class_object = getattr(module, class_name)
return class_object
+ def pickle_connection(connection):
+ return pickle.dumps(reduce_connection(connection))
+
+ def unpickle_connection(pickled_connection):
+ # From http://stackoverflow.com/questions/1446004
+ unpickled = pickle.loads(pickled_connection)
+ func = unpickled[0]
+ args = unpickled[1]
+ return func(*args)
+
class SettingsError(Exception):
pass
class Settings(object):
def __getattr__(self, attr):
if not hasattr(raw_settings, attr):
raise SettingsError(u'Setting "%s" is not set.' % attr)
value = getattr(raw_settings, attr)
if type(value) != bool and not value:
raise SettingsError(u'Setting "%s" is empty.' % attr)
return value
settings = Settings()
| Add util functions for pickling and unpickling multiprocessing.Connection | ## Code Before:
import logging
from mopidy import settings as raw_settings
logger = logging.getLogger('mopidy')
def get_version():
return u'0.1.dev'
def get_mpd_protocol_version():
return u'0.16.0'
def get_class(name):
module_name = name[:name.rindex('.')]
class_name = name[name.rindex('.') + 1:]
logger.info('Loading: %s from %s', class_name, module_name)
module = __import__(module_name, globals(), locals(), [class_name], -1)
class_object = getattr(module, class_name)
return class_object
class SettingsError(Exception):
pass
class Settings(object):
def __getattr__(self, attr):
if not hasattr(raw_settings, attr):
raise SettingsError(u'Setting "%s" is not set.' % attr)
value = getattr(raw_settings, attr)
if type(value) != bool and not value:
raise SettingsError(u'Setting "%s" is empty.' % attr)
return value
settings = Settings()
## Instruction:
Add util functions for pickling and unpickling multiprocessing.Connection
## Code After:
import logging
from multiprocessing.reduction import reduce_connection
import pickle
from mopidy import settings as raw_settings
logger = logging.getLogger('mopidy')
def get_version():
return u'0.1.dev'
def get_mpd_protocol_version():
return u'0.16.0'
def get_class(name):
module_name = name[:name.rindex('.')]
class_name = name[name.rindex('.') + 1:]
logger.info('Loading: %s from %s', class_name, module_name)
module = __import__(module_name, globals(), locals(), [class_name], -1)
class_object = getattr(module, class_name)
return class_object
def pickle_connection(connection):
return pickle.dumps(reduce_connection(connection))
def unpickle_connection(pickled_connection):
# From http://stackoverflow.com/questions/1446004
unpickled = pickle.loads(pickled_connection)
func = unpickled[0]
args = unpickled[1]
return func(*args)
class SettingsError(Exception):
pass
class Settings(object):
def __getattr__(self, attr):
if not hasattr(raw_settings, attr):
raise SettingsError(u'Setting "%s" is not set.' % attr)
value = getattr(raw_settings, attr)
if type(value) != bool and not value:
raise SettingsError(u'Setting "%s" is empty.' % attr)
return value
settings = Settings()
|
a8bd6e86583b72211f028ecb51df2ee27550b258 | submit.py | submit.py | import json
import requests
import argparse
parser = argparse.ArgumentParser(
description="Upload submission from submit.cancergenetrust.org")
parser.add_argument('file', nargs='?', default="submission.json",
help="Path to json file to submit")
args = parser.parse_args()
with open(args.file) as f:
submission = json.loads(f.read())
submission["clinical"]["CGT Public ID"] = submission["patientId"]
r = requests.post("http://localhost:5000/v0/submissions?publish=true",
files=[("files[]",
("foundationone.json",
json.dumps(submission["genomic"], sort_keys=True)))],
data=submission["clinical"])
print(r.text)
assert(r.status_code == requests.codes.ok)
| import json
import requests
import argparse
parser = argparse.ArgumentParser(
description="Upload submission from submit.cancergenetrust.org")
parser.add_argument('file', nargs='?', default="submission.json",
help="Path to json file to submit")
args = parser.parse_args()
with open(args.file) as f:
submission = json.loads(f.read())
submission["clinical"]["CGT Public ID"] = submission["patientId"]
if submission["genomic"]:
print("Submitting clinical and genomic data")
r = requests.post("http://localhost:5000/v0/submissions?publish=true",
files=[("files[]",
("foundationone.json",
json.dumps(submission["genomic"], sort_keys=True)))],
data=submission["clinical"])
else:
print("No genomic data, submitting only clinical")
r = requests.post("http://localhost:5000/v0/submissions?publish=true",
data=submission["clinical"])
print(r.text)
assert(r.status_code == requests.codes.ok)
| Handle only clinical, no genomic, submission | Handle only clinical, no genomic, submission
| Python | apache-2.0 | ga4gh/CGT,ga4gh/CGT,ga4gh/CGT | import json
import requests
import argparse
parser = argparse.ArgumentParser(
description="Upload submission from submit.cancergenetrust.org")
parser.add_argument('file', nargs='?', default="submission.json",
help="Path to json file to submit")
args = parser.parse_args()
with open(args.file) as f:
submission = json.loads(f.read())
submission["clinical"]["CGT Public ID"] = submission["patientId"]
+ if submission["genomic"]:
+ print("Submitting clinical and genomic data")
- r = requests.post("http://localhost:5000/v0/submissions?publish=true",
+ r = requests.post("http://localhost:5000/v0/submissions?publish=true",
- files=[("files[]",
+ files=[("files[]",
- ("foundationone.json",
+ ("foundationone.json",
- json.dumps(submission["genomic"], sort_keys=True)))],
+ json.dumps(submission["genomic"], sort_keys=True)))],
- data=submission["clinical"])
+ data=submission["clinical"])
+ else:
+ print("No genomic data, submitting only clinical")
+ r = requests.post("http://localhost:5000/v0/submissions?publish=true",
+ data=submission["clinical"])
print(r.text)
assert(r.status_code == requests.codes.ok)
| Handle only clinical, no genomic, submission | ## Code Before:
import json
import requests
import argparse
parser = argparse.ArgumentParser(
description="Upload submission from submit.cancergenetrust.org")
parser.add_argument('file', nargs='?', default="submission.json",
help="Path to json file to submit")
args = parser.parse_args()
with open(args.file) as f:
submission = json.loads(f.read())
submission["clinical"]["CGT Public ID"] = submission["patientId"]
r = requests.post("http://localhost:5000/v0/submissions?publish=true",
files=[("files[]",
("foundationone.json",
json.dumps(submission["genomic"], sort_keys=True)))],
data=submission["clinical"])
print(r.text)
assert(r.status_code == requests.codes.ok)
## Instruction:
Handle only clinical, no genomic, submission
## Code After:
import json
import requests
import argparse
parser = argparse.ArgumentParser(
description="Upload submission from submit.cancergenetrust.org")
parser.add_argument('file', nargs='?', default="submission.json",
help="Path to json file to submit")
args = parser.parse_args()
with open(args.file) as f:
submission = json.loads(f.read())
submission["clinical"]["CGT Public ID"] = submission["patientId"]
if submission["genomic"]:
print("Submitting clinical and genomic data")
r = requests.post("http://localhost:5000/v0/submissions?publish=true",
files=[("files[]",
("foundationone.json",
json.dumps(submission["genomic"], sort_keys=True)))],
data=submission["clinical"])
else:
print("No genomic data, submitting only clinical")
r = requests.post("http://localhost:5000/v0/submissions?publish=true",
data=submission["clinical"])
print(r.text)
assert(r.status_code == requests.codes.ok)
|
81904effd492e2b2cea64dc98b29033261ae8b62 | tests/generator_test.py | tests/generator_test.py | from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
class GeneratorTest(GeneratorTest):
def testLotsaModelsGenerated(self):
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
| from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
class GeneratorTest(GeneratorTest):
def testLotsaModelsGenerated(self):
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
assert len(self.klasses) > 100
| Check that we are creating Test Classes | Check that we are creating Test Classes
| Python | mit | talkiq/gaend,samedhi/gaend,talkiq/gaend,samedhi/gaend | from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
class GeneratorTest(GeneratorTest):
def testLotsaModelsGenerated(self):
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
+ assert len(self.klasses) > 100
+ | Check that we are creating Test Classes | ## Code Before:
from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
class GeneratorTest(GeneratorTest):
def testLotsaModelsGenerated(self):
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
## Instruction:
Check that we are creating Test Classes
## Code After:
from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
class GeneratorTest(GeneratorTest):
def testLotsaModelsGenerated(self):
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
assert len(self.klasses) > 100
|
bc36a19d3bb1c07cbe2a44de88f227ef71c50b8c | notebooks/utils.py | notebooks/utils.py | def print_generated_sequence(g, num, *, sep=", "):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `g`.
"""
elems = [str(next(g)) for _ in range(num)]
sep_initial = "\n" if sep == "\n" else " "
print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
| def print_generated_sequence(g, num, *, sep=", ", seed=None):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `g`.
"""
if seed:
g.reset(seed)
elems = [str(next(g)) for _ in range(num)]
sep_initial = "\n" if sep == "\n" else " "
print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
| Allow passing seed directly to helper function | Allow passing seed directly to helper function
| Python | mit | maxalbert/tohu | - def print_generated_sequence(g, num, *, sep=", "):
+ def print_generated_sequence(g, num, *, sep=", ", seed=None):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `g`.
"""
+ if seed:
+ g.reset(seed)
elems = [str(next(g)) for _ in range(num)]
sep_initial = "\n" if sep == "\n" else " "
print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
| Allow passing seed directly to helper function | ## Code Before:
def print_generated_sequence(g, num, *, sep=", "):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `g`.
"""
elems = [str(next(g)) for _ in range(num)]
sep_initial = "\n" if sep == "\n" else " "
print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
## Instruction:
Allow passing seed directly to helper function
## Code After:
def print_generated_sequence(g, num, *, sep=", ", seed=None):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `g`.
"""
if seed:
g.reset(seed)
elems = [str(next(g)) for _ in range(num)]
sep_initial = "\n" if sep == "\n" else " "
print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
|
44223235e5b8b0c49df564ae190927905de1f9a4 | plenario/worker.py | plenario/worker.py | from datetime import datetime
from flask import Flask
import plenario.tasks as tasks
def create_worker():
app = Flask(__name__)
app.config.from_object('plenario.settings')
app.url_map.strict_slashes = False
@app.route('/update/weather', methods=['POST'])
def weather():
return tasks.update_weather.delay().id
@app.route('/update/often', methods=['POST'])
def metar():
return tasks.update_metar.delay().id
@app.route('/update/<frequency>', methods=['POST'])
def update(frequency):
return tasks.frequency_update.delay(frequency).id
@app.route('/archive', methods=['POST'])
def archive():
return tasks.archive.delay(datetime.now()).id
@app.route('/resolve', methods=['POST'])
def resolve():
return tasks.resolve.delay().id
@app.route('/health', methods=['GET', 'POST'])
def check_health():
return tasks.health.delay().id
return app
| import os
from datetime import datetime
from flask import Flask
import plenario.tasks as tasks
def create_worker():
app = Flask(__name__)
app.config.from_object('plenario.settings')
app.url_map.strict_slashes = False
@app.route('/update/weather', methods=['POST'])
def weather():
return tasks.update_weather.delay().id
@app.route('/update/often', methods=['POST'])
def metar():
return tasks.update_metar.delay().id
@app.route('/update/<frequency>', methods=['POST'])
def update(frequency):
return tasks.frequency_update.delay(frequency).id
@app.route('/archive', methods=['POST'])
def archive():
return tasks.archive.delay(datetime.now()).id
@app.route('/resolve', methods=['POST'])
def resolve():
if not os.environ.get('PRIVATE'):
return 'hullo'
return tasks.resolve.delay().id
@app.route('/health', methods=['GET', 'POST'])
def check_health():
return tasks.health.delay().id
return app
| Add temporary check to block production resolve | Add temporary check to block production resolve
| Python | mit | UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario | + import os
from datetime import datetime
from flask import Flask
import plenario.tasks as tasks
def create_worker():
app = Flask(__name__)
app.config.from_object('plenario.settings')
app.url_map.strict_slashes = False
@app.route('/update/weather', methods=['POST'])
def weather():
return tasks.update_weather.delay().id
@app.route('/update/often', methods=['POST'])
def metar():
return tasks.update_metar.delay().id
@app.route('/update/<frequency>', methods=['POST'])
def update(frequency):
return tasks.frequency_update.delay(frequency).id
@app.route('/archive', methods=['POST'])
def archive():
return tasks.archive.delay(datetime.now()).id
@app.route('/resolve', methods=['POST'])
def resolve():
+ if not os.environ.get('PRIVATE'):
+ return 'hullo'
return tasks.resolve.delay().id
@app.route('/health', methods=['GET', 'POST'])
def check_health():
return tasks.health.delay().id
return app
| Add temporary check to block production resolve | ## Code Before:
from datetime import datetime
from flask import Flask
import plenario.tasks as tasks
def create_worker():
app = Flask(__name__)
app.config.from_object('plenario.settings')
app.url_map.strict_slashes = False
@app.route('/update/weather', methods=['POST'])
def weather():
return tasks.update_weather.delay().id
@app.route('/update/often', methods=['POST'])
def metar():
return tasks.update_metar.delay().id
@app.route('/update/<frequency>', methods=['POST'])
def update(frequency):
return tasks.frequency_update.delay(frequency).id
@app.route('/archive', methods=['POST'])
def archive():
return tasks.archive.delay(datetime.now()).id
@app.route('/resolve', methods=['POST'])
def resolve():
return tasks.resolve.delay().id
@app.route('/health', methods=['GET', 'POST'])
def check_health():
return tasks.health.delay().id
return app
## Instruction:
Add temporary check to block production resolve
## Code After:
import os
from datetime import datetime
from flask import Flask
import plenario.tasks as tasks
def create_worker():
app = Flask(__name__)
app.config.from_object('plenario.settings')
app.url_map.strict_slashes = False
@app.route('/update/weather', methods=['POST'])
def weather():
return tasks.update_weather.delay().id
@app.route('/update/often', methods=['POST'])
def metar():
return tasks.update_metar.delay().id
@app.route('/update/<frequency>', methods=['POST'])
def update(frequency):
return tasks.frequency_update.delay(frequency).id
@app.route('/archive', methods=['POST'])
def archive():
return tasks.archive.delay(datetime.now()).id
@app.route('/resolve', methods=['POST'])
def resolve():
if not os.environ.get('PRIVATE'):
return 'hullo'
return tasks.resolve.delay().id
@app.route('/health', methods=['GET', 'POST'])
def check_health():
return tasks.health.delay().id
return app
|
2ec93f385e9eea63d42e17a2a777b459edf93816 | tools/debug_adapter.py | tools/debug_adapter.py | import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server(multiple=False)
| import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| Update code for changed function. | Update code for changed function.
| Python | mit | vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb | import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
- adapter.main.run_tcp_server(multiple=False)
+ adapter.main.run_tcp_server()
| Update code for changed function. | ## Code Before:
import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server(multiple=False)
## Instruction:
Update code for changed function.
## Code After:
import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
|
143b74a2c6f99d2d92ac85310351327ffb630c1e | uscampgrounds/admin.py | uscampgrounds/admin.py | from django.contrib.gis import admin
from uscampgrounds.models import *
class CampgroundAdmin(admin.OSMGeoAdmin):
list_display = ('name', 'campground_code', 'campground_type', 'phone', 'sites', 'elevation', 'hookups', 'amenities')
list_filter = ('campground_type',)
admin.site.register(Campground, CampgroundAdmin)
| from django.contrib.gis import admin
from uscampgrounds.models import *
class CampgroundAdmin(admin.OSMGeoAdmin):
list_display = ('name', 'campground_code', 'campground_type', 'phone', 'sites', 'elevation', 'hookups', 'amenities')
list_filter = ('campground_type',)
search_fields = ('name',)
admin.site.register(Campground, CampgroundAdmin)
| Allow searching campgrounds by name for convenience. | Allow searching campgrounds by name for convenience.
| Python | bsd-3-clause | adamfast/geodjango-uscampgrounds,adamfast/geodjango-uscampgrounds | from django.contrib.gis import admin
from uscampgrounds.models import *
class CampgroundAdmin(admin.OSMGeoAdmin):
list_display = ('name', 'campground_code', 'campground_type', 'phone', 'sites', 'elevation', 'hookups', 'amenities')
list_filter = ('campground_type',)
+ search_fields = ('name',)
admin.site.register(Campground, CampgroundAdmin)
| Allow searching campgrounds by name for convenience. | ## Code Before:
from django.contrib.gis import admin
from uscampgrounds.models import *
class CampgroundAdmin(admin.OSMGeoAdmin):
list_display = ('name', 'campground_code', 'campground_type', 'phone', 'sites', 'elevation', 'hookups', 'amenities')
list_filter = ('campground_type',)
admin.site.register(Campground, CampgroundAdmin)
## Instruction:
Allow searching campgrounds by name for convenience.
## Code After:
from django.contrib.gis import admin
from uscampgrounds.models import *
class CampgroundAdmin(admin.OSMGeoAdmin):
list_display = ('name', 'campground_code', 'campground_type', 'phone', 'sites', 'elevation', 'hookups', 'amenities')
list_filter = ('campground_type',)
search_fields = ('name',)
admin.site.register(Campground, CampgroundAdmin)
|
3dd5cd27963a0cfeb446a36fcd50c05e7c715eb3 | cyder/api/v1/endpoints/api.py | cyder/api/v1/endpoints/api.py | from django.utils.decorators import classonlymethod
from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, viewsets
NestedAVFields = ['id', 'attribute', 'value']
class CommonAPISerializer(serializers.ModelSerializer):
pass
class CommonAPINestedAVSerializer(serializers.ModelSerializer):
attribute = serializers.SlugRelatedField(slug_field='name')
class CommonAPIMeta:
pass
class CommonAPIViewSet(viewsets.ModelViewSet):
def __init__(self, *args, **kwargs):
self.queryset = self.model.objects.all()
super(CommonAPIViewSet, self).__init__(*args, **kwargs)
#@classonlymethod
#@csrf_exempt
#def as_view(cls, *args, **kwargs):
# super(CommonAPIViewSet, cls).as_view(*args, **kwargs) | from rest_framework import serializers, viewsets
NestedAVFields = ['id', 'attribute', 'value']
class CommonAPISerializer(serializers.ModelSerializer):
pass
class CommonAPINestedAVSerializer(serializers.ModelSerializer):
attribute = serializers.SlugRelatedField(slug_field='name')
class CommonAPIMeta:
pass
class CommonAPIViewSet(viewsets.ModelViewSet):
def __init__(self, *args, **kwargs):
self.queryset = self.model.objects.all()
super(CommonAPIViewSet, self).__init__(*args, **kwargs)
| Fix earlier folly (commented and useless code) | Fix earlier folly (commented and useless code)
| Python | bsd-3-clause | akeym/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder,murrown/cyder,murrown/cyder,murrown/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder,zeeman/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,drkitty/cyder,akeym/cyder,zeeman/cyder | - from django.utils.decorators import classonlymethod
- from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, viewsets
NestedAVFields = ['id', 'attribute', 'value']
class CommonAPISerializer(serializers.ModelSerializer):
pass
class CommonAPINestedAVSerializer(serializers.ModelSerializer):
attribute = serializers.SlugRelatedField(slug_field='name')
class CommonAPIMeta:
pass
class CommonAPIViewSet(viewsets.ModelViewSet):
def __init__(self, *args, **kwargs):
self.queryset = self.model.objects.all()
super(CommonAPIViewSet, self).__init__(*args, **kwargs)
- #@classonlymethod
- #@csrf_exempt
- #def as_view(cls, *args, **kwargs):
- # super(CommonAPIViewSet, cls).as_view(*args, **kwargs) | Fix earlier folly (commented and useless code) | ## Code Before:
from django.utils.decorators import classonlymethod
from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, viewsets
NestedAVFields = ['id', 'attribute', 'value']
class CommonAPISerializer(serializers.ModelSerializer):
pass
class CommonAPINestedAVSerializer(serializers.ModelSerializer):
attribute = serializers.SlugRelatedField(slug_field='name')
class CommonAPIMeta:
pass
class CommonAPIViewSet(viewsets.ModelViewSet):
def __init__(self, *args, **kwargs):
self.queryset = self.model.objects.all()
super(CommonAPIViewSet, self).__init__(*args, **kwargs)
#@classonlymethod
#@csrf_exempt
#def as_view(cls, *args, **kwargs):
# super(CommonAPIViewSet, cls).as_view(*args, **kwargs)
## Instruction:
Fix earlier folly (commented and useless code)
## Code After:
from rest_framework import serializers, viewsets
NestedAVFields = ['id', 'attribute', 'value']
class CommonAPISerializer(serializers.ModelSerializer):
pass
class CommonAPINestedAVSerializer(serializers.ModelSerializer):
attribute = serializers.SlugRelatedField(slug_field='name')
class CommonAPIMeta:
pass
class CommonAPIViewSet(viewsets.ModelViewSet):
def __init__(self, *args, **kwargs):
self.queryset = self.model.objects.all()
super(CommonAPIViewSet, self).__init__(*args, **kwargs)
|
fd5cad381e8b821bfabbefc9deb4b8a4531844f6 | rnacentral_pipeline/rnacentral/notify/slack.py | rnacentral_pipeline/rnacentral/notify/slack.py |
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHOOK is None:
raise SystemExit("SLACK_WEBHOOK environment variable not defined")
if plain:
slack_json = {
"text" : title + ': ' + message
}
else:
slack_json = {
"text" : title,
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": message
},
},
]
}
try:
response = requests.post(SLACK_WEBHOOK,
json=slack_json,
headers={'Content-Type':'application/json'}
)
response.raise_for_status()
except Exception as request_exception:
raise SystemExit from request_exception
|
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHOOK is None:
try:
from rnacentral_pipeline.secrets import SLACK_WEBHOOK
except:
raise SystemExit("SLACK_WEBHOOK environment variable not defined, and couldn't find a secrets file")
if plain:
slack_json = {
"text" : title + ': ' + message
}
else:
slack_json = {
"text" : title,
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": message
},
},
]
}
try:
response = requests.post(SLACK_WEBHOOK,
json=slack_json,
headers={'Content-Type':'application/json'}
)
response.raise_for_status()
except Exception as request_exception:
raise SystemExit from request_exception
| Add a secrets file in rnac notify | Add a secrets file in rnac notify
Nextflow doesn't propagate environment variables from the profile into
the event handler closures. This is the simplest workaround for that.
secrets.py should be on the cluster and symlinked into
rnacentral_pipeline
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline |
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHOOK is None:
+ try:
+ from rnacentral_pipeline.secrets import SLACK_WEBHOOK
+ except:
- raise SystemExit("SLACK_WEBHOOK environment variable not defined")
+ raise SystemExit("SLACK_WEBHOOK environment variable not defined, and couldn't find a secrets file")
if plain:
slack_json = {
"text" : title + ': ' + message
}
else:
slack_json = {
"text" : title,
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": message
},
},
]
}
try:
response = requests.post(SLACK_WEBHOOK,
json=slack_json,
headers={'Content-Type':'application/json'}
)
response.raise_for_status()
except Exception as request_exception:
raise SystemExit from request_exception
| Add a secrets file in rnac notify | ## Code Before:
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHOOK is None:
raise SystemExit("SLACK_WEBHOOK environment variable not defined")
if plain:
slack_json = {
"text" : title + ': ' + message
}
else:
slack_json = {
"text" : title,
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": message
},
},
]
}
try:
response = requests.post(SLACK_WEBHOOK,
json=slack_json,
headers={'Content-Type':'application/json'}
)
response.raise_for_status()
except Exception as request_exception:
raise SystemExit from request_exception
## Instruction:
Add a secrets file in rnac notify
## Code After:
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHOOK is None:
try:
from rnacentral_pipeline.secrets import SLACK_WEBHOOK
except:
raise SystemExit("SLACK_WEBHOOK environment variable not defined, and couldn't find a secrets file")
if plain:
slack_json = {
"text" : title + ': ' + message
}
else:
slack_json = {
"text" : title,
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": message
},
},
]
}
try:
response = requests.post(SLACK_WEBHOOK,
json=slack_json,
headers={'Content-Type':'application/json'}
)
response.raise_for_status()
except Exception as request_exception:
raise SystemExit from request_exception
|
5df350254e966007f80f7a14fde29a8c93316bb3 | tests/rules/test_git_push.py | tests/rules/test_git_push.py | import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
| import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push --quiet', stderr=stderr))\
== "git push --set-upstream origin master --quiet"
| Check arguments are preserved in git_push | Check arguments are preserved in git_push
| Python | mit | scorphus/thefuck,mlk/thefuck,Clpsplug/thefuck,SimenB/thefuck,nvbn/thefuck,Clpsplug/thefuck,SimenB/thefuck,mlk/thefuck,nvbn/thefuck,scorphus/thefuck | import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
+ assert get_new_command(Command('git push --quiet', stderr=stderr))\
+ == "git push --set-upstream origin master --quiet"
| Check arguments are preserved in git_push | ## Code Before:
import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
## Instruction:
Check arguments are preserved in git_push
## Code After:
import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push --quiet', stderr=stderr))\
== "git push --set-upstream origin master --quiet"
|
c09a8ce5bb47db4ea4381925ec07199415ae5c39 | spacy/tests/integration/test_load_languages.py | spacy/tests/integration/test_load_languages.py | from __future__ import unicode_literals
from ...fr import French
def test_load_french():
nlp = French()
doc = nlp(u'Parlez-vous français?')
| from __future__ import unicode_literals
from ...fr import French
def test_load_french():
nlp = French()
doc = nlp(u'Parlez-vous français?')
assert doc[0].text == u'Parlez'
assert doc[1].text == u'-'
assert doc[2].text == u'vouz'
assert doc[3].text == u'français'
assert doc[4].text == u'?'
| Add test for french tokenizer | Add test for french tokenizer
| Python | mit | raphael0202/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,raphael0202/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,banglakit/spaCy,recognai/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,recognai/spaCy,banglakit/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,honnibal/spaCy,aikramer2/spaCy,explosion/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,banglakit/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,banglakit/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy | from __future__ import unicode_literals
from ...fr import French
def test_load_french():
nlp = French()
doc = nlp(u'Parlez-vous français?')
+ assert doc[0].text == u'Parlez'
+ assert doc[1].text == u'-'
+ assert doc[2].text == u'vouz'
+ assert doc[3].text == u'français'
+ assert doc[4].text == u'?'
| Add test for french tokenizer | ## Code Before:
from __future__ import unicode_literals
from ...fr import French
def test_load_french():
nlp = French()
doc = nlp(u'Parlez-vous français?')
## Instruction:
Add test for french tokenizer
## Code After:
from __future__ import unicode_literals
from ...fr import French
def test_load_french():
nlp = French()
doc = nlp(u'Parlez-vous français?')
assert doc[0].text == u'Parlez'
assert doc[1].text == u'-'
assert doc[2].text == u'vouz'
assert doc[3].text == u'français'
assert doc[4].text == u'?'
|
b718c1d817e767c336654001f3aaea5d7327625a | wsgi_intercept/requests_intercept.py | wsgi_intercept/requests_intercept.py |
from . import WSGI_HTTPConnection, WSGI_HTTPSConnection, wsgi_fake_socket
from requests.packages.urllib3.connectionpool import (HTTPConnectionPool,
HTTPSConnectionPool)
from requests.packages.urllib3.connection import (HTTPConnection,
HTTPSConnection)
wsgi_fake_socket.settimeout = lambda self, timeout: None
class HTTP_WSGIInterceptor(WSGI_HTTPConnection, HTTPConnection):
pass
class HTTPS_WSGIInterceptor(WSGI_HTTPSConnection, HTTPSConnection):
pass
def install():
HTTPConnectionPool.ConnectionCls = HTTP_WSGIInterceptor
HTTPSConnectionPool.ConnectionCls = HTTPS_WSGIInterceptor
def uninstall():
HTTPConnectionPool.ConnectionCls = HTTPConnection
HTTPSConnectionPool.ConnectionCls = HTTPSConnection
|
import sys
from . import WSGI_HTTPConnection, WSGI_HTTPSConnection, wsgi_fake_socket
from requests.packages.urllib3.connectionpool import (HTTPConnectionPool,
HTTPSConnectionPool)
from requests.packages.urllib3.connection import (HTTPConnection,
HTTPSConnection)
wsgi_fake_socket.settimeout = lambda self, timeout: None
class HTTP_WSGIInterceptor(WSGI_HTTPConnection, HTTPConnection):
def __init__(self, *args, **kwargs):
if 'strict' in kwargs and sys.version_info > (3, 0):
kwargs.pop('strict')
WSGI_HTTPConnection.__init__(self, *args, **kwargs)
HTTPConnection.__init__(self, *args, **kwargs)
class HTTPS_WSGIInterceptor(WSGI_HTTPSConnection, HTTPSConnection):
def __init__(self, *args, **kwargs):
if 'strict' in kwargs and sys.version_info > (3, 0):
kwargs.pop('strict')
WSGI_HTTPSConnection.__init__(self, *args, **kwargs)
HTTPSConnection.__init__(self, *args, **kwargs)
def install():
HTTPConnectionPool.ConnectionCls = HTTP_WSGIInterceptor
HTTPSConnectionPool.ConnectionCls = HTTPS_WSGIInterceptor
def uninstall():
HTTPConnectionPool.ConnectionCls = HTTPConnection
HTTPSConnectionPool.ConnectionCls = HTTPSConnection
| Deal with request's urllib3 being annoying about 'strict' | Deal with request's urllib3 being annoying about 'strict'
These changes are required to get tests to pass in python3.4 (and
presumably others).
This is entirely code from @sashahart, who had done the work earlier
to deal with with some Debian related issues uncovered by @thomasgoirand.
These changes will probably mean the debian packages will need to be
updated when the next version is released.
| Python | mit | sileht/python3-wsgi-intercept,cdent/wsgi-intercept | +
+ import sys
from . import WSGI_HTTPConnection, WSGI_HTTPSConnection, wsgi_fake_socket
from requests.packages.urllib3.connectionpool import (HTTPConnectionPool,
HTTPSConnectionPool)
from requests.packages.urllib3.connection import (HTTPConnection,
HTTPSConnection)
wsgi_fake_socket.settimeout = lambda self, timeout: None
class HTTP_WSGIInterceptor(WSGI_HTTPConnection, HTTPConnection):
- pass
+ def __init__(self, *args, **kwargs):
+ if 'strict' in kwargs and sys.version_info > (3, 0):
+ kwargs.pop('strict')
+ WSGI_HTTPConnection.__init__(self, *args, **kwargs)
+ HTTPConnection.__init__(self, *args, **kwargs)
class HTTPS_WSGIInterceptor(WSGI_HTTPSConnection, HTTPSConnection):
- pass
+ def __init__(self, *args, **kwargs):
+ if 'strict' in kwargs and sys.version_info > (3, 0):
+ kwargs.pop('strict')
+ WSGI_HTTPSConnection.__init__(self, *args, **kwargs)
+ HTTPSConnection.__init__(self, *args, **kwargs)
def install():
HTTPConnectionPool.ConnectionCls = HTTP_WSGIInterceptor
HTTPSConnectionPool.ConnectionCls = HTTPS_WSGIInterceptor
def uninstall():
HTTPConnectionPool.ConnectionCls = HTTPConnection
HTTPSConnectionPool.ConnectionCls = HTTPSConnection
| Deal with request's urllib3 being annoying about 'strict' | ## Code Before:
from . import WSGI_HTTPConnection, WSGI_HTTPSConnection, wsgi_fake_socket
from requests.packages.urllib3.connectionpool import (HTTPConnectionPool,
HTTPSConnectionPool)
from requests.packages.urllib3.connection import (HTTPConnection,
HTTPSConnection)
wsgi_fake_socket.settimeout = lambda self, timeout: None
class HTTP_WSGIInterceptor(WSGI_HTTPConnection, HTTPConnection):
pass
class HTTPS_WSGIInterceptor(WSGI_HTTPSConnection, HTTPSConnection):
pass
def install():
HTTPConnectionPool.ConnectionCls = HTTP_WSGIInterceptor
HTTPSConnectionPool.ConnectionCls = HTTPS_WSGIInterceptor
def uninstall():
HTTPConnectionPool.ConnectionCls = HTTPConnection
HTTPSConnectionPool.ConnectionCls = HTTPSConnection
## Instruction:
Deal with request's urllib3 being annoying about 'strict'
## Code After:
import sys
from . import WSGI_HTTPConnection, WSGI_HTTPSConnection, wsgi_fake_socket
from requests.packages.urllib3.connectionpool import (HTTPConnectionPool,
HTTPSConnectionPool)
from requests.packages.urllib3.connection import (HTTPConnection,
HTTPSConnection)
wsgi_fake_socket.settimeout = lambda self, timeout: None
class HTTP_WSGIInterceptor(WSGI_HTTPConnection, HTTPConnection):
def __init__(self, *args, **kwargs):
if 'strict' in kwargs and sys.version_info > (3, 0):
kwargs.pop('strict')
WSGI_HTTPConnection.__init__(self, *args, **kwargs)
HTTPConnection.__init__(self, *args, **kwargs)
class HTTPS_WSGIInterceptor(WSGI_HTTPSConnection, HTTPSConnection):
def __init__(self, *args, **kwargs):
if 'strict' in kwargs and sys.version_info > (3, 0):
kwargs.pop('strict')
WSGI_HTTPSConnection.__init__(self, *args, **kwargs)
HTTPSConnection.__init__(self, *args, **kwargs)
def install():
HTTPConnectionPool.ConnectionCls = HTTP_WSGIInterceptor
HTTPSConnectionPool.ConnectionCls = HTTPS_WSGIInterceptor
def uninstall():
HTTPConnectionPool.ConnectionCls = HTTPConnection
HTTPSConnectionPool.ConnectionCls = HTTPSConnection
|
2843052a222541e3b7ce45fa633f5df61b10a809 | test/oracle.py | test/oracle.py | import qnd
import tensorflow as tf
def model_fn(x, y):
return (y,
0.0,
tf.contrib.framework.get_or_create_global_step().assign_add())
def input_fn(q):
shape = (100,)
return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32)
train_and_evaluate = qnd.def_train_and_evaluate()
def main():
train_and_evaluate(model_fn, input_fn)
if __name__ == "__main__":
main()
| import qnd
import tensorflow as tf
def model_fn(x, y):
return (y,
0.0,
tf.contrib.framework.get_or_create_global_step().assign_add())
def input_fn(q):
shape = (100,)
return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32)
train_and_evaluate = qnd.def_train_and_evaluate(distributed=True)
def main():
train_and_evaluate(model_fn, input_fn)
if __name__ == "__main__":
main()
| Use distributed flag for xfail test | Use distributed flag for xfail test
| Python | unlicense | raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd | import qnd
import tensorflow as tf
def model_fn(x, y):
return (y,
0.0,
tf.contrib.framework.get_or_create_global_step().assign_add())
def input_fn(q):
shape = (100,)
return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32)
- train_and_evaluate = qnd.def_train_and_evaluate()
+ train_and_evaluate = qnd.def_train_and_evaluate(distributed=True)
def main():
train_and_evaluate(model_fn, input_fn)
if __name__ == "__main__":
main()
| Use distributed flag for xfail test | ## Code Before:
import qnd
import tensorflow as tf
def model_fn(x, y):
return (y,
0.0,
tf.contrib.framework.get_or_create_global_step().assign_add())
def input_fn(q):
shape = (100,)
return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32)
train_and_evaluate = qnd.def_train_and_evaluate()
def main():
train_and_evaluate(model_fn, input_fn)
if __name__ == "__main__":
main()
## Instruction:
Use distributed flag for xfail test
## Code After:
import qnd
import tensorflow as tf
def model_fn(x, y):
return (y,
0.0,
tf.contrib.framework.get_or_create_global_step().assign_add())
def input_fn(q):
shape = (100,)
return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32)
train_and_evaluate = qnd.def_train_and_evaluate(distributed=True)
def main():
train_and_evaluate(model_fn, input_fn)
if __name__ == "__main__":
main()
|
1f914a04adb4ad7d39ca7104e2ea36acc76b18bd | pvextractor/tests/test_gui.py | pvextractor/tests/test_gui.py | import numpy as np
from numpy.testing import assert_allclose
import pytest
from astropy.io import fits
from ..pvextractor import extract_pv_slice
from ..geometry.path import Path
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5OK = False
import matplotlib as mpl
if mpl.__version__[0] == '2':
MPLOK = False
else:
MPLOK = True
@pytest.mark.skipif('not PYQT5OK or not MPLOK')
def test_gui():
hdu = make_test_hdu()
pv = PVSlicer(hdu, clim=(-0.02, 2))
pv.show(block=False)
x = [100,200,220,330,340]
y = [100,200,300,420,430]
for i in range(len(x)):
pv.fig.canvas.motion_notify_event(x[i],y[i])
pv.fig.canvas.button_press_event(x[i],y[i],1)
pv.fig.canvas.key_press_event('enter')
pv.fig.canvas.motion_notify_event(310,420)
pv.fig.canvas.button_press_event(410,420,1)
pv.fig.canvas.draw()
assert pv.pv_slice.data.shape == (5,2)
| import pytest
from distutils.version import LooseVersion
import matplotlib as mpl
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5OK = False
if LooseVersion(mpl.__version__) < LooseVersion('2'):
MPLOK = True
else:
MPLOK = False
@pytest.mark.skipif('not PYQT5OK or not MPLOK')
def test_gui():
hdu = make_test_hdu()
pv = PVSlicer(hdu, clim=(-0.02, 2))
pv.show(block=False)
x = [100, 200, 220, 330, 340]
y = [100, 200, 300, 420, 430]
for i in range(len(x)):
pv.fig.canvas.motion_notify_event(x[i], y[i])
pv.fig.canvas.button_press_event(x[i], y[i], 1)
pv.fig.canvas.key_press_event('enter')
pv.fig.canvas.motion_notify_event(310, 420)
pv.fig.canvas.button_press_event(410, 420, 1)
pv.fig.canvas.draw()
assert pv.pv_slice.data.shape == (5, 2)
| Use LooseVersion to compare version numbers | Use LooseVersion to compare version numbers
| Python | bsd-3-clause | radio-astro-tools/pvextractor,keflavich/pvextractor | - import numpy as np
- from numpy.testing import assert_allclose
import pytest
+ from distutils.version import LooseVersion
+ import matplotlib as mpl
- from astropy.io import fits
- from ..pvextractor import extract_pv_slice
- from ..geometry.path import Path
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5OK = False
- import matplotlib as mpl
- if mpl.__version__[0] == '2':
+
+ if LooseVersion(mpl.__version__) < LooseVersion('2'):
+ MPLOK = True
+ else:
MPLOK = False
+
- else:
- MPLOK = True
@pytest.mark.skipif('not PYQT5OK or not MPLOK')
def test_gui():
hdu = make_test_hdu()
pv = PVSlicer(hdu, clim=(-0.02, 2))
pv.show(block=False)
- x = [100,200,220,330,340]
+ x = [100, 200, 220, 330, 340]
- y = [100,200,300,420,430]
+ y = [100, 200, 300, 420, 430]
for i in range(len(x)):
- pv.fig.canvas.motion_notify_event(x[i],y[i])
+ pv.fig.canvas.motion_notify_event(x[i], y[i])
- pv.fig.canvas.button_press_event(x[i],y[i],1)
+ pv.fig.canvas.button_press_event(x[i], y[i], 1)
pv.fig.canvas.key_press_event('enter')
- pv.fig.canvas.motion_notify_event(310,420)
+ pv.fig.canvas.motion_notify_event(310, 420)
- pv.fig.canvas.button_press_event(410,420,1)
+ pv.fig.canvas.button_press_event(410, 420, 1)
pv.fig.canvas.draw()
- assert pv.pv_slice.data.shape == (5,2)
+ assert pv.pv_slice.data.shape == (5, 2)
| Use LooseVersion to compare version numbers | ## Code Before:
import numpy as np
from numpy.testing import assert_allclose
import pytest
from astropy.io import fits
from ..pvextractor import extract_pv_slice
from ..geometry.path import Path
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5OK = False
import matplotlib as mpl
if mpl.__version__[0] == '2':
MPLOK = False
else:
MPLOK = True
@pytest.mark.skipif('not PYQT5OK or not MPLOK')
def test_gui():
hdu = make_test_hdu()
pv = PVSlicer(hdu, clim=(-0.02, 2))
pv.show(block=False)
x = [100,200,220,330,340]
y = [100,200,300,420,430]
for i in range(len(x)):
pv.fig.canvas.motion_notify_event(x[i],y[i])
pv.fig.canvas.button_press_event(x[i],y[i],1)
pv.fig.canvas.key_press_event('enter')
pv.fig.canvas.motion_notify_event(310,420)
pv.fig.canvas.button_press_event(410,420,1)
pv.fig.canvas.draw()
assert pv.pv_slice.data.shape == (5,2)
## Instruction:
Use LooseVersion to compare version numbers
## Code After:
import pytest
from distutils.version import LooseVersion
import matplotlib as mpl
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5OK = False
if LooseVersion(mpl.__version__) < LooseVersion('2'):
MPLOK = True
else:
MPLOK = False
@pytest.mark.skipif('not PYQT5OK or not MPLOK')
def test_gui():
hdu = make_test_hdu()
pv = PVSlicer(hdu, clim=(-0.02, 2))
pv.show(block=False)
x = [100, 200, 220, 330, 340]
y = [100, 200, 300, 420, 430]
for i in range(len(x)):
pv.fig.canvas.motion_notify_event(x[i], y[i])
pv.fig.canvas.button_press_event(x[i], y[i], 1)
pv.fig.canvas.key_press_event('enter')
pv.fig.canvas.motion_notify_event(310, 420)
pv.fig.canvas.button_press_event(410, 420, 1)
pv.fig.canvas.draw()
assert pv.pv_slice.data.shape == (5, 2)
|
87c861f6ed0e73e21983edc3add35954b9f0def5 | apps/configuration/fields.py | apps/configuration/fields.py | import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(str):
return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
| import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(input):
valid_chars = ['\n', '\r']
return "".join(ch for ch in input if
unicodedata.category(ch)[0] != "C" or ch in valid_chars)
| Allow linebreaks textareas (should be valid in XML) | Allow linebreaks textareas (should be valid in XML)
| Python | apache-2.0 | CDE-UNIBE/qcat,CDE-UNIBE/qcat,CDE-UNIBE/qcat,CDE-UNIBE/qcat | import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
- def remove_control_characters(str):
+ def remove_control_characters(input):
- return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
+ valid_chars = ['\n', '\r']
+ return "".join(ch for ch in input if
+ unicodedata.category(ch)[0] != "C" or ch in valid_chars)
| Allow linebreaks textareas (should be valid in XML) | ## Code Before:
import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(str):
return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
## Instruction:
Allow linebreaks textareas (should be valid in XML)
## Code After:
import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(input):
valid_chars = ['\n', '\r']
return "".join(ch for ch in input if
unicodedata.category(ch)[0] != "C" or ch in valid_chars)
|
b61679efce39841120fcdb921acefbc729f4c4fd | tests/test_kmeans.py | tests/test_kmeans.py | import numpy as np
import milk.unsupervised
def test_kmeans():
features = np.r_[np.random.rand(20,3)-.5,.5+np.random.rand(20,3)]
centroids, _ = milk.unsupervised.kmeans(features,2)
positions = [0]*20 + [1]*20
correct = (centroids == positions).sum()
assert correct >= 38 or correct <= 2
| import numpy as np
import milk.unsupervised
def test_kmeans():
np.random.seed(132)
features = np.r_[np.random.rand(20,3)-.5,.5+np.random.rand(20,3)]
centroids, _ = milk.unsupervised.kmeans(features,2)
positions = [0]*20 + [1]*20
correct = (centroids == positions).sum()
assert correct >= 38 or correct <= 2
def test_kmeans_centroids():
np.random.seed(132)
features = np.random.rand(201,30)
for k in [2,3,5,10]:
indices,centroids = milk.unsupervised.kmeans(features, k)
for i in xrange(k):
assert np.allclose(centroids[i], features[indices == i].mean(0))
| Make sure results make sense | Make sure results make sense
| Python | mit | luispedro/milk,pombredanne/milk,luispedro/milk,pombredanne/milk,luispedro/milk,pombredanne/milk | import numpy as np
import milk.unsupervised
def test_kmeans():
+ np.random.seed(132)
features = np.r_[np.random.rand(20,3)-.5,.5+np.random.rand(20,3)]
centroids, _ = milk.unsupervised.kmeans(features,2)
positions = [0]*20 + [1]*20
correct = (centroids == positions).sum()
assert correct >= 38 or correct <= 2
+ def test_kmeans_centroids():
+ np.random.seed(132)
+ features = np.random.rand(201,30)
+ for k in [2,3,5,10]:
+ indices,centroids = milk.unsupervised.kmeans(features, k)
+ for i in xrange(k):
+ assert np.allclose(centroids[i], features[indices == i].mean(0))
+
+ | Make sure results make sense | ## Code Before:
import numpy as np
import milk.unsupervised
def test_kmeans():
features = np.r_[np.random.rand(20,3)-.5,.5+np.random.rand(20,3)]
centroids, _ = milk.unsupervised.kmeans(features,2)
positions = [0]*20 + [1]*20
correct = (centroids == positions).sum()
assert correct >= 38 or correct <= 2
## Instruction:
Make sure results make sense
## Code After:
import numpy as np
import milk.unsupervised
def test_kmeans():
np.random.seed(132)
features = np.r_[np.random.rand(20,3)-.5,.5+np.random.rand(20,3)]
centroids, _ = milk.unsupervised.kmeans(features,2)
positions = [0]*20 + [1]*20
correct = (centroids == positions).sum()
assert correct >= 38 or correct <= 2
def test_kmeans_centroids():
np.random.seed(132)
features = np.random.rand(201,30)
for k in [2,3,5,10]:
indices,centroids = milk.unsupervised.kmeans(features, k)
for i in xrange(k):
assert np.allclose(centroids[i], features[indices == i].mean(0))
|
e676877492057d7b370431f6896154702c8459f1 | webshack/auto_inject.py | webshack/auto_inject.py | from urllib.parse import urljoin
from urllib.request import urlopen
from urllib.error import URLError
import sys
GITHUB_USERS = [('Polymer', '0.5.2')]
def resolve_missing_user(user, branch, package):
assets = ["{}.html".format(package),
"{}.css".format(package),
"{}.js".format(package)]
base_url = "https://raw.githubusercontent.com/{user}/{package}/{branch}/".format(**locals())
matched_assets = []
for asset in assets:
asset_url = urljoin(base_url, asset)
try:
with urlopen(asset_url):
pass
matched_assets.append(asset)
except URLError:
pass
if matched_assets:
print(" Matched.")
data = {'base': base_url, 'assets': {a: a for a in matched_assets}}
print('---')
print('{}:'.format(package))
print(' base: {}'.format(base_url))
print(' assets:')
for asset in matched_assets:
print(' {0}: {0}'.format(asset))
print('---')
return True
return False
def resolve_missing(package):
print('Trying to resolve missing package from GitHub repositories...')
for user, branch in GITHUB_USERS:
print(' {}...'.format(user))
if resolve_missing_user(user, branch, package):
return
| from urllib.parse import urljoin
from urllib.request import urlopen
from urllib.error import URLError
import sys
ENORMOUS_INJECTION_HACK = False
GITHUB_USERS = [('Polymer', '0.5.2')]
def resolve_missing_user(user, branch, package):
assets = ["{}.html".format(package),
"{}.css".format(package),
"{}.js".format(package)]
base_url = "https://raw.githubusercontent.com/{user}/{package}/{branch}/".format(**locals())
matched_assets = []
for asset in assets:
asset_url = urljoin(base_url, asset)
try:
with urlopen(asset_url):
pass
matched_assets.append(asset)
except URLError:
pass
if matched_assets:
print(" Matched.")
data = {'base': base_url, 'assets': {a: a for a in matched_assets}}
if ENORMOUS_INJECTION_HACK:
target = open('webshack/standard_packages.yaml', 'a')
else:
target = sys.stdout
print('---')
print('{}:'.format(package), file=target)
print(' base: {}'.format(base_url), file=target)
print(' assets:', file=target)
for asset in matched_assets:
print(' {0}: {0}'.format(asset), file=target)
if not ENORMOUS_INJECTION_HACK:
print('---')
return True
return False
def resolve_missing(package):
print('Trying to resolve missing package from GitHub repositories...')
for user, branch in GITHUB_USERS:
print(' {}...'.format(user))
if resolve_missing_user(user, branch, package):
return
| Add a hack to auto-inject new deps | Add a hack to auto-inject new deps
| Python | mit | prophile/webshack | from urllib.parse import urljoin
from urllib.request import urlopen
from urllib.error import URLError
import sys
+
+ ENORMOUS_INJECTION_HACK = False
GITHUB_USERS = [('Polymer', '0.5.2')]
def resolve_missing_user(user, branch, package):
assets = ["{}.html".format(package),
"{}.css".format(package),
"{}.js".format(package)]
base_url = "https://raw.githubusercontent.com/{user}/{package}/{branch}/".format(**locals())
matched_assets = []
for asset in assets:
asset_url = urljoin(base_url, asset)
try:
with urlopen(asset_url):
pass
matched_assets.append(asset)
except URLError:
pass
if matched_assets:
print(" Matched.")
data = {'base': base_url, 'assets': {a: a for a in matched_assets}}
+ if ENORMOUS_INJECTION_HACK:
+ target = open('webshack/standard_packages.yaml', 'a')
+ else:
+ target = sys.stdout
- print('---')
+ print('---')
- print('{}:'.format(package))
+ print('{}:'.format(package), file=target)
- print(' base: {}'.format(base_url))
+ print(' base: {}'.format(base_url), file=target)
- print(' assets:')
+ print(' assets:', file=target)
for asset in matched_assets:
- print(' {0}: {0}'.format(asset))
+ print(' {0}: {0}'.format(asset), file=target)
+ if not ENORMOUS_INJECTION_HACK:
- print('---')
+ print('---')
return True
return False
def resolve_missing(package):
print('Trying to resolve missing package from GitHub repositories...')
for user, branch in GITHUB_USERS:
print(' {}...'.format(user))
if resolve_missing_user(user, branch, package):
return
| Add a hack to auto-inject new deps | ## Code Before:
from urllib.parse import urljoin
from urllib.request import urlopen
from urllib.error import URLError
import sys
GITHUB_USERS = [('Polymer', '0.5.2')]
def resolve_missing_user(user, branch, package):
assets = ["{}.html".format(package),
"{}.css".format(package),
"{}.js".format(package)]
base_url = "https://raw.githubusercontent.com/{user}/{package}/{branch}/".format(**locals())
matched_assets = []
for asset in assets:
asset_url = urljoin(base_url, asset)
try:
with urlopen(asset_url):
pass
matched_assets.append(asset)
except URLError:
pass
if matched_assets:
print(" Matched.")
data = {'base': base_url, 'assets': {a: a for a in matched_assets}}
print('---')
print('{}:'.format(package))
print(' base: {}'.format(base_url))
print(' assets:')
for asset in matched_assets:
print(' {0}: {0}'.format(asset))
print('---')
return True
return False
def resolve_missing(package):
print('Trying to resolve missing package from GitHub repositories...')
for user, branch in GITHUB_USERS:
print(' {}...'.format(user))
if resolve_missing_user(user, branch, package):
return
## Instruction:
Add a hack to auto-inject new deps
## Code After:
from urllib.parse import urljoin
from urllib.request import urlopen
from urllib.error import URLError
import sys
ENORMOUS_INJECTION_HACK = False
GITHUB_USERS = [('Polymer', '0.5.2')]
def resolve_missing_user(user, branch, package):
assets = ["{}.html".format(package),
"{}.css".format(package),
"{}.js".format(package)]
base_url = "https://raw.githubusercontent.com/{user}/{package}/{branch}/".format(**locals())
matched_assets = []
for asset in assets:
asset_url = urljoin(base_url, asset)
try:
with urlopen(asset_url):
pass
matched_assets.append(asset)
except URLError:
pass
if matched_assets:
print(" Matched.")
data = {'base': base_url, 'assets': {a: a for a in matched_assets}}
if ENORMOUS_INJECTION_HACK:
target = open('webshack/standard_packages.yaml', 'a')
else:
target = sys.stdout
print('---')
print('{}:'.format(package), file=target)
print(' base: {}'.format(base_url), file=target)
print(' assets:', file=target)
for asset in matched_assets:
print(' {0}: {0}'.format(asset), file=target)
if not ENORMOUS_INJECTION_HACK:
print('---')
return True
return False
def resolve_missing(package):
print('Trying to resolve missing package from GitHub repositories...')
for user, branch in GITHUB_USERS:
print(' {}...'.format(user))
if resolve_missing_user(user, branch, package):
return
|
0e53ae11cb1cc53979edb1f17162e8b1d89ad809 | user/models.py | user/models.py | from django.db import models
# Create your models here.
| from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Extends User model. Defines sn and notifications for a User.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
sn = models.CharField(max_length=60)
notifications = models.ForeignKey(Notifications, on_delete=models.CASCADE)
# Defines user's email notification settings.
class Notifications(models.Model):
update = models.BooleanField(default=True)
response = models.BooleanField(default=True)
#
# The following functions define signals so that the Profile model
# will be automatically created/updated whenever the Django User object
# is created/updated. This makes it so you never have to call the Profile
# object's save method, all saving is done with the User model.
#
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
| Define initial schema for user and email notifications | Define initial schema for user and email notifications
| Python | apache-2.0 | ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints | from django.db import models
+ from django.contrib.auth.models import User
+ from django.db.models.signals import post_save
+ from django.dispatch import receiver
- # Create your models here.
+ # Extends User model. Defines sn and notifications for a User.
+ class Profile(models.Model):
+ user = models.OneToOneField(User, on_delete=models.CASCADE)
+ sn = models.CharField(max_length=60)
+ notifications = models.ForeignKey(Notifications, on_delete=models.CASCADE)
+ # Defines user's email notification settings.
+ class Notifications(models.Model):
+ update = models.BooleanField(default=True)
+ response = models.BooleanField(default=True)
+
+ #
+ # The following functions define signals so that the Profile model
+ # will be automatically created/updated whenever the Django User object
+ # is created/updated. This makes it so you never have to call the Profile
+ # object's save method, all saving is done with the User model.
+ #
+ @receiver(post_save, sender=User)
+ def create_user_profile(sender, instance, created, **kwargs):
+ if created:
+ Profile.objects.create(user=instance)
+
+ @receiver(post_save, sender=User)
+ def save_user_profile(sender, instance, **kwargs):
+ instance.profile.save()
+ | Define initial schema for user and email notifications | ## Code Before:
from django.db import models
# Create your models here.
## Instruction:
Define initial schema for user and email notifications
## Code After:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Extends User model. Defines sn and notifications for a User.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
sn = models.CharField(max_length=60)
notifications = models.ForeignKey(Notifications, on_delete=models.CASCADE)
# Defines user's email notification settings.
class Notifications(models.Model):
update = models.BooleanField(default=True)
response = models.BooleanField(default=True)
#
# The following functions define signals so that the Profile model
# will be automatically created/updated whenever the Django User object
# is created/updated. This makes it so you never have to call the Profile
# object's save method, all saving is done with the User model.
#
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
|
172feb5997a826181a0ec381c171a0a2cc854e4c | yolapy/configuration.py | yolapy/configuration.py | config = {}
_default = object()
def configure(**kwargs):
"""Save all keyword arguments as (key=value) configuration."""
config.update(kwargs)
def get_config(key, default=_default):
"""Lookup the value of a configuration key using an optional default."""
value = config.get(key, default)
if value == _default:
raise KeyError('%s is not configured' % key)
return value
| config = {}
_missing = object()
def configure(**kwargs):
"""Save all keyword arguments as (key=value) configuration."""
config.update(kwargs)
def get_config(key, default=_missing):
"""Lookup the value of a configuration key using an optional default."""
value = config.get(key, default)
if value == _missing:
raise KeyError('%s is not configured' % key)
return value
| Improve varname for missing config | Improve varname for missing config
| Python | mit | yola/yolapy | config = {}
- _default = object()
+ _missing = object()
def configure(**kwargs):
"""Save all keyword arguments as (key=value) configuration."""
config.update(kwargs)
- def get_config(key, default=_default):
+ def get_config(key, default=_missing):
"""Lookup the value of a configuration key using an optional default."""
value = config.get(key, default)
- if value == _default:
+ if value == _missing:
raise KeyError('%s is not configured' % key)
return value
| Improve varname for missing config | ## Code Before:
config = {}
_default = object()
def configure(**kwargs):
"""Save all keyword arguments as (key=value) configuration."""
config.update(kwargs)
def get_config(key, default=_default):
"""Lookup the value of a configuration key using an optional default."""
value = config.get(key, default)
if value == _default:
raise KeyError('%s is not configured' % key)
return value
## Instruction:
Improve varname for missing config
## Code After:
config = {}
_missing = object()
def configure(**kwargs):
"""Save all keyword arguments as (key=value) configuration."""
config.update(kwargs)
def get_config(key, default=_missing):
"""Lookup the value of a configuration key using an optional default."""
value = config.get(key, default)
if value == _missing:
raise KeyError('%s is not configured' % key)
return value
|
041e1545c99681c8cf9e43d364877d1ff43342d0 | augur/datasources/augur_db/test_augur_db.py | augur/datasources/augur_db/test_augur_db.py | import os
import pytest
@pytest.fixture(scope="module")
def augur_db():
import augur
augur_app = augur.Application()
return augur_app['augur_db']()
# def test_repoid(augur_db):
# assert ghtorrent.repoid('rails', 'rails') >= 1000
# def test_userid(augur_db):
# assert ghtorrent.userid('howderek') >= 1000
"""
Pandas testing format
assert ghtorrent.<function>('owner', 'repo').isin(['<data that should be in dataframe>']).any
The tests check if a value is anywhere in the dataframe
"""
| import os
import pytest
@pytest.fixture(scope="module")
def augur_db():
import augur
augur_app = augur.Application()
return augur_app['augur_db']()
# def test_repoid(augur_db):
# assert ghtorrent.repoid('rails', 'rails') >= 1000
# def test_userid(augur_db):
# assert ghtorrent.userid('howderek') >= 1000
"""
Pandas testing format
assert ghtorrent.<function>('owner', 'repo').isin(['<data that should be in dataframe>']).any
The tests check if a value is anywhere in the dataframe
"""
def test_issues_first_time_opened(augur_db):
# repo_id
assert augur_db.issues_first_time_opened(
1, repo_id=25001, period='day').isin(["2019-05-23 00:00:00+00:00"]).any
assert augur_db.issues_first_time_opened(
1, repo_id=25001, period='week').isin(["2019-05-20 00:00:00+00:00"]).any
# repo_gorup_id
assert augur_db.issues_first_time_opened(1, period='day').isin([
"2019-05-23 00:00:00+00:00"]).any
| Add Unit test for new contributors of issues | Add Unit test for new contributors of issues
Signed-off-by: Bingwen Ma <27def536c643ce1f88ca2c07ff6169767bd9a90f@gmail.com>
| Python | mit | OSSHealth/ghdata,OSSHealth/ghdata,OSSHealth/ghdata | import os
import pytest
@pytest.fixture(scope="module")
def augur_db():
import augur
augur_app = augur.Application()
return augur_app['augur_db']()
# def test_repoid(augur_db):
# assert ghtorrent.repoid('rails', 'rails') >= 1000
# def test_userid(augur_db):
# assert ghtorrent.userid('howderek') >= 1000
"""
Pandas testing format
assert ghtorrent.<function>('owner', 'repo').isin(['<data that should be in dataframe>']).any
The tests check if a value is anywhere in the dataframe
"""
+
+ def test_issues_first_time_opened(augur_db):
+
+ # repo_id
+ assert augur_db.issues_first_time_opened(
+ 1, repo_id=25001, period='day').isin(["2019-05-23 00:00:00+00:00"]).any
+ assert augur_db.issues_first_time_opened(
+ 1, repo_id=25001, period='week').isin(["2019-05-20 00:00:00+00:00"]).any
+
+ # repo_gorup_id
+ assert augur_db.issues_first_time_opened(1, period='day').isin([
+ "2019-05-23 00:00:00+00:00"]).any
+ | Add Unit test for new contributors of issues | ## Code Before:
import os
import pytest
@pytest.fixture(scope="module")
def augur_db():
import augur
augur_app = augur.Application()
return augur_app['augur_db']()
# def test_repoid(augur_db):
# assert ghtorrent.repoid('rails', 'rails') >= 1000
# def test_userid(augur_db):
# assert ghtorrent.userid('howderek') >= 1000
"""
Pandas testing format
assert ghtorrent.<function>('owner', 'repo').isin(['<data that should be in dataframe>']).any
The tests check if a value is anywhere in the dataframe
"""
## Instruction:
Add Unit test for new contributors of issues
## Code After:
import os
import pytest
@pytest.fixture(scope="module")
def augur_db():
import augur
augur_app = augur.Application()
return augur_app['augur_db']()
# def test_repoid(augur_db):
# assert ghtorrent.repoid('rails', 'rails') >= 1000
# def test_userid(augur_db):
# assert ghtorrent.userid('howderek') >= 1000
"""
Pandas testing format
assert ghtorrent.<function>('owner', 'repo').isin(['<data that should be in dataframe>']).any
The tests check if a value is anywhere in the dataframe
"""
def test_issues_first_time_opened(augur_db):
# repo_id
assert augur_db.issues_first_time_opened(
1, repo_id=25001, period='day').isin(["2019-05-23 00:00:00+00:00"]).any
assert augur_db.issues_first_time_opened(
1, repo_id=25001, period='week').isin(["2019-05-20 00:00:00+00:00"]).any
# repo_gorup_id
assert augur_db.issues_first_time_opened(1, period='day').isin([
"2019-05-23 00:00:00+00:00"]).any
|
cd1c3645d733ab16355fe516bb2e505f87d49ace | backdrop/contrib/evl_upload.py | backdrop/contrib/evl_upload.py | from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"agent_automated_dupes", "calls_answered_by_advisor"
]
def ceg_rows(rows):
for column in itertools.count(3):
date = ceg_date(rows, column)
if not isinstance(date, datetime):
return
if date >= d_tz(2012, 4, 1):
yield [
date, "month", rows[5][column], rows[6][column],
rows[9][column], rows[11][column], rows[12][column],
rows[13][column], rows[15][column], rows[17][column]
]
def ceg_date(rows, column):
try:
return rows[3][column]
except IndexError:
return None
yield ceg_keys(rows)
for row in ceg_rows(rows):
yield row
| from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"agent_automated_dupes", "calls_answered_by_advisor"
]
def ceg_rows(rows):
rows = list(rows)
for column in itertools.count(3):
date = ceg_date(rows, column)
if not isinstance(date, datetime):
return
if date >= d_tz(2012, 4, 1):
yield [
date, "month", rows[5][column], rows[6][column],
rows[9][column], rows[11][column], rows[12][column],
rows[13][column], rows[15][column], rows[17][column]
]
def ceg_date(rows, column):
try:
return rows[3][column]
except IndexError:
return None
yield ceg_keys(rows)
for row in ceg_rows(rows):
yield row
| Convert rows to list in EVL CEG parser | Convert rows to list in EVL CEG parser
It needs to access cells directly
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"agent_automated_dupes", "calls_answered_by_advisor"
]
def ceg_rows(rows):
+ rows = list(rows)
for column in itertools.count(3):
date = ceg_date(rows, column)
if not isinstance(date, datetime):
return
if date >= d_tz(2012, 4, 1):
yield [
date, "month", rows[5][column], rows[6][column],
rows[9][column], rows[11][column], rows[12][column],
rows[13][column], rows[15][column], rows[17][column]
]
def ceg_date(rows, column):
try:
return rows[3][column]
except IndexError:
return None
yield ceg_keys(rows)
for row in ceg_rows(rows):
yield row
| Convert rows to list in EVL CEG parser | ## Code Before:
from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"agent_automated_dupes", "calls_answered_by_advisor"
]
def ceg_rows(rows):
for column in itertools.count(3):
date = ceg_date(rows, column)
if not isinstance(date, datetime):
return
if date >= d_tz(2012, 4, 1):
yield [
date, "month", rows[5][column], rows[6][column],
rows[9][column], rows[11][column], rows[12][column],
rows[13][column], rows[15][column], rows[17][column]
]
def ceg_date(rows, column):
try:
return rows[3][column]
except IndexError:
return None
yield ceg_keys(rows)
for row in ceg_rows(rows):
yield row
## Instruction:
Convert rows to list in EVL CEG parser
## Code After:
from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"agent_automated_dupes", "calls_answered_by_advisor"
]
def ceg_rows(rows):
rows = list(rows)
for column in itertools.count(3):
date = ceg_date(rows, column)
if not isinstance(date, datetime):
return
if date >= d_tz(2012, 4, 1):
yield [
date, "month", rows[5][column], rows[6][column],
rows[9][column], rows[11][column], rows[12][column],
rows[13][column], rows[15][column], rows[17][column]
]
def ceg_date(rows, column):
try:
return rows[3][column]
except IndexError:
return None
yield ceg_keys(rows)
for row in ceg_rows(rows):
yield row
|
7a04bb7692b4838e0abe9ba586fc4748ed9cd5d4 | tests/integration/blueprints/site/test_homepage.py | tests/integration/blueprints/site/test_homepage.py |
import pytest
from tests.helpers import http_client
def test_homepage(site_app, site):
with http_client(site_app) as client:
response = client.get('/')
# By default, nothing is mounted on `/`, but at least check that
# the application boots up and doesn't return a server error.
assert response.status_code == 404
|
import pytest
from tests.helpers import http_client
def test_homepage(site_app, site):
with http_client(site_app) as client:
response = client.get('/')
# By default, nothing is mounted on `/`, but at least check that
# the application boots up and doesn't return a server error.
assert response.status_code == 404
assert response.location is None
def test_homepage_with_root_redirect(make_site_app, site):
site_app = make_site_app(ROOT_REDIRECT_TARGET='welcome')
with http_client(site_app) as client:
response = client.get('/')
assert response.status_code == 307
assert response.location == 'http://www.acmecon.test/welcome'
| Test custom root path redirect | Test custom root path redirect
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
import pytest
from tests.helpers import http_client
def test_homepage(site_app, site):
with http_client(site_app) as client:
response = client.get('/')
# By default, nothing is mounted on `/`, but at least check that
# the application boots up and doesn't return a server error.
assert response.status_code == 404
+ assert response.location is None
+
+ def test_homepage_with_root_redirect(make_site_app, site):
+ site_app = make_site_app(ROOT_REDIRECT_TARGET='welcome')
+
+ with http_client(site_app) as client:
+ response = client.get('/')
+
+ assert response.status_code == 307
+ assert response.location == 'http://www.acmecon.test/welcome'
+ | Test custom root path redirect | ## Code Before:
import pytest
from tests.helpers import http_client
def test_homepage(site_app, site):
with http_client(site_app) as client:
response = client.get('/')
# By default, nothing is mounted on `/`, but at least check that
# the application boots up and doesn't return a server error.
assert response.status_code == 404
## Instruction:
Test custom root path redirect
## Code After:
import pytest
from tests.helpers import http_client
def test_homepage(site_app, site):
with http_client(site_app) as client:
response = client.get('/')
# By default, nothing is mounted on `/`, but at least check that
# the application boots up and doesn't return a server error.
assert response.status_code == 404
assert response.location is None
def test_homepage_with_root_redirect(make_site_app, site):
site_app = make_site_app(ROOT_REDIRECT_TARGET='welcome')
with http_client(site_app) as client:
response = client.get('/')
assert response.status_code == 307
assert response.location == 'http://www.acmecon.test/welcome'
|
cdfb5c0c074e9143eeb84d914225dbcfb63151ba | common/djangoapps/dark_lang/models.py | common/djangoapps/dark_lang/models.py | from django.db import models
from config_models.models import ConfigurationModel
class DarkLangConfig(ConfigurationModel):
"""
Configuration for the dark_lang django app
"""
released_languages = models.TextField(
blank=True,
help_text="A comma-separated list of language codes to release to the public."
)
@property
def released_languages_list(self):
"""
``released_languages`` as a list of language codes.
Example: ['it', 'de-at', 'es', 'pt-br']
"""
if not self.released_languages.strip(): # pylint: disable=no-member
return []
return [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member
| from django.db import models
from config_models.models import ConfigurationModel
class DarkLangConfig(ConfigurationModel):
"""
Configuration for the dark_lang django app
"""
released_languages = models.TextField(
blank=True,
help_text="A comma-separated list of language codes to release to the public."
)
@property
def released_languages_list(self):
"""
``released_languages`` as a list of language codes.
Example: ['it', 'de-at', 'es', 'pt-br']
"""
if not self.released_languages.strip(): # pylint: disable=no-member
return []
languages = [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member
# Put in alphabetical order
languages.sort()
return languages
| Put language modal in alphabetical order LMS-2302 | Put language modal in alphabetical order LMS-2302
| Python | agpl-3.0 | Softmotions/edx-platform,rismalrv/edx-platform,ovnicraft/edx-platform,jbzdak/edx-platform,nttks/jenkins-test,philanthropy-u/edx-platform,dkarakats/edx-platform,AkA84/edx-platform,kursitet/edx-platform,eestay/edx-platform,atsolakid/edx-platform,kxliugang/edx-platform,zadgroup/edx-platform,B-MOOC/edx-platform,romain-li/edx-platform,martynovp/edx-platform,deepsrijit1105/edx-platform,rhndg/openedx,doganov/edx-platform,cognitiveclass/edx-platform,ahmadiga/min_edx,chand3040/cloud_that,LICEF/edx-platform,utecuy/edx-platform,Unow/edx-platform,jelugbo/tundex,zerobatu/edx-platform,IndonesiaX/edx-platform,dcosentino/edx-platform,ampax/edx-platform-backup,cselis86/edx-platform,DNFcode/edx-platform,stvstnfrd/edx-platform,cpennington/edx-platform,fly19890211/edx-platform,sameetb-cuelogic/edx-platform-test,ESOedX/edx-platform,xingyepei/edx-platform,zhenzhai/edx-platform,Kalyzee/edx-platform,cselis86/edx-platform,tiagochiavericosta/edx-platform,prarthitm/edxplatform,devs1991/test_edx_docmode,eemirtekin/edx-platform,motion2015/a3,DNFcode/edx-platform,kmoocdev/edx-platform,shubhdev/edx-platform,kmoocdev/edx-platform,amir-qayyum-khan/edx-platform,eduNEXT/edx-platform,kursitet/edx-platform,Ayub-Khan/edx-platform,fintech-circle/edx-platform,shubhdev/edxOnBaadal,auferack08/edx-platform,OmarIthawi/edx-platform,UXE/local-edx,jamiefolsom/edx-platform,dcosentino/edx-platform,openfun/edx-platform,Lektorium-LLC/edx-platform,kxliugang/edx-platform,hkawasaki/kawasaki-aio8-0,arbrandes/edx-platform,ampax/edx-platform,hkawasaki/kawasaki-aio8-0,jazkarta/edx-platform,eemirtekin/edx-platform,ahmedaljazzar/edx-platform,jruiperezv/ANALYSE,CredoReference/edx-platform,bdero/edx-platform,wwj718/ANALYSE,Stanford-Online/edx-platform,MSOpenTech/edx-platform,JCBarahona/edX,alu042/edx-platform,Shrhawk/edx-platform,kmoocdev2/edx-platform,jelugbo/tundex,Endika/edx-platform,don-github/edx-platform,Kalyzee/edx-platform,angelapper/edx-platform,marcore/edx-platform,waheedahmed/edx-platform,UXE/local-edx,jazztpt/edx-platform,zhenzhai/edx-platform,IndonesiaX/edx-platform,chauhanhardik/populo_2,antonve/s4-project-mooc,procangroup/edx-platform,antonve/s4-project-mooc,mcgachey/edx-platform,zerobatu/edx-platform,shubhdev/openedx,appsembler/edx-platform,SivilTaram/edx-platform,DefyVentures/edx-platform,ferabra/edx-platform,kmoocdev2/edx-platform,edx-solutions/edx-platform,devs1991/test_edx_docmode,Semi-global/edx-platform,AkA84/edx-platform,Softmotions/edx-platform,Endika/edx-platform,inares/edx-platform,yokose-ks/edx-platform,shurihell/testasia,halvertoluke/edx-platform,waheedahmed/edx-platform,xuxiao19910803/edx,olexiim/edx-platform,eestay/edx-platform,ubc/edx-platform,edry/edx-platform,knehez/edx-platform,deepsrijit1105/edx-platform,Shrhawk/edx-platform,4eek/edx-platform,carsongee/edx-platform,tanmaykm/edx-platform,carsongee/edx-platform,nttks/edx-platform,Endika/edx-platform,don-github/edx-platform,chauhanhardik/populo,waheedahmed/edx-platform,zadgroup/edx-platform,eduNEXT/edunext-platform,adoosii/edx-platform,jazkarta/edx-platform-for-isc,nikolas/edx-platform,nanolearningllc/edx-platform-cypress,caesar2164/edx-platform,amir-qayyum-khan/edx-platform,jelugbo/tundex,ampax/edx-platform-backup,longmen21/edx-platform,beni55/edx-platform,vasyarv/edx-platform,ovnicraft/edx-platform,jonathan-beard/edx-platform,solashirai/edx-platform,bdero/edx-platform,motion2015/edx-platform,appsembler/edx-platform,appliedx/edx-platform,chand3040/cloud_that,torchingloom/edx-platform,nanolearningllc/edx-platform-cypress-2,bigdatauniversity/edx-platform,B-MOOC/edx-platform,procangroup/edx-platform,Shrhawk/edx-platform,dcosentino/edx-platform,atsolakid/edx-platform,y12uc231/edx-platform,rue89-tech/edx-platform,devs1991/test_edx_docmode,gsehub/edx-platform,fintech-circle/edx-platform,gsehub/edx-platform,TeachAtTUM/edx-platform,CourseTalk/edx-platform,Edraak/circleci-edx-platform,EDUlib/edx-platform,eestay/edx-platform,Lektorium-LLC/edx-platform,shubhdev/openedx,jbzdak/edx-platform,benpatterson/edx-platform,jswope00/griffinx,jazkarta/edx-platform-for-isc,vismartltd/edx-platform,hkawasaki/kawasaki-aio8-2,simbs/edx-platform,xuxiao19910803/edx-platform,antonve/s4-project-mooc,arbrandes/edx-platform,IONISx/edx-platform,ampax/edx-platform-backup,OmarIthawi/edx-platform,knehez/edx-platform,itsjeyd/edx-platform,ahmadio/edx-platform,longmen21/edx-platform,Semi-global/edx-platform,nttks/edx-platform,wwj718/edx-platform,solashirai/edx-platform,miptliot/edx-platform,zhenzhai/edx-platform,ahmadiga/min_edx,bitifirefly/edx-platform,DefyVentures/edx-platform,teltek/edx-platform,auferack08/edx-platform,sudheerchintala/LearnEraPlatForm,doismellburning/edx-platform,zerobatu/edx-platform,solashirai/edx-platform,chauhanhardik/populo_2,mbareta/edx-platform-ft,jjmiranda/edx-platform,jonathan-beard/edx-platform,pepeportela/edx-platform,shurihell/testasia,etzhou/edx-platform,rue89-tech/edx-platform,vasyarv/edx-platform,prarthitm/edxplatform,jswope00/GAI,simbs/edx-platform,eduNEXT/edunext-platform,olexiim/edx-platform,motion2015/a3,arbrandes/edx-platform,louyihua/edx-platform,mitocw/edx-platform,ahmadiga/min_edx,hkawasaki/kawasaki-aio8-1,cecep-edu/edx-platform,chand3040/cloud_that,xinjiguaike/edx-platform,msegado/edx-platform,beni55/edx-platform,beni55/edx-platform,vikas1885/test1,utecuy/edx-platform,SivilTaram/edx-platform,nanolearning/edx-platform,procangroup/edx-platform,RPI-OPENEDX/edx-platform,SivilTaram/edx-platform,playm2mboy/edx-platform,jswope00/griffinx,pabloborrego93/edx-platform,jazkarta/edx-platform,JioEducation/edx-platform,hastexo/edx-platform,jzoldak/edx-platform,dkarakats/edx-platform,analyseuc3m/ANALYSE-v1,B-MOOC/edx-platform,Edraak/edraak-platform,longmen21/edx-platform,motion2015/edx-platform,angelapper/edx-platform,vikas1885/test1,DefyVentures/edx-platform,gsehub/edx-platform,jolyonb/edx-platform,knehez/edx-platform,ovnicraft/edx-platform,LICEF/edx-platform,ferabra/edx-platform,JCBarahona/edX,bdero/edx-platform,ubc/edx-platform,edx-solutions/edx-platform,nikolas/edx-platform,MSOpenTech/edx-platform,AkA84/edx-platform,ESOedX/edx-platform,adoosii/edx-platform,halvertoluke/edx-platform,mahendra-r/edx-platform,arifsetiawan/edx-platform,shabab12/edx-platform,Semi-global/edx-platform,lduarte1991/edx-platform,CredoReference/edx-platform,eemirtekin/edx-platform,MSOpenTech/edx-platform,iivic/BoiseStateX,knehez/edx-platform,jzoldak/edx-platform,openfun/edx-platform,Ayub-Khan/edx-platform,MakeHer/edx-platform,ak2703/edx-platform,nttks/edx-platform,doganov/edx-platform,simbs/edx-platform,defance/edx-platform,Edraak/circleci-edx-platform,jamiefolsom/edx-platform,10clouds/edx-platform,shubhdev/edx-platform,atsolakid/edx-platform,ZLLab-Mooc/edx-platform,romain-li/edx-platform,mcgachey/edx-platform,antoviaque/edx-platform,stvstnfrd/edx-platform,edx/edx-platform,chauhanhardik/populo_2,hkawasaki/kawasaki-aio8-2,wwj718/ANALYSE,MakeHer/edx-platform,synergeticsedx/deployment-wipro,kmoocdev/edx-platform,valtech-mooc/edx-platform,lduarte1991/edx-platform,hkawasaki/kawasaki-aio8-0,romain-li/edx-platform,devs1991/test_edx_docmode,nagyistoce/edx-platform,shashank971/edx-platform,mushtaqak/edx-platform,cselis86/edx-platform,vasyarv/edx-platform,zubair-arbi/edx-platform,mjirayu/sit_academy,mtlchun/edx,vikas1885/test1,ovnicraft/edx-platform,angelapper/edx-platform,antoviaque/edx-platform,cpennington/edx-platform,prarthitm/edxplatform,deepsrijit1105/edx-platform,y12uc231/edx-platform,nagyistoce/edx-platform,zofuthan/edx-platform,unicri/edx-platform,nanolearningllc/edx-platform-cypress,cecep-edu/edx-platform,gsehub/edx-platform,carsongee/edx-platform,xingyepei/edx-platform,msegado/edx-platform,hamzehd/edx-platform,doganov/edx-platform,sudheerchintala/LearnEraPlatForm,wwj718/edx-platform,jazkarta/edx-platform-for-isc,don-github/edx-platform,leansoft/edx-platform,ampax/edx-platform-backup,zerobatu/edx-platform,shabab12/edx-platform,IndonesiaX/edx-platform,SivilTaram/edx-platform,franosincic/edx-platform,olexiim/edx-platform,shubhdev/edxOnBaadal,nttks/edx-platform,mcgachey/edx-platform,peterm-itr/edx-platform,zhenzhai/edx-platform,kmoocdev2/edx-platform,mcgachey/edx-platform,kamalx/edx-platform,amir-qayyum-khan/edx-platform,eemirtekin/edx-platform,arifsetiawan/edx-platform,mitocw/edx-platform,chudaol/edx-platform,alexthered/kienhoc-platform,adoosii/edx-platform,J861449197/edx-platform,a-parhom/edx-platform,jswope00/GAI,benpatterson/edx-platform,ubc/edx-platform,rue89-tech/edx-platform,y12uc231/edx-platform,torchingloom/edx-platform,TeachAtTUM/edx-platform,sudheerchintala/LearnEraPlatForm,nanolearningllc/edx-platform-cypress-2,nikolas/edx-platform,mjirayu/sit_academy,jjmiranda/edx-platform,wwj718/edx-platform,beni55/edx-platform,abdoosh00/edraak,analyseuc3m/ANALYSE-v1,teltek/edx-platform,UXE/local-edx,playm2mboy/edx-platform,jazztpt/edx-platform,zubair-arbi/edx-platform,LearnEra/LearnEraPlaftform,hmcmooc/muddx-platform,fly19890211/edx-platform,mahendra-r/edx-platform,OmarIthawi/edx-platform,naresh21/synergetics-edx-platform,rismalrv/edx-platform,mitocw/edx-platform,chauhanhardik/populo_2,synergeticsedx/deployment-wipro,Edraak/edraak-platform,openfun/edx-platform,rismalrv/edx-platform,lduarte1991/edx-platform,arifsetiawan/edx-platform,zubair-arbi/edx-platform,miptliot/edx-platform,Softmotions/edx-platform,arifsetiawan/edx-platform,cyanna/edx-platform,fly19890211/edx-platform,jazkarta/edx-platform-for-isc,torchingloom/edx-platform,yokose-ks/edx-platform,fintech-circle/edx-platform,ahmadio/edx-platform,OmarIthawi/edx-platform,nanolearningllc/edx-platform-cypress-2,CourseTalk/edx-platform,bitifirefly/edx-platform,bitifirefly/edx-platform,mushtaqak/edx-platform,hamzehd/edx-platform,Edraak/circleci-edx-platform,edry/edx-platform,eestay/edx-platform,Semi-global/edx-platform,pabloborrego93/edx-platform,IONISx/edx-platform,alu042/edx-platform,jjmiranda/edx-platform,vikas1885/test1,fly19890211/edx-platform,shashank971/edx-platform,jbzdak/edx-platform,shabab12/edx-platform,martynovp/edx-platform,mahendra-r/edx-platform,a-parhom/edx-platform,unicri/edx-platform,jamesblunt/edx-platform,ESOedX/edx-platform,stvstnfrd/edx-platform,tanmaykm/edx-platform,bitifirefly/edx-platform,4eek/edx-platform,ahmadiga/min_edx,hkawasaki/kawasaki-aio8-1,marcore/edx-platform,DNFcode/edx-platform,xuxiao19910803/edx-platform,jzoldak/edx-platform,kmoocdev2/edx-platform,jruiperezv/ANALYSE,Lektorium-LLC/edx-platform,IONISx/edx-platform,Livit/Livit.Learn.EdX,jamiefolsom/edx-platform,Edraak/edx-platform,zubair-arbi/edx-platform,knehez/edx-platform,nttks/jenkins-test,DNFcode/edx-platform,jbassen/edx-platform,jazztpt/edx-platform,don-github/edx-platform,alexthered/kienhoc-platform,jolyonb/edx-platform,jamesblunt/edx-platform,stvstnfrd/edx-platform,chrisndodge/edx-platform,xinjiguaike/edx-platform,10clouds/edx-platform,teltek/edx-platform,nanolearningllc/edx-platform-cypress,etzhou/edx-platform,Edraak/circleci-edx-platform,Endika/edx-platform,kmoocdev2/edx-platform,bdero/edx-platform,MSOpenTech/edx-platform,mtlchun/edx,torchingloom/edx-platform,jbzdak/edx-platform,jamesblunt/edx-platform,yokose-ks/edx-platform,polimediaupv/edx-platform,mjirayu/sit_academy,kamalx/edx-platform,eestay/edx-platform,DNFcode/edx-platform,mjirayu/sit_academy,pabloborrego93/edx-platform,romain-li/edx-platform,dcosentino/edx-platform,edx/edx-platform,vasyarv/edx-platform,cognitiveclass/edx-platform,alu042/edx-platform,zadgroup/edx-platform,playm2mboy/edx-platform,unicri/edx-platform,cyanna/edx-platform,raccoongang/edx-platform,tiagochiavericosta/edx-platform,Edraak/edraak-platform,xuxiao19910803/edx-platform,mbareta/edx-platform-ft,adoosii/edx-platform,beacloudgenius/edx-platform,xuxiao19910803/edx-platform,nagyistoce/edx-platform,SravanthiSinha/edx-platform,kursitet/edx-platform,rhndg/openedx,mushtaqak/edx-platform,xuxiao19910803/edx-platform,dkarakats/edx-platform,nagyistoce/edx-platform,sudheerchintala/LearnEraPlatForm,sameetb-cuelogic/edx-platform-test,philanthropy-u/edx-platform,olexiim/edx-platform,morenopc/edx-platform,SravanthiSinha/edx-platform,ZLLab-Mooc/edx-platform,LearnEra/LearnEraPlaftform,mtlchun/edx,WatanabeYasumasa/edx-platform,jelugbo/tundex,mjirayu/sit_academy,abdoosh00/edraak,xinjiguaike/edx-platform,analyseuc3m/ANALYSE-v1,jswope00/GAI,utecuy/edx-platform,doismellburning/edx-platform,Unow/edx-platform,tiagochiavericosta/edx-platform,beacloudgenius/edx-platform,edry/edx-platform,nagyistoce/edx-platform,proversity-org/edx-platform,JioEducation/edx-platform,raccoongang/edx-platform,martynovp/edx-platform,polimediaupv/edx-platform,synergeticsedx/deployment-wipro,peterm-itr/edx-platform,doismellburning/edx-platform,RPI-OPENEDX/edx-platform,IONISx/edx-platform,Ayub-Khan/edx-platform,vismartltd/edx-platform,hkawasaki/kawasaki-aio8-1,4eek/edx-platform,ak2703/edx-platform,proversity-org/edx-platform,kamalx/edx-platform,antoviaque/edx-platform,motion2015/a3,mushtaqak/edx-platform,gymnasium/edx-platform,don-github/edx-platform,ESOedX/edx-platform,louyihua/edx-platform,openfun/edx-platform,mahendra-r/edx-platform,jazztpt/edx-platform,JCBarahona/edX,LICEF/edx-platform,leansoft/edx-platform,waheedahmed/edx-platform,ferabra/edx-platform,shubhdev/edx-platform,xinjiguaike/edx-platform,Softmotions/edx-platform,hastexo/edx-platform,wwj718/ANALYSE,etzhou/edx-platform,polimediaupv/edx-platform,Kalyzee/edx-platform,ZLLab-Mooc/edx-platform,sameetb-cuelogic/edx-platform-test,nanolearning/edx-platform,ferabra/edx-platform,nanolearningllc/edx-platform-cypress-2,halvertoluke/edx-platform,JCBarahona/edX,jbassen/edx-platform,BehavioralInsightsTeam/edx-platform,RPI-OPENEDX/edx-platform,inares/edx-platform,ahmadio/edx-platform,edx-solutions/edx-platform,IndonesiaX/edx-platform,hmcmooc/muddx-platform,dsajkl/123,hmcmooc/muddx-platform,raccoongang/edx-platform,naresh21/synergetics-edx-platform,utecuy/edx-platform,miptliot/edx-platform,eemirtekin/edx-platform,rue89-tech/edx-platform,Edraak/edx-platform,eduNEXT/edx-platform,chauhanhardik/populo_2,tanmaykm/edx-platform,olexiim/edx-platform,UOMx/edx-platform,xuxiao19910803/edx,jjmiranda/edx-platform,vasyarv/edx-platform,appliedx/edx-platform,Kalyzee/edx-platform,hkawasaki/kawasaki-aio8-2,nikolas/edx-platform,chudaol/edx-platform,vismartltd/edx-platform,jruiperezv/ANALYSE,synergeticsedx/deployment-wipro,TeachAtTUM/edx-platform,prarthitm/edxplatform,pomegranited/edx-platform,Stanford-Online/edx-platform,zadgroup/edx-platform,Semi-global/edx-platform,kxliugang/edx-platform,proversity-org/edx-platform,chauhanhardik/populo,wwj718/ANALYSE,marcore/edx-platform,Softmotions/edx-platform,rue89-tech/edx-platform,cyanna/edx-platform,ak2703/edx-platform,xinjiguaike/edx-platform,shashank971/edx-platform,jazkarta/edx-platform,andyzsf/edx,andyzsf/edx,appliedx/edx-platform,zofuthan/edx-platform,chauhanhardik/populo,kamalx/edx-platform,nanolearningllc/edx-platform-cypress,iivic/BoiseStateX,dsajkl/reqiop,rhndg/openedx,zofuthan/edx-platform,pepeportela/edx-platform,Unow/edx-platform,nanolearningllc/edx-platform-cypress-2,ZLLab-Mooc/edx-platform,vismartltd/edx-platform,doismellburning/edx-platform,edry/edx-platform,jazztpt/edx-platform,doganov/edx-platform,hamzehd/edx-platform,tiagochiavericosta/edx-platform,valtech-mooc/edx-platform,shubhdev/edxOnBaadal,jruiperezv/ANALYSE,simbs/edx-platform,motion2015/edx-platform,jonathan-beard/edx-platform,etzhou/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,Livit/Livit.Learn.EdX,caesar2164/edx-platform,SivilTaram/edx-platform,BehavioralInsightsTeam/edx-platform,cpennington/edx-platform,longmen21/edx-platform,Unow/edx-platform,bigdatauniversity/edx-platform,Stanford-Online/edx-platform,zofuthan/edx-platform,eduNEXT/edx-platform,franosincic/edx-platform,WatanabeYasumasa/edx-platform,ampax/edx-platform-backup,tanmaykm/edx-platform,mbareta/edx-platform-ft,kmoocdev/edx-platform,valtech-mooc/edx-platform,10clouds/edx-platform,louyihua/edx-platform,louyihua/edx-platform,chand3040/cloud_that,mahendra-r/edx-platform,Kalyzee/edx-platform,10clouds/edx-platform,Livit/Livit.Learn.EdX,dsajkl/reqiop,auferack08/edx-platform,waheedahmed/edx-platform,SravanthiSinha/edx-platform,andyzsf/edx,shubhdev/openedx,leansoft/edx-platform,iivic/BoiseStateX,peterm-itr/edx-platform,jolyonb/edx-platform,defance/edx-platform,chrisndodge/edx-platform,xingyepei/edx-platform,chudaol/edx-platform,vismartltd/edx-platform,gymnasium/edx-platform,deepsrijit1105/edx-platform,jswope00/griffinx,msegado/edx-platform,nttks/jenkins-test,IONISx/edx-platform,procangroup/edx-platform,msegado/edx-platform,J861449197/edx-platform,chudaol/edx-platform,polimediaupv/edx-platform,pabloborrego93/edx-platform,shubhdev/edxOnBaadal,shashank971/edx-platform,gymnasium/edx-platform,shubhdev/edx-platform,morenopc/edx-platform,ZLLab-Mooc/edx-platform,LICEF/edx-platform,morenopc/edx-platform,ahmadio/edx-platform,zhenzhai/edx-platform,valtech-mooc/edx-platform,auferack08/edx-platform,cognitiveclass/edx-platform,AkA84/edx-platform,shubhdev/edxOnBaadal,shubhdev/edx-platform,Edraak/edx-platform,pomegranited/edx-platform,alexthered/kienhoc-platform,JioEducation/edx-platform,TeachAtTUM/edx-platform,Edraak/edraak-platform,RPI-OPENEDX/edx-platform,LearnEra/LearnEraPlaftform,nttks/jenkins-test,bitifirefly/edx-platform,wwj718/ANALYSE,raccoongang/edx-platform,halvertoluke/edx-platform,CredoReference/edx-platform,cecep-edu/edx-platform,wwj718/edx-platform,devs1991/test_edx_docmode,antonve/s4-project-mooc,motion2015/edx-platform,ovnicraft/edx-platform,yokose-ks/edx-platform,jonathan-beard/edx-platform,doismellburning/edx-platform,Livit/Livit.Learn.EdX,unicri/edx-platform,naresh21/synergetics-edx-platform,nttks/jenkins-test,4eek/edx-platform,dsajkl/123,chauhanhardik/populo,appsembler/edx-platform,cognitiveclass/edx-platform,ferabra/edx-platform,edx/edx-platform,pomegranited/edx-platform,jamiefolsom/edx-platform,mtlchun/edx,dsajkl/123,cselis86/edx-platform,shabab12/edx-platform,RPI-OPENEDX/edx-platform,jelugbo/tundex,lduarte1991/edx-platform,edx-solutions/edx-platform,itsjeyd/edx-platform,UOMx/edx-platform,mushtaqak/edx-platform,franosincic/edx-platform,proversity-org/edx-platform,longmen21/edx-platform,philanthropy-u/edx-platform,playm2mboy/edx-platform,utecuy/edx-platform,MakeHer/edx-platform,openfun/edx-platform,BehavioralInsightsTeam/edx-platform,nanolearning/edx-platform,JioEducation/edx-platform,Shrhawk/edx-platform,a-parhom/edx-platform,amir-qayyum-khan/edx-platform,halvertoluke/edx-platform,morenopc/edx-platform,zofuthan/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,AkA84/edx-platform,jazkarta/edx-platform-for-isc,alexthered/kienhoc-platform,CredoReference/edx-platform,simbs/edx-platform,zerobatu/edx-platform,4eek/edx-platform,kxliugang/edx-platform,jbassen/edx-platform,analyseuc3m/ANALYSE-v1,cyanna/edx-platform,hastexo/edx-platform,Edraak/edx-platform,philanthropy-u/edx-platform,iivic/BoiseStateX,EDUlib/edx-platform,DefyVentures/edx-platform,ahmadiga/min_edx,devs1991/test_edx_docmode,y12uc231/edx-platform,jbassen/edx-platform,kxliugang/edx-platform,hkawasaki/kawasaki-aio8-2,appliedx/edx-platform,kmoocdev/edx-platform,ubc/edx-platform,inares/edx-platform,Lektorium-LLC/edx-platform,tiagochiavericosta/edx-platform,zubair-arbi/edx-platform,Stanford-Online/edx-platform,xuxiao19910803/edx,jbzdak/edx-platform,unicri/edx-platform,franosincic/edx-platform,cyanna/edx-platform,shubhdev/openedx,benpatterson/edx-platform,solashirai/edx-platform,cecep-edu/edx-platform,peterm-itr/edx-platform,ahmedaljazzar/edx-platform,vikas1885/test1,JCBarahona/edX,nikolas/edx-platform,ak2703/edx-platform,DefyVentures/edx-platform,yokose-ks/edx-platform,CourseTalk/edx-platform,eduNEXT/edx-platform,pepeportela/edx-platform,Edraak/edx-platform,xingyepei/edx-platform,BehavioralInsightsTeam/edx-platform,UOMx/edx-platform,bigdatauniversity/edx-platform,MakeHer/edx-platform,inares/edx-platform,jazkarta/edx-platform,hastexo/edx-platform,mtlchun/edx,beacloudgenius/edx-platform,zadgroup/edx-platform,itsjeyd/edx-platform,IndonesiaX/edx-platform,jamiefolsom/edx-platform,teltek/edx-platform,ampax/edx-platform,benpatterson/edx-platform,LICEF/edx-platform,leansoft/edx-platform,rhndg/openedx,xuxiao19910803/edx,EDUlib/edx-platform,iivic/BoiseStateX,chudaol/edx-platform,bigdatauniversity/edx-platform,benpatterson/edx-platform,J861449197/edx-platform,LearnEra/LearnEraPlaftform,sameetb-cuelogic/edx-platform-test,devs1991/test_edx_docmode,abdoosh00/edraak,SravanthiSinha/edx-platform,kamalx/edx-platform,shurihell/testasia,cselis86/edx-platform,martynovp/edx-platform,marcore/edx-platform,xingyepei/edx-platform,hamzehd/edx-platform,antoviaque/edx-platform,morenopc/edx-platform,mitocw/edx-platform,pepeportela/edx-platform,carsongee/edx-platform,cecep-edu/edx-platform,dsajkl/reqiop,hamzehd/edx-platform,ahmadio/edx-platform,beni55/edx-platform,naresh21/synergetics-edx-platform,Shrhawk/edx-platform,y12uc231/edx-platform,jswope00/griffinx,atsolakid/edx-platform,rismalrv/edx-platform,J861449197/edx-platform,SravanthiSinha/edx-platform,angelapper/edx-platform,CourseTalk/edx-platform,bigdatauniversity/edx-platform,B-MOOC/edx-platform,cognitiveclass/edx-platform,edry/edx-platform,dcosentino/edx-platform,nanolearning/edx-platform,kursitet/edx-platform,etzhou/edx-platform,martynovp/edx-platform,alu042/edx-platform,WatanabeYasumasa/edx-platform,torchingloom/edx-platform,arifsetiawan/edx-platform,adoosii/edx-platform,dkarakats/edx-platform,shurihell/testasia,J861449197/edx-platform,miptliot/edx-platform,chrisndodge/edx-platform,Ayub-Khan/edx-platform,franosincic/edx-platform,EDUlib/edx-platform,defance/edx-platform,solashirai/edx-platform,edx/edx-platform,motion2015/a3,hkawasaki/kawasaki-aio8-1,dsajkl/123,jbassen/edx-platform,atsolakid/edx-platform,defance/edx-platform,jolyonb/edx-platform,mcgachey/edx-platform,itsjeyd/edx-platform,polimediaupv/edx-platform,msegado/edx-platform,appsembler/edx-platform,jruiperezv/ANALYSE,rismalrv/edx-platform,motion2015/a3,beacloudgenius/edx-platform,romain-li/edx-platform,sameetb-cuelogic/edx-platform-test,abdoosh00/edraak,doganov/edx-platform,a-parhom/edx-platform,ahmedaljazzar/edx-platform,jamesblunt/edx-platform,jswope00/griffinx,Edraak/circleci-edx-platform,MSOpenTech/edx-platform,hkawasaki/kawasaki-aio8-0,UXE/local-edx,jamesblunt/edx-platform,shurihell/testasia,leansoft/edx-platform,inares/edx-platform,motion2015/edx-platform,MakeHer/edx-platform,pomegranited/edx-platform,ampax/edx-platform,dsajkl/123,chrisndodge/edx-platform,chand3040/cloud_that,wwj718/edx-platform,fly19890211/edx-platform,rhndg/openedx,beacloudgenius/edx-platform,andyzsf/edx,shubhdev/openedx,dsajkl/reqiop,UOMx/edx-platform,B-MOOC/edx-platform,eduNEXT/edunext-platform,nttks/edx-platform,valtech-mooc/edx-platform,playm2mboy/edx-platform,fintech-circle/edx-platform,devs1991/test_edx_docmode,chauhanhardik/populo,Ayub-Khan/edx-platform,xuxiao19910803/edx,jzoldak/edx-platform,ahmedaljazzar/edx-platform,WatanabeYasumasa/edx-platform,jazkarta/edx-platform,shashank971/edx-platform,hmcmooc/muddx-platform,kursitet/edx-platform,cpennington/edx-platform,mbareta/edx-platform-ft,jswope00/GAI,ak2703/edx-platform,ubc/edx-platform,ampax/edx-platform,nanolearningllc/edx-platform-cypress,pomegranited/edx-platform,jonathan-beard/edx-platform,gymnasium/edx-platform,dkarakats/edx-platform,appliedx/edx-platform,antonve/s4-project-mooc,alexthered/kienhoc-platform,nanolearning/edx-platform | from django.db import models
from config_models.models import ConfigurationModel
class DarkLangConfig(ConfigurationModel):
"""
Configuration for the dark_lang django app
"""
released_languages = models.TextField(
blank=True,
help_text="A comma-separated list of language codes to release to the public."
)
@property
def released_languages_list(self):
"""
``released_languages`` as a list of language codes.
Example: ['it', 'de-at', 'es', 'pt-br']
"""
if not self.released_languages.strip(): # pylint: disable=no-member
return []
- return [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member
+ languages = [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member
+ # Put in alphabetical order
+ languages.sort()
+ return languages
| Put language modal in alphabetical order LMS-2302 | ## Code Before:
from django.db import models
from config_models.models import ConfigurationModel
class DarkLangConfig(ConfigurationModel):
"""
Configuration for the dark_lang django app
"""
released_languages = models.TextField(
blank=True,
help_text="A comma-separated list of language codes to release to the public."
)
@property
def released_languages_list(self):
"""
``released_languages`` as a list of language codes.
Example: ['it', 'de-at', 'es', 'pt-br']
"""
if not self.released_languages.strip(): # pylint: disable=no-member
return []
return [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member
## Instruction:
Put language modal in alphabetical order LMS-2302
## Code After:
from django.db import models
from config_models.models import ConfigurationModel
class DarkLangConfig(ConfigurationModel):
"""
Configuration for the dark_lang django app
"""
released_languages = models.TextField(
blank=True,
help_text="A comma-separated list of language codes to release to the public."
)
@property
def released_languages_list(self):
"""
``released_languages`` as a list of language codes.
Example: ['it', 'de-at', 'es', 'pt-br']
"""
if not self.released_languages.strip(): # pylint: disable=no-member
return []
languages = [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member
# Put in alphabetical order
languages.sort()
return languages
|
14b9ef43fd244d4709d14478ec0714325ca37cdb | tests/builtins/test_sum.py | tests/builtins/test_sum.py | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_bytearray',
'test_frozenzet',
]
| from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_frozenzet',
]
| Fix unexpected success on sum(bytearray()) | Fix unexpected success on sum(bytearray())
| Python | bsd-3-clause | cflee/voc,cflee/voc,freakboy3742/voc,freakboy3742/voc | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
- 'test_bytearray',
'test_frozenzet',
]
| Fix unexpected success on sum(bytearray()) | ## Code Before:
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_bytearray',
'test_frozenzet',
]
## Instruction:
Fix unexpected success on sum(bytearray())
## Code After:
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_frozenzet',
]
|
9ff92d0a437e5af08fbf996ed0e3362cbd9cf2c9 | tests/instrumentdb_test.py | tests/instrumentdb_test.py |
'Test the functions in the instrumentdb module.'
import os.path
import unittest as ut
import stripeline.instrumentdb as idb
class TestInstrumentDb(ut.TestCase):
def test_paths(self):
self.assertTrue(os.path.exists(idb.instrument_db_path()))
self.assertTrue(os.path.exists(idb.focal_plane_db_file_name()))
self.assertTrue(os.path.exists(idb.detector_db_file_name()))
self.assertTrue(os.path.exists(idb.scanning_strategy_db_file_name()))
|
'Test the functions in the instrumentdb module.'
import os.path
import unittest as ut
import stripeline.instrumentdb as idb
class TestInstrumentDb(ut.TestCase):
def test_paths(self):
self.assertTrue(os.path.exists(idb.instrument_db_path()),
'Path "{0}" not found'.format(idb.instrument_db_path()))
for file_name in (idb.focal_plane_db_file_name(),
idb.detector_db_file_name(),
idb.scanning_strategy_db_file_name()):
self.assertTrue(os.path.exists(file_name),
'File "{0}" not found'.format(file_name))
| Print more helpful messages when tests fail | Print more helpful messages when tests fail
| Python | mit | ziotom78/stripeline,ziotom78/stripeline |
'Test the functions in the instrumentdb module.'
import os.path
import unittest as ut
import stripeline.instrumentdb as idb
class TestInstrumentDb(ut.TestCase):
def test_paths(self):
- self.assertTrue(os.path.exists(idb.instrument_db_path()))
+ self.assertTrue(os.path.exists(idb.instrument_db_path()),
+ 'Path "{0}" not found'.format(idb.instrument_db_path()))
- self.assertTrue(os.path.exists(idb.focal_plane_db_file_name()))
+ for file_name in (idb.focal_plane_db_file_name(),
+ idb.detector_db_file_name(),
+ idb.scanning_strategy_db_file_name()):
- self.assertTrue(os.path.exists(idb.detector_db_file_name()))
+ self.assertTrue(os.path.exists(file_name),
- self.assertTrue(os.path.exists(idb.scanning_strategy_db_file_name()))
+ 'File "{0}" not found'.format(file_name))
| Print more helpful messages when tests fail | ## Code Before:
'Test the functions in the instrumentdb module.'
import os.path
import unittest as ut
import stripeline.instrumentdb as idb
class TestInstrumentDb(ut.TestCase):
def test_paths(self):
self.assertTrue(os.path.exists(idb.instrument_db_path()))
self.assertTrue(os.path.exists(idb.focal_plane_db_file_name()))
self.assertTrue(os.path.exists(idb.detector_db_file_name()))
self.assertTrue(os.path.exists(idb.scanning_strategy_db_file_name()))
## Instruction:
Print more helpful messages when tests fail
## Code After:
'Test the functions in the instrumentdb module.'
import os.path
import unittest as ut
import stripeline.instrumentdb as idb
class TestInstrumentDb(ut.TestCase):
def test_paths(self):
self.assertTrue(os.path.exists(idb.instrument_db_path()),
'Path "{0}" not found'.format(idb.instrument_db_path()))
for file_name in (idb.focal_plane_db_file_name(),
idb.detector_db_file_name(),
idb.scanning_strategy_db_file_name()):
self.assertTrue(os.path.exists(file_name),
'File "{0}" not found'.format(file_name))
|
7966f771c4b5450625d5247c6bf5369901457d9a | capstone/player/monte_carlo.py | capstone/player/monte_carlo.py | import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
return type(self).name
def move(self, game):
counter = defaultdict(int)
for i in range(self.n_sims):
for move in game.legal_moves():
new_game = game.copy()
new_game.make_move(move)
while not new_game.is_over():
rand_move = random.choice(new_game.legal_moves())
new_game.make_move(rand_move)
counter[move] += utility(new_game, game.cur_player())
m = Counter(counter).most_common(1)
return m[0][0]
##########
# Player #
##########
def choose_move(self, game):
return self.move(game)
| import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
return type(self).name
##########
# Player #
##########
def choose_move(self, game):
counter = defaultdict(int)
for i in range(self.n_sims):
for move in game.legal_moves():
new_game = game.copy()
new_game.make_move(move)
while not new_game.is_over():
rand_move = random.choice(new_game.legal_moves())
new_game.make_move(rand_move)
counter[move] += utility(new_game, game.cur_player())
best_move, count = Counter(counter).most_common(1)[0]
return best_move
| Move MonteCarlo move to choose_move | Move MonteCarlo move to choose_move
| Python | mit | davidrobles/mlnd-capstone-code | import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
return type(self).name
+ ##########
+ # Player #
+ ##########
+
- def move(self, game):
+ def choose_move(self, game):
counter = defaultdict(int)
for i in range(self.n_sims):
for move in game.legal_moves():
new_game = game.copy()
new_game.make_move(move)
while not new_game.is_over():
rand_move = random.choice(new_game.legal_moves())
new_game.make_move(rand_move)
counter[move] += utility(new_game, game.cur_player())
- m = Counter(counter).most_common(1)
+ best_move, count = Counter(counter).most_common(1)[0]
- return m[0][0]
+ return best_move
- ##########
- # Player #
- ##########
-
- def choose_move(self, game):
- return self.move(game)
- | Move MonteCarlo move to choose_move | ## Code Before:
import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
return type(self).name
def move(self, game):
counter = defaultdict(int)
for i in range(self.n_sims):
for move in game.legal_moves():
new_game = game.copy()
new_game.make_move(move)
while not new_game.is_over():
rand_move = random.choice(new_game.legal_moves())
new_game.make_move(rand_move)
counter[move] += utility(new_game, game.cur_player())
m = Counter(counter).most_common(1)
return m[0][0]
##########
# Player #
##########
def choose_move(self, game):
return self.move(game)
## Instruction:
Move MonteCarlo move to choose_move
## Code After:
import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
return type(self).name
##########
# Player #
##########
def choose_move(self, game):
counter = defaultdict(int)
for i in range(self.n_sims):
for move in game.legal_moves():
new_game = game.copy()
new_game.make_move(move)
while not new_game.is_over():
rand_move = random.choice(new_game.legal_moves())
new_game.make_move(rand_move)
counter[move] += utility(new_game, game.cur_player())
best_move, count = Counter(counter).most_common(1)[0]
return best_move
|
ba0ea7491fab383992013a8379592657eedfe1ce | scripts/contrib/model_info.py | scripts/contrib/model_info.py |
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints version and model type from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if S2S_SPECIAL_NODE not in model:
print("No special Marian YAML node found in the model")
exit(1)
yaml_text = bytes(model[S2S_SPECIAL_NODE]).decode('ascii')
if not args.key:
print(yaml_text)
exit(0)
# fix the invalid trailing unicode character '#x0000' added to the YAML
# string by the C++ cnpy library
try:
yaml_node = yaml.load(yaml_text)
except yaml.reader.ReaderError:
yaml_node = yaml.load(yaml_text[:-1])
print(yaml_node[args.key])
def parse_args():
parser = argparse.ArgumentParser(description=DESC)
parser.add_argument("-m", "--model", help="model file", required=True)
parser.add_argument("-k", "--key", help="print value for specific key")
return parser.parse_args()
if __name__ == "__main__":
main()
|
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints keys and values from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if args.special:
if S2S_SPECIAL_NODE not in model:
print("No special Marian YAML node found in the model")
exit(1)
yaml_text = bytes(model[S2S_SPECIAL_NODE]).decode('ascii')
if not args.key:
print(yaml_text)
exit(0)
# fix the invalid trailing unicode character '#x0000' added to the YAML
# string by the C++ cnpy library
try:
yaml_node = yaml.load(yaml_text)
except yaml.reader.ReaderError:
yaml_node = yaml.load(yaml_text[:-1])
print(yaml_node[args.key])
else:
if args.key:
if args.key not in model:
print("Key not found")
exit(1)
print(model[args.key])
else:
for key in model:
print(key)
def parse_args():
parser = argparse.ArgumentParser(description=DESC)
parser.add_argument("-m", "--model", help="model file", required=True)
parser.add_argument("-k", "--key", help="print value for specific key")
parser.add_argument("-s", "--special", action="store_true",
help="print values from special:model.yml node")
return parser.parse_args()
if __name__ == "__main__":
main()
| Add printing value for any key from model.npz | Add printing value for any key from model.npz
| Python | mit | emjotde/amunmt,emjotde/amunmt,marian-nmt/marian-train,emjotde/amunmt,amunmt/marian,emjotde/amunn,amunmt/marian,emjotde/amunn,emjotde/amunmt,marian-nmt/marian-train,emjotde/amunn,marian-nmt/marian-train,emjotde/amunn,marian-nmt/marian-train,emjotde/Marian,marian-nmt/marian-train,emjotde/Marian,amunmt/marian |
import sys
import argparse
import numpy as np
import yaml
- DESC = "Prints version and model type from model.npz file."
+ DESC = "Prints keys and values from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
+ model = np.load(args.model)
- model = np.load(args.model)
+ if args.special:
- if S2S_SPECIAL_NODE not in model:
+ if S2S_SPECIAL_NODE not in model:
- print("No special Marian YAML node found in the model")
+ print("No special Marian YAML node found in the model")
- exit(1)
+ exit(1)
- yaml_text = bytes(model[S2S_SPECIAL_NODE]).decode('ascii')
+ yaml_text = bytes(model[S2S_SPECIAL_NODE]).decode('ascii')
- if not args.key:
+ if not args.key:
- print(yaml_text)
+ print(yaml_text)
- exit(0)
+ exit(0)
- # fix the invalid trailing unicode character '#x0000' added to the YAML
+ # fix the invalid trailing unicode character '#x0000' added to the YAML
- # string by the C++ cnpy library
+ # string by the C++ cnpy library
- try:
+ try:
- yaml_node = yaml.load(yaml_text)
+ yaml_node = yaml.load(yaml_text)
- except yaml.reader.ReaderError:
+ except yaml.reader.ReaderError:
- yaml_node = yaml.load(yaml_text[:-1])
+ yaml_node = yaml.load(yaml_text[:-1])
- print(yaml_node[args.key])
+ print(yaml_node[args.key])
+ else:
+ if args.key:
+ if args.key not in model:
+ print("Key not found")
+ exit(1)
+ print(model[args.key])
+ else:
+ for key in model:
+ print(key)
def parse_args():
parser = argparse.ArgumentParser(description=DESC)
parser.add_argument("-m", "--model", help="model file", required=True)
parser.add_argument("-k", "--key", help="print value for specific key")
+ parser.add_argument("-s", "--special", action="store_true",
+ help="print values from special:model.yml node")
return parser.parse_args()
if __name__ == "__main__":
main()
| Add printing value for any key from model.npz | ## Code Before:
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints version and model type from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if S2S_SPECIAL_NODE not in model:
print("No special Marian YAML node found in the model")
exit(1)
yaml_text = bytes(model[S2S_SPECIAL_NODE]).decode('ascii')
if not args.key:
print(yaml_text)
exit(0)
# fix the invalid trailing unicode character '#x0000' added to the YAML
# string by the C++ cnpy library
try:
yaml_node = yaml.load(yaml_text)
except yaml.reader.ReaderError:
yaml_node = yaml.load(yaml_text[:-1])
print(yaml_node[args.key])
def parse_args():
parser = argparse.ArgumentParser(description=DESC)
parser.add_argument("-m", "--model", help="model file", required=True)
parser.add_argument("-k", "--key", help="print value for specific key")
return parser.parse_args()
if __name__ == "__main__":
main()
## Instruction:
Add printing value for any key from model.npz
## Code After:
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints keys and values from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if args.special:
if S2S_SPECIAL_NODE not in model:
print("No special Marian YAML node found in the model")
exit(1)
yaml_text = bytes(model[S2S_SPECIAL_NODE]).decode('ascii')
if not args.key:
print(yaml_text)
exit(0)
# fix the invalid trailing unicode character '#x0000' added to the YAML
# string by the C++ cnpy library
try:
yaml_node = yaml.load(yaml_text)
except yaml.reader.ReaderError:
yaml_node = yaml.load(yaml_text[:-1])
print(yaml_node[args.key])
else:
if args.key:
if args.key not in model:
print("Key not found")
exit(1)
print(model[args.key])
else:
for key in model:
print(key)
def parse_args():
parser = argparse.ArgumentParser(description=DESC)
parser.add_argument("-m", "--model", help="model file", required=True)
parser.add_argument("-k", "--key", help="print value for specific key")
parser.add_argument("-s", "--special", action="store_true",
help="print values from special:model.yml node")
return parser.parse_args()
if __name__ == "__main__":
main()
|
48e405f0f2027c82403c96b58023f1308c3f7c14 | model/orderbook.py | model/orderbook.py |
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
oanda = oandapy.API(environment="practice", access_token=oanda_token)
orders = oanda.get_orderbook(instrument=instrument)
try:
timeset = orders.keys()
timeset.sort()
timeset.reverse()
target_time = timeset[history]
except:
return None
order = orders[target_time]
order['time'] = target_time
return order
|
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
oanda_environment = os.environ.get('OANDA_ENVIRONMENT', 'practice')
oanda = oandapy.API(environment=oanda_environment, access_token=oanda_token)
orders = oanda.get_orderbook(instrument=instrument)
try:
timeset = orders.keys()
timeset.sort()
timeset.reverse()
target_time = timeset[history]
except:
return None
order = orders[target_time]
order['time'] = target_time
return order
| Add oanda environment selector from runtime environments. | Add oanda environment selector from runtime environments.
| Python | mit | supistar/OandaOrderbook,supistar/OandaOrderbook,supistar/OandaOrderbook |
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
+ oanda_environment = os.environ.get('OANDA_ENVIRONMENT', 'practice')
- oanda = oandapy.API(environment="practice", access_token=oanda_token)
+ oanda = oandapy.API(environment=oanda_environment, access_token=oanda_token)
orders = oanda.get_orderbook(instrument=instrument)
try:
timeset = orders.keys()
timeset.sort()
timeset.reverse()
target_time = timeset[history]
except:
return None
order = orders[target_time]
order['time'] = target_time
return order
| Add oanda environment selector from runtime environments. | ## Code Before:
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
oanda = oandapy.API(environment="practice", access_token=oanda_token)
orders = oanda.get_orderbook(instrument=instrument)
try:
timeset = orders.keys()
timeset.sort()
timeset.reverse()
target_time = timeset[history]
except:
return None
order = orders[target_time]
order['time'] = target_time
return order
## Instruction:
Add oanda environment selector from runtime environments.
## Code After:
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
oanda_environment = os.environ.get('OANDA_ENVIRONMENT', 'practice')
oanda = oandapy.API(environment=oanda_environment, access_token=oanda_token)
orders = oanda.get_orderbook(instrument=instrument)
try:
timeset = orders.keys()
timeset.sort()
timeset.reverse()
target_time = timeset[history]
except:
return None
order = orders[target_time]
order['time'] = target_time
return order
|
0fe990cf476dcd0cdea56c39de1dad6003d81851 | statbot/mention.py | statbot/mention.py |
from enum import auto, Enum
__all__ = [
'MentionType',
]
class MentionType(Enum):
USER = auto()
ROLE = auto()
CHANNEL = auto()
|
from enum import Enum
__all__ = [
'MentionType',
]
class MentionType(Enum):
USER = 0
ROLE = 1
CHANNEL = 2
| Change MentionType to use fixed enum values. | Change MentionType to use fixed enum values.
| Python | mit | strinking/statbot,strinking/statbot |
- from enum import auto, Enum
+ from enum import Enum
__all__ = [
'MentionType',
]
class MentionType(Enum):
- USER = auto()
+ USER = 0
- ROLE = auto()
+ ROLE = 1
- CHANNEL = auto()
+ CHANNEL = 2
| Change MentionType to use fixed enum values. | ## Code Before:
from enum import auto, Enum
__all__ = [
'MentionType',
]
class MentionType(Enum):
USER = auto()
ROLE = auto()
CHANNEL = auto()
## Instruction:
Change MentionType to use fixed enum values.
## Code After:
from enum import Enum
__all__ = [
'MentionType',
]
class MentionType(Enum):
USER = 0
ROLE = 1
CHANNEL = 2
|
06c2fe1bd836f4adfcff4eb35cc29203e10a729d | blinkytape/animation.py | blinkytape/animation.py |
class Animation(object):
def __init__(self, frame_period_sec):
if frame_period_sec < 0: raise ValueError
self._frame_period_sec = frame_period_sec
@property
def frame_period_sec(self):
return self._frame_period_sec
def begin(self):
pass
def next_frame(self):
pass
def end(self):
pass
|
class Animation(object):
def __init__(self, frame_period_sec):
if frame_period_sec < 0: raise ValueError
self._frame_period_sec = frame_period_sec
@property
def frame_period_sec(self):
return self._frame_period_sec
@property
def finished(self):
raise NotImplementedError('Animation must implement finished property')
def begin(self):
pass
def next_frame(self):
raise NotImplementedError('Animation must implement next_frame method')
def end(self):
pass
| Add abstract method exceptions to make Animation inheritance easier | Add abstract method exceptions to make Animation inheritance easier
| Python | mit | jonspeicher/blinkyfun |
class Animation(object):
def __init__(self, frame_period_sec):
if frame_period_sec < 0: raise ValueError
self._frame_period_sec = frame_period_sec
@property
def frame_period_sec(self):
return self._frame_period_sec
+ @property
+ def finished(self):
+ raise NotImplementedError('Animation must implement finished property')
+
def begin(self):
pass
def next_frame(self):
- pass
+ raise NotImplementedError('Animation must implement next_frame method')
def end(self):
pass
| Add abstract method exceptions to make Animation inheritance easier | ## Code Before:
class Animation(object):
def __init__(self, frame_period_sec):
if frame_period_sec < 0: raise ValueError
self._frame_period_sec = frame_period_sec
@property
def frame_period_sec(self):
return self._frame_period_sec
def begin(self):
pass
def next_frame(self):
pass
def end(self):
pass
## Instruction:
Add abstract method exceptions to make Animation inheritance easier
## Code After:
class Animation(object):
def __init__(self, frame_period_sec):
if frame_period_sec < 0: raise ValueError
self._frame_period_sec = frame_period_sec
@property
def frame_period_sec(self):
return self._frame_period_sec
@property
def finished(self):
raise NotImplementedError('Animation must implement finished property')
def begin(self):
pass
def next_frame(self):
raise NotImplementedError('Animation must implement next_frame method')
def end(self):
pass
|
f2d34fa3153448ab6a893fba45ae48b52d7759db | chipy_org/apps/profiles/urls.py | chipy_org/apps/profiles/urls.py | from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from profiles.views import (ProfilesList,
ProfileEdit,
)
urlpatterns = patterns("",
url(r'^list/$', ProfilesList.as_view(), name='list'),
url(r'^edit/$', ProfileEdit.as_view(), name='edit'),
)
| from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from .views import ProfilesList, ProfileEdit
urlpatterns = patterns("",
url(r'^list/$', ProfilesList.as_view(), name='list'),
url(r'^edit/$', login_required(ProfileEdit).as_view(), name='edit'),
)
| Add login required for profile edit | Add login required for profile edit
| Python | mit | agfor/chipy.org,brianray/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,chicagopython/chipy.org,brianray/chipy.org,agfor/chipy.org | from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
- from profiles.views import (ProfilesList,
+ from .views import ProfilesList, ProfileEdit
- ProfileEdit,
- )
urlpatterns = patterns("",
url(r'^list/$', ProfilesList.as_view(), name='list'),
- url(r'^edit/$', ProfileEdit.as_view(), name='edit'),
+ url(r'^edit/$', login_required(ProfileEdit).as_view(), name='edit'),
)
| Add login required for profile edit | ## Code Before:
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from profiles.views import (ProfilesList,
ProfileEdit,
)
urlpatterns = patterns("",
url(r'^list/$', ProfilesList.as_view(), name='list'),
url(r'^edit/$', ProfileEdit.as_view(), name='edit'),
)
## Instruction:
Add login required for profile edit
## Code After:
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from .views import ProfilesList, ProfileEdit
urlpatterns = patterns("",
url(r'^list/$', ProfilesList.as_view(), name='list'),
url(r'^edit/$', login_required(ProfileEdit).as_view(), name='edit'),
)
|
3f236d74615dced53c57628ae1b5f2c74f9e1de5 | examples/rate_limiting_test.py | examples/rate_limiting_test.py | from seleniumbase import BaseCase
from seleniumbase.common import decorators
class MyTestClass(BaseCase):
@decorators.rate_limited(3.5) # The arg is max calls per second
def print_item(self, item):
print(item)
def test_rate_limited_printing(self):
print("\nRunning rate-limited print test:")
for item in xrange(1, 11):
self.print_item(item)
|
import unittest
from seleniumbase.common import decorators
class MyTestClass(unittest.TestCase):
@decorators.rate_limited(3.5) # The arg is max calls per second
def print_item(self, item):
print(item)
def test_rate_limited_printing(self):
print("\nRunning rate-limited print test:")
for item in xrange(1, 11):
self.print_item(item)
| Update the rate_limited decorator test | Update the rate_limited decorator test
| Python | mit | seleniumbase/SeleniumBase,possoumous/Watchers,possoumous/Watchers,mdmintz/SeleniumBase,possoumous/Watchers,ktp420/SeleniumBase,seleniumbase/SeleniumBase,ktp420/SeleniumBase,mdmintz/SeleniumBase,ktp420/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/seleniumspot,ktp420/SeleniumBase,mdmintz/seleniumspot,seleniumbase/SeleniumBase,possoumous/Watchers | - from seleniumbase import BaseCase
+
+ import unittest
from seleniumbase.common import decorators
- class MyTestClass(BaseCase):
+ class MyTestClass(unittest.TestCase):
@decorators.rate_limited(3.5) # The arg is max calls per second
def print_item(self, item):
print(item)
def test_rate_limited_printing(self):
print("\nRunning rate-limited print test:")
for item in xrange(1, 11):
self.print_item(item)
| Update the rate_limited decorator test | ## Code Before:
from seleniumbase import BaseCase
from seleniumbase.common import decorators
class MyTestClass(BaseCase):
@decorators.rate_limited(3.5) # The arg is max calls per second
def print_item(self, item):
print(item)
def test_rate_limited_printing(self):
print("\nRunning rate-limited print test:")
for item in xrange(1, 11):
self.print_item(item)
## Instruction:
Update the rate_limited decorator test
## Code After:
import unittest
from seleniumbase.common import decorators
class MyTestClass(unittest.TestCase):
@decorators.rate_limited(3.5) # The arg is max calls per second
def print_item(self, item):
print(item)
def test_rate_limited_printing(self):
print("\nRunning rate-limited print test:")
for item in xrange(1, 11):
self.print_item(item)
|
2a23e72f7ad01976bcd80aa91f89882e2a37cbf6 | test/test_model.py | test/test_model.py | import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).build()
assert [('const2', {'str': 'hello'})] == m.create()
def test_model_with_multiple_entities():
m = model(
entity('first', {'name': lambda: 'elves'}),
entity('second', {'name': lambda: 'humans'})).build()
assert [('first', {'name': 'elves'}),
('second', {'name': 'humans'})] == m.create()
def test_model_with_multiple_params():
m = model(entity('human', {
'head': lambda: 1,
'hands': lambda: 2,
'name': lambda: 'Hurin',
})).build()
assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
| import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).build()
assert [('const2', {'str': 'hello'})] == m.create()
def test_model_with_multiple_entities():
m = model(
entity('first', {'name': lambda: 'elves'}),
entity('second', {'name': lambda: 'humans'})).build()
assert [('first', {'name': 'elves'}),
('second', {'name': 'humans'})] == m.create()
def test_model_with_multiple_params():
m = model(entity('human', {
'head': lambda: 1,
'hands': lambda: 2,
'name': lambda: 'Hurin',
})).build()
assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
# error handling
def test_same_enitities_should_throw_error():
pass
def test_same_params_should_throw_error():
pass
| Test blueprints for corner cases | Test blueprints for corner cases
| Python | mit | ahitrin/carlo | import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).build()
assert [('const2', {'str': 'hello'})] == m.create()
def test_model_with_multiple_entities():
m = model(
entity('first', {'name': lambda: 'elves'}),
entity('second', {'name': lambda: 'humans'})).build()
assert [('first', {'name': 'elves'}),
('second', {'name': 'humans'})] == m.create()
def test_model_with_multiple_params():
m = model(entity('human', {
'head': lambda: 1,
'hands': lambda: 2,
'name': lambda: 'Hurin',
})).build()
assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
+ # error handling
+
+ def test_same_enitities_should_throw_error():
+ pass
+
+ def test_same_params_should_throw_error():
+ pass
+ | Test blueprints for corner cases | ## Code Before:
import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).build()
assert [('const2', {'str': 'hello'})] == m.create()
def test_model_with_multiple_entities():
m = model(
entity('first', {'name': lambda: 'elves'}),
entity('second', {'name': lambda: 'humans'})).build()
assert [('first', {'name': 'elves'}),
('second', {'name': 'humans'})] == m.create()
def test_model_with_multiple_params():
m = model(entity('human', {
'head': lambda: 1,
'hands': lambda: 2,
'name': lambda: 'Hurin',
})).build()
assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
## Instruction:
Test blueprints for corner cases
## Code After:
import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).build()
assert [('const2', {'str': 'hello'})] == m.create()
def test_model_with_multiple_entities():
m = model(
entity('first', {'name': lambda: 'elves'}),
entity('second', {'name': lambda: 'humans'})).build()
assert [('first', {'name': 'elves'}),
('second', {'name': 'humans'})] == m.create()
def test_model_with_multiple_params():
m = model(entity('human', {
'head': lambda: 1,
'hands': lambda: 2,
'name': lambda: 'Hurin',
})).build()
assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
# error handling
def test_same_enitities_should_throw_error():
pass
def test_same_params_should_throw_error():
pass
|
4b56e0da85cec4aa89b8105c3a7ca416a2f7919e | wdim/client/blob.py | wdim/client/blob.py | import json
import hashlib
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self):
return self._id
| import json
import hashlib
from typing import Any, Dict
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data: Dict[str, Any]) -> 'Blob':
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self) -> str:
return self._id
def __getitem__(self, key):
return self.data[key]
| Allow Blob to be accessed with __getitem__ | Allow Blob to be accessed with __getitem__
| Python | mit | chrisseto/Still | import json
import hashlib
+ from typing import Any, Dict
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
- async def create(cls, data):
+ async def create(cls, data: Dict[str, Any]) -> 'Blob':
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
- def hash(self):
+ def hash(self) -> str:
return self._id
+ def __getitem__(self, key):
+ return self.data[key]
+ | Allow Blob to be accessed with __getitem__ | ## Code Before:
import json
import hashlib
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self):
return self._id
## Instruction:
Allow Blob to be accessed with __getitem__
## Code After:
import json
import hashlib
from typing import Any, Dict
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data: Dict[str, Any]) -> 'Blob':
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self) -> str:
return self._id
def __getitem__(self, key):
return self.data[key]
|
a78445cfada5cc1f77a7887dc5241071bef69989 | compass/tests/test_models.py | compass/tests/test_models.py | from django.test import TestCase
from compass.models import (Category,
Book)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
| from django.test import TestCase
from compass.models import (Category,
Book, Compass)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
class CompassTestCase(TestCase):
def test_correct_title_if_not_title_and_category(self,):
heading = Compass.heading(title="", category="")
self.assertEqual(heading, "All books")
def test_correct_title_if_not_category(self,):
heading = Compass.heading(title="Title 1", category="")
self.assertEqual(heading, "All book titles like Title 1")
def test_correct_title_if_not_title(self,):
heading = Compass.heading(title="", category="Category 1")
self.assertEqual(heading, "All book titles under Category 1")
| Test correct heading returned in search results | Test correct heading returned in search results
| Python | mit | andela-osule/bookworm,andela-osule/bookworm | from django.test import TestCase
from compass.models import (Category,
- Book)
+ Book, Compass)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
+
+ class CompassTestCase(TestCase):
+ def test_correct_title_if_not_title_and_category(self,):
+ heading = Compass.heading(title="", category="")
+ self.assertEqual(heading, "All books")
+
+ def test_correct_title_if_not_category(self,):
+ heading = Compass.heading(title="Title 1", category="")
+ self.assertEqual(heading, "All book titles like Title 1")
+
+ def test_correct_title_if_not_title(self,):
+ heading = Compass.heading(title="", category="Category 1")
+ self.assertEqual(heading, "All book titles under Category 1")
+ | Test correct heading returned in search results | ## Code Before:
from django.test import TestCase
from compass.models import (Category,
Book)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
## Instruction:
Test correct heading returned in search results
## Code After:
from django.test import TestCase
from compass.models import (Category,
Book, Compass)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
class CompassTestCase(TestCase):
def test_correct_title_if_not_title_and_category(self,):
heading = Compass.heading(title="", category="")
self.assertEqual(heading, "All books")
def test_correct_title_if_not_category(self,):
heading = Compass.heading(title="Title 1", category="")
self.assertEqual(heading, "All book titles like Title 1")
def test_correct_title_if_not_title(self,):
heading = Compass.heading(title="", category="Category 1")
self.assertEqual(heading, "All book titles under Category 1")
|
eaa2ef92eba11d44bf5159342e314b932d79f58d | fedora/__init__.py | fedora/__init__.py | '''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
# Needed for our unit tests
from fedora.wsgi.test import websetup
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup')
| '''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup')
| Undo the webtest import... it's causing runtime failiure and unittests are currently broken anyway. | Undo the webtest import... it's causing runtime failiure and unittests are
currently broken anyway.
| Python | lgpl-2.1 | fedora-infra/python-fedora | '''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
- # Needed for our unit tests
- from fedora.wsgi.test import websetup
-
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup')
| Undo the webtest import... it's causing runtime failiure and unittests are currently broken anyway. | ## Code Before:
'''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
# Needed for our unit tests
from fedora.wsgi.test import websetup
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup')
## Instruction:
Undo the webtest import... it's causing runtime failiure and unittests are currently broken anyway.
## Code After:
'''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup')
|
662287761b8549a86d3fb8c05ec37d47491da120 | flatblocks/urls.py | flatblocks/urls.py | from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path("^edit/(?P<pk>\d+)/$", staff_member_required(edit), name="flatblocks-edit"),
]
| from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path(
r"^edit/(?P<pk>\d+)/$",
staff_member_required(edit),
name="flatblocks-edit",
),
]
| Use raw string notation for regular expression. | Use raw string notation for regular expression.
| Python | bsd-3-clause | funkybob/django-flatblocks,funkybob/django-flatblocks | from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
- re_path("^edit/(?P<pk>\d+)/$", staff_member_required(edit), name="flatblocks-edit"),
+ re_path(
+ r"^edit/(?P<pk>\d+)/$",
+ staff_member_required(edit),
+ name="flatblocks-edit",
+ ),
]
| Use raw string notation for regular expression. | ## Code Before:
from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path("^edit/(?P<pk>\d+)/$", staff_member_required(edit), name="flatblocks-edit"),
]
## Instruction:
Use raw string notation for regular expression.
## Code After:
from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path(
r"^edit/(?P<pk>\d+)/$",
staff_member_required(edit),
name="flatblocks-edit",
),
]
|
1cc6ec9f328d3ce045a4a1a50138b11c0b23cc3a | pyfr/ctypesutil.py | pyfr/ctypesutil.py |
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
# First attempt to utilise the system search path
try:
return ctypes.CDLL(lname)
# Otherwise, if this fails then run our own search
except OSError:
for sd in sdirs:
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
|
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
# If an explicit override has been given then use it
lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
if lpath:
return ctypes.CDLL(lpath)
# Otherwise synthesise the library name and start searching
lname = platform_libname(name)
# Start with system search path
try:
return ctypes.CDLL(lname)
# ..and if this fails then run our own search
except OSError:
for sd in platform_libdirs():
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
| Enable library paths to be explicitly specified. | Enable library paths to be explicitly specified.
All shared libraries loaded through the load_library function
can bow be specified explicitly through a suitable environmental
variable
PYFR_<LIB>_LIBRARY_PATH=/path/to/lib.here
where <LIB> corresponds to the name of the library, e.g. METIS.
| Python | bsd-3-clause | BrianVermeire/PyFR |
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
+ # If an explicit override has been given then use it
+ lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
+ if lpath:
+ return ctypes.CDLL(lpath)
+
+ # Otherwise synthesise the library name and start searching
lname = platform_libname(name)
- sdirs = platform_libdirs()
- # First attempt to utilise the system search path
+ # Start with system search path
try:
return ctypes.CDLL(lname)
- # Otherwise, if this fails then run our own search
+ # ..and if this fails then run our own search
except OSError:
- for sd in sdirs:
+ for sd in platform_libdirs():
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
| Enable library paths to be explicitly specified. | ## Code Before:
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
# First attempt to utilise the system search path
try:
return ctypes.CDLL(lname)
# Otherwise, if this fails then run our own search
except OSError:
for sd in sdirs:
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
## Instruction:
Enable library paths to be explicitly specified.
## Code After:
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
# If an explicit override has been given then use it
lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
if lpath:
return ctypes.CDLL(lpath)
# Otherwise synthesise the library name and start searching
lname = platform_libname(name)
# Start with system search path
try:
return ctypes.CDLL(lname)
# ..and if this fails then run our own search
except OSError:
for sd in platform_libdirs():
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
|
8237291e194aa900857fe382d0b8cefb7806c331 | ocradmin/ocrmodels/models.py | ocradmin/ocrmodels/models.py | from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=True)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True)
public = models.BooleanField(default=True)
file = models.FileField(upload_to="models")
type = models.CharField(max_length=20,
choices=[("char", "Character"), ("lang", "Language")])
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
def __unicode__(self):
"""
String representation.
"""
return self.name
| from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=True)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True)
public = models.BooleanField(default=True)
file = models.FileField(upload_to="models")
type = models.CharField(max_length=20,
choices=[("char", "Character"), ("lang", "Language")])
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
def __unicode__(self):
"""
String representation.
"""
return "<%s: %s>" % (self.__class__.__name__, self.name)
| Improve unicode method. Whitespace cleanup | Improve unicode method. Whitespace cleanup
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=True)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True)
public = models.BooleanField(default=True)
file = models.FileField(upload_to="models")
type = models.CharField(max_length=20,
choices=[("char", "Character"), ("lang", "Language")])
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
-
def __unicode__(self):
"""
String representation.
"""
- return self.name
+ return "<%s: %s>" % (self.__class__.__name__, self.name)
-
+ | Improve unicode method. Whitespace cleanup | ## Code Before:
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=True)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True)
public = models.BooleanField(default=True)
file = models.FileField(upload_to="models")
type = models.CharField(max_length=20,
choices=[("char", "Character"), ("lang", "Language")])
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
def __unicode__(self):
"""
String representation.
"""
return self.name
## Instruction:
Improve unicode method. Whitespace cleanup
## Code After:
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=True)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True)
public = models.BooleanField(default=True)
file = models.FileField(upload_to="models")
type = models.CharField(max_length=20,
choices=[("char", "Character"), ("lang", "Language")])
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
def __unicode__(self):
"""
String representation.
"""
return "<%s: %s>" % (self.__class__.__name__, self.name)
|
7a99695c7612609de294a6905820fad3e41afc43 | marketpulse/devices/models.py | marketpulse/devices/models.py | from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
| from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
class Meta:
ordering = ['manufacturer', 'model']
| Order devices by manufacturer and model. | Order devices by manufacturer and model.
| Python | mpl-2.0 | johngian/marketpulse,akatsoulas/marketpulse,johngian/marketpulse,mozilla/marketpulse,mozilla/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse | from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
+ class Meta:
+ ordering = ['manufacturer', 'model']
+ | Order devices by manufacturer and model. | ## Code Before:
from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
## Instruction:
Order devices by manufacturer and model.
## Code After:
from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
class Meta:
ordering = ['manufacturer', 'model']
|
ecbabd56f6afc4474402d3293bf11e3b6eb2e8f4 | server/__init__.py | server/__init__.py | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHtmlVars(girderRoot.vars)
histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'})
info['serverRoot'].histomicstk = histomicsRoot
info['serverRoot'].girder = girderRoot
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
genRESTEndPointsForSlicerCLIsInDocker(info,
'HistomicsTK',
'dsarchive/histomicstk') | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHtmlVars(girderRoot.vars)
histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'})
info['serverRoot'].histomicstk = histomicsRoot
info['serverRoot'].girder = girderRoot
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
_ = genRESTEndPointsForSlicerCLIsInDocker(
info, 'HistomicsTK', 'dsarchive/histomicstk'
) | Switch to generating REST end points from docker image | Switch to generating REST end points from docker image
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHtmlVars(girderRoot.vars)
histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'})
info['serverRoot'].histomicstk = histomicsRoot
info['serverRoot'].girder = girderRoot
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
- genRESTEndPointsForSlicerCLIsInDocker(info,
+ _ = genRESTEndPointsForSlicerCLIsInDocker(
- 'HistomicsTK',
- 'dsarchive/histomicstk')
+ info, 'HistomicsTK', 'dsarchive/histomicstk'
+ ) | Switch to generating REST end points from docker image | ## Code Before:
import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHtmlVars(girderRoot.vars)
histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'})
info['serverRoot'].histomicstk = histomicsRoot
info['serverRoot'].girder = girderRoot
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
genRESTEndPointsForSlicerCLIsInDocker(info,
'HistomicsTK',
'dsarchive/histomicstk')
## Instruction:
Switch to generating REST end points from docker image
## Code After:
import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHtmlVars(girderRoot.vars)
histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'})
info['serverRoot'].histomicstk = histomicsRoot
info['serverRoot'].girder = girderRoot
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
_ = genRESTEndPointsForSlicerCLIsInDocker(
info, 'HistomicsTK', 'dsarchive/histomicstk'
) |
56dc9af410907780faba79699d274bef96a18675 | functionaltests/common/base.py | functionaltests/common/base.py |
import tempest_lib.base
from functionaltests.common.config import read_config
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
def __init__(self, *args, **kwargs):
super(BaseDesignateTest, self).__init__(*args, **kwargs)
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass()
read_config()
|
import tempest_lib.base
from functionaltests.common.config import read_config
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass()
read_config()
| Remove unnecessary __init__ from functionaltests | Remove unnecessary __init__ from functionaltests
The __init__ just passes the same arguments, so it is not necessary
to implement it. This patch removes it for the cleanup.
Change-Id: Ib465356c47d06bfc66bef69126b089be24d19474
| Python | apache-2.0 | openstack/designate,openstack/designate,openstack/designate |
import tempest_lib.base
from functionaltests.common.config import read_config
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
- def __init__(self, *args, **kwargs):
- super(BaseDesignateTest, self).__init__(*args, **kwargs)
-
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass()
read_config()
| Remove unnecessary __init__ from functionaltests | ## Code Before:
import tempest_lib.base
from functionaltests.common.config import read_config
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
def __init__(self, *args, **kwargs):
super(BaseDesignateTest, self).__init__(*args, **kwargs)
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass()
read_config()
## Instruction:
Remove unnecessary __init__ from functionaltests
## Code After:
import tempest_lib.base
from functionaltests.common.config import read_config
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass()
read_config()
|
def9d7037a3c629f63e1a0d8c1721501abc110cd | linguee_api/downloaders/httpx_downloader.py | linguee_api/downloaders/httpx_downloader.py | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
ERROR_503 = (
"The Linguee server returned 503. The API proxy was temporarily blocked by "
"Linguee. For more details, see https://github.com/imankulov/linguee-api#"
"the-api-server-returns-the-linguee-server-returned-503"
)
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code == 503:
raise DownloaderError(ERROR_503)
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| Update the 503 error message. | Update the 503 error message.
| Python | mit | imankulov/linguee-api | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
+
+ ERROR_503 = (
+ "The Linguee server returned 503. The API proxy was temporarily blocked by "
+ "Linguee. For more details, see https://github.com/imankulov/linguee-api#"
+ "the-api-server-returns-the-linguee-server-returned-503"
+ )
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
+
+ if response.status_code == 503:
+ raise DownloaderError(ERROR_503)
+
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| Update the 503 error message. | ## Code Before:
import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
## Instruction:
Update the 503 error message.
## Code After:
import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
ERROR_503 = (
"The Linguee server returned 503. The API proxy was temporarily blocked by "
"Linguee. For more details, see https://github.com/imankulov/linguee-api#"
"the-api-server-returns-the-linguee-server-returned-503"
)
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code == 503:
raise DownloaderError(ERROR_503)
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
|
ffa00eaea02cda8258bf42d4fa733fb8693e2f0c | chemtrails/apps.py | chemtrails/apps.py |
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL)
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE', False)
|
import os
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL',
os.environ.get('NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL))
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE',
os.environ.get('NEOMODEL_FORCE_TIMEZONE', False))
| Read Neo4j config from ENV if present | Read Neo4j config from ENV if present
| Python | mit | inonit/django-chemtrails,inonit/django-chemtrails,inonit/django-chemtrails | +
+ import os
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
- config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL)
+ config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL',
+ os.environ.get('NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL))
- config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE', False)
+ config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE',
+ os.environ.get('NEOMODEL_FORCE_TIMEZONE', False))
| Read Neo4j config from ENV if present | ## Code Before:
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL)
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE', False)
## Instruction:
Read Neo4j config from ENV if present
## Code After:
import os
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL',
os.environ.get('NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL))
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE',
os.environ.get('NEOMODEL_FORCE_TIMEZONE', False))
|
d4db750d2ff2e18c9fced49fffe7a3073880078b | InvenTree/common/apps.py | InvenTree/common/apps.py |
from django.apps import AppConfig
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
pass
|
import logging
from django.apps import AppConfig
logger = logging.getLogger('inventree')
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.clear_restart_flag()
def clear_restart_flag(self):
"""
Clear the SERVER_RESTART_REQUIRED setting
"""
try:
import common.models
if common.models.InvenTreeSetting.get_setting('SERVER_RESTART_REQUIRED'):
logger.info("Clearing SERVER_RESTART_REQUIRED flag")
common.models.InvenTreeSetting.set_setting('SERVER_RESTART_REQUIRED', False, None)
except:
pass
| Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads | Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads
| Python | mit | SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree | +
+ import logging
from django.apps import AppConfig
+
+
+ logger = logging.getLogger('inventree')
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
- pass
+
+ self.clear_restart_flag()
+ def clear_restart_flag(self):
+ """
+ Clear the SERVER_RESTART_REQUIRED setting
+ """
+
+ try:
+ import common.models
+
+ if common.models.InvenTreeSetting.get_setting('SERVER_RESTART_REQUIRED'):
+ logger.info("Clearing SERVER_RESTART_REQUIRED flag")
+ common.models.InvenTreeSetting.set_setting('SERVER_RESTART_REQUIRED', False, None)
+ except:
+ pass
+ | Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads | ## Code Before:
from django.apps import AppConfig
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
pass
## Instruction:
Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads
## Code After:
import logging
from django.apps import AppConfig
logger = logging.getLogger('inventree')
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.clear_restart_flag()
def clear_restart_flag(self):
"""
Clear the SERVER_RESTART_REQUIRED setting
"""
try:
import common.models
if common.models.InvenTreeSetting.get_setting('SERVER_RESTART_REQUIRED'):
logger.info("Clearing SERVER_RESTART_REQUIRED flag")
common.models.InvenTreeSetting.set_setting('SERVER_RESTART_REQUIRED', False, None)
except:
pass
|
ae918211a85654d7eaa848cbd09f717d0339f844 | database_email_backend/backend.py | database_email_backend/backend.py | from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
return
for message in email_messages:
email = Email.objects.create(
from_email = message.from_email,
to_emails = ', '.join(message.to),
cc_emails = ', '.join(message.cc),
bcc_emails = ', '.join(message.bcc),
all_recipients = ', '.join(message.recipients()),
subject = message.subject,
body = message.body,
raw = message.message().as_string()
)
for attachment in message.attachments:
if isinstance(attachment, tuple):
filename, content, mimetype = attachment
elif isinstance(attachment, MIMEBase):
filename = attachment.get_filename()
content = attachment.get_payload(decode=True)
mimetype = None
else:
continue
Attachment.objects.create(
email=email,
filename=filename,
content=content,
mimetype=mimetype
)
| from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
return
for message in email_messages:
email = Email.objects.create(
from_email = u'%s' % message.from_email,
to_emails = u', '.join(message.to),
cc_emails = u', '.join(message.cc),
bcc_emails = u', '.join(message.bcc),
all_recipients = u', '.join(message.recipients()),
subject = u'%s' % message.subject,
body = u'%s' % message.body,
raw = u'%s' % message.message().as_string()
)
for attachment in message.attachments:
if isinstance(attachment, tuple):
filename, content, mimetype = attachment
elif isinstance(attachment, MIMEBase):
filename = attachment.get_filename()
content = attachment.get_payload(decode=True)
mimetype = None
else:
continue
Attachment.objects.create(
email=email,
filename=filename,
content=content,
mimetype=mimetype
)
| Convert everything to unicode strings before inserting to DB | Convert everything to unicode strings before inserting to DB | Python | mit | machtfit/django-database-email-backend,machtfit/django-database-email-backend,jbinary/django-database-email-backend,stefanfoulis/django-database-email-backend,jbinary/django-database-email-backend | from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
return
for message in email_messages:
email = Email.objects.create(
- from_email = message.from_email,
+ from_email = u'%s' % message.from_email,
- to_emails = ', '.join(message.to),
+ to_emails = u', '.join(message.to),
- cc_emails = ', '.join(message.cc),
+ cc_emails = u', '.join(message.cc),
- bcc_emails = ', '.join(message.bcc),
+ bcc_emails = u', '.join(message.bcc),
- all_recipients = ', '.join(message.recipients()),
+ all_recipients = u', '.join(message.recipients()),
- subject = message.subject,
+ subject = u'%s' % message.subject,
- body = message.body,
+ body = u'%s' % message.body,
- raw = message.message().as_string()
+ raw = u'%s' % message.message().as_string()
)
for attachment in message.attachments:
if isinstance(attachment, tuple):
filename, content, mimetype = attachment
elif isinstance(attachment, MIMEBase):
filename = attachment.get_filename()
content = attachment.get_payload(decode=True)
mimetype = None
else:
continue
Attachment.objects.create(
email=email,
filename=filename,
content=content,
mimetype=mimetype
)
| Convert everything to unicode strings before inserting to DB | ## Code Before:
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
return
for message in email_messages:
email = Email.objects.create(
from_email = message.from_email,
to_emails = ', '.join(message.to),
cc_emails = ', '.join(message.cc),
bcc_emails = ', '.join(message.bcc),
all_recipients = ', '.join(message.recipients()),
subject = message.subject,
body = message.body,
raw = message.message().as_string()
)
for attachment in message.attachments:
if isinstance(attachment, tuple):
filename, content, mimetype = attachment
elif isinstance(attachment, MIMEBase):
filename = attachment.get_filename()
content = attachment.get_payload(decode=True)
mimetype = None
else:
continue
Attachment.objects.create(
email=email,
filename=filename,
content=content,
mimetype=mimetype
)
## Instruction:
Convert everything to unicode strings before inserting to DB
## Code After:
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
return
for message in email_messages:
email = Email.objects.create(
from_email = u'%s' % message.from_email,
to_emails = u', '.join(message.to),
cc_emails = u', '.join(message.cc),
bcc_emails = u', '.join(message.bcc),
all_recipients = u', '.join(message.recipients()),
subject = u'%s' % message.subject,
body = u'%s' % message.body,
raw = u'%s' % message.message().as_string()
)
for attachment in message.attachments:
if isinstance(attachment, tuple):
filename, content, mimetype = attachment
elif isinstance(attachment, MIMEBase):
filename = attachment.get_filename()
content = attachment.get_payload(decode=True)
mimetype = None
else:
continue
Attachment.objects.create(
email=email,
filename=filename,
content=content,
mimetype=mimetype
)
|
413bebe630c29764dcbf17b114662427edfdac3c | pydot/errors.py | pydot/errors.py | class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
try:
self.err_code = json_response['@attributes']['err_code']
self.message = str(json_response['err'])
except KeyError:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
| class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
self.err_code = json_response.get('@attributes').get('err_code')
self.message = str(json_response.get('err'))
if self.err_code is None:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
| Refactor error data extraction from JSON | Refactor error data extraction from JSON
| Python | mit | joshgeller/PyPardot | class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
- try:
- self.err_code = json_response['@attributes']['err_code']
+ self.err_code = json_response.get('@attributes').get('err_code')
- self.message = str(json_response['err'])
+ self.message = str(json_response.get('err'))
- except KeyError:
+ if self.err_code is None:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
| Refactor error data extraction from JSON | ## Code Before:
class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
try:
self.err_code = json_response['@attributes']['err_code']
self.message = str(json_response['err'])
except KeyError:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
## Instruction:
Refactor error data extraction from JSON
## Code After:
class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
self.err_code = json_response.get('@attributes').get('err_code')
self.message = str(json_response.get('err'))
if self.err_code is None:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
|
13e4a0ef064460ffa90bc150dc04b9a1fff26a1c | blanc_basic_news/news/templatetags/news_tags.py | blanc_basic_news/news/templatetags/news_tags.py | from django import template
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
| from django import template
from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
@register.assignment_tag
def get_latest_news(count):
return Post.objects.select_related().filter(
published=True, date__lte=timezone.now())[:count]
| Add a template tag to get the latest news posts. | Add a template tag to get the latest news posts.
| Python | bsd-3-clause | blancltd/blanc-basic-news | from django import template
+ from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
+
+ @register.assignment_tag
+ def get_latest_news(count):
+ return Post.objects.select_related().filter(
+ published=True, date__lte=timezone.now())[:count]
+ | Add a template tag to get the latest news posts. | ## Code Before:
from django import template
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
## Instruction:
Add a template tag to get the latest news posts.
## Code After:
from django import template
from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
@register.assignment_tag
def get_latest_news(count):
return Post.objects.select_related().filter(
published=True, date__lte=timezone.now())[:count]
|
649f2aa5a23541a4c57372eeb34a337d84dd0f86 | timed/tests/test_serializers.py | timed/tests/test_serializers.py | from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
pk_key = 'test_nr'
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
| from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
| Remove obsolete pk_key in test | Remove obsolete pk_key in test
| Python | agpl-3.0 | adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend | from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
- pk_key = 'test_nr'
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
| Remove obsolete pk_key in test | ## Code Before:
from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
pk_key = 'test_nr'
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
## Instruction:
Remove obsolete pk_key in test
## Code After:
from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
|
5bc51f525c702cd43d3d7bc3819d179815c41807 | foliant/backends/pre.py | foliant/backends/pre.py | from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._preprocessed_dir_name = f'{self.get_slug()}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
| from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._preprocessed_config = self.config.get('backend_config', {}).get('pre', {})
self._preprocessed_dir_name = f'{self._preprocessed_config.get("slug", self.get_slug())}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
| Allow to override the top-level slug. | Allow to override the top-level slug.
| Python | mit | foliant-docs/foliant | from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ self._preprocessed_config = self.config.get('backend_config', {}).get('pre', {})
+
- self._preprocessed_dir_name = f'{self.get_slug()}.pre'
+ self._preprocessed_dir_name = f'{self._preprocessed_config.get("slug", self.get_slug())}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
| Allow to override the top-level slug. | ## Code Before:
from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._preprocessed_dir_name = f'{self.get_slug()}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
## Instruction:
Allow to override the top-level slug.
## Code After:
from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._preprocessed_config = self.config.get('backend_config', {}).get('pre', {})
self._preprocessed_dir_name = f'{self._preprocessed_config.get("slug", self.get_slug())}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
|
c37e3fe832ef3f584a60783a474b31f9f91e3735 | github_webhook/test_webhook.py | github_webhook/test_webhook.py | """Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------- END-OF-FILE -----------------------------------
| """Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------- END-OF-FILE -----------------------------------
| Fix mock import for Python 3 | Fix mock import for Python 3
| Python | apache-2.0 | fophillips/python-github-webhook | """Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
+ try:
+ from unittest.mock import Mock
+ except ImportError:
- from mock import Mock
+ from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------- END-OF-FILE -----------------------------------
| Fix mock import for Python 3 | ## Code Before:
"""Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------- END-OF-FILE -----------------------------------
## Instruction:
Fix mock import for Python 3
## Code After:
"""Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------- END-OF-FILE -----------------------------------
|
94bcaa24f0dc1c0750023770574e26bb41183c6a | hangupsbot/plugins/namelock.py | hangupsbot/plugins/namelock.py |
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
|
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
"""Rename Hangout"""
yield from bot._client.setchatname(event.conv_id, ' '.join(args))
| Make hangout rename itself after setchatname is called | Make hangout rename itself after setchatname is called
| Python | agpl-3.0 | makiftasova/hangoutsbot,cd334/hangoutsbot,jhonnyam123/hangoutsbot |
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
+ """Rename Hangout"""
+ yield from bot._client.setchatname(event.conv_id, ' '.join(args))
+ | Make hangout rename itself after setchatname is called | ## Code Before:
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
## Instruction:
Make hangout rename itself after setchatname is called
## Code After:
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
"""Rename Hangout"""
yield from bot._client.setchatname(event.conv_id, ' '.join(args))
|
89b7b7f7fe1ec50f1d0bdfba7581f76326efe717 | dacapo_analyzer.py | dacapo_analyzer.py | import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| Use only msecs of dacapo output. | [client] Use only msecs of dacapo output.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy | import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
- WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
+ WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| Use only msecs of dacapo output. | ## Code Before:
import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
## Instruction:
Use only msecs of dacapo output.
## Code After:
import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
|
f5cc0d9327f35d818b10e200404c849a5527aa50 | indra/databases/hgnc_client.py | indra/databases/hgnc_client.py | import urllib2
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
| import urllib2
from functools32 import lru_cache
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
@lru_cache(maxsize=1000)
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
| Add caching to HGNC client | Add caching to HGNC client
| Python | bsd-2-clause | johnbachman/belpy,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,jmuhlich/indra,jmuhlich/indra,sorgerlab/belpy,jmuhlich/indra | import urllib2
+ from functools32 import lru_cache
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
+ @lru_cache(maxsize=1000)
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
| Add caching to HGNC client | ## Code Before:
import urllib2
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
## Instruction:
Add caching to HGNC client
## Code After:
import urllib2
from functools32 import lru_cache
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
@lru_cache(maxsize=1000)
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
|
87cfac55b14083fdb8e346b9db1a95bb0f63881a | connect/config/factories.py | connect/config/factories.py | import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png')
| import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
| Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency | Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
| Python | bsd-3-clause | nlhkabu/connect,f3r3nc/connect,f3r3nc/connect,f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect,nlhkabu/connect | import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
+ logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
- email_header = factory.django.ImageField(filename='my_image.png')
+ email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
| Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency | ## Code Before:
import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png')
## Instruction:
Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
## Code After:
import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
|
b3413818bf651c13cef047132813fb26a185cd33 | indra/tests/test_reading_files.py | indra/tests/test_reading_files.py | from os import path
from indra.tools.reading.read_files import read_files, get_readers
from nose.plugins.attrib import attr
@attr('slow', 'nonpublic')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
readers = get_readers()
outputs = read_files(example_files, readers)
N_out = len(outputs)
N_exp = 2*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
| from os import path
from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
from indra.tools.reading.readers import EmptyReader
@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
reader_classes = get_reader_classes()
readers = []
for rc in reader_classes:
readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
| Fix the reading files test. | Fix the reading files test.
| Python | bsd-2-clause | johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy | from os import path
- from indra.tools.reading.read_files import read_files, get_readers
+ from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
+ from indra.tools.reading.readers import EmptyReader
+
- @attr('slow', 'nonpublic')
+ @attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
- readers = get_readers()
+ reader_classes = get_reader_classes()
+ readers = []
+ for rc in reader_classes:
+ readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
+ proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
- N_exp = 2*len(example_files)
+ N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
| Fix the reading files test. | ## Code Before:
from os import path
from indra.tools.reading.read_files import read_files, get_readers
from nose.plugins.attrib import attr
@attr('slow', 'nonpublic')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
readers = get_readers()
outputs = read_files(example_files, readers)
N_out = len(outputs)
N_exp = 2*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
## Instruction:
Fix the reading files test.
## Code After:
from os import path
from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
from indra.tools.reading.readers import EmptyReader
@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
reader_classes = get_reader_classes()
readers = []
for rc in reader_classes:
readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
|
fd951edbef26dcab2a4b89036811520b22e77fcf | marry-fuck-kill/main.py | marry-fuck-kill/main.py | from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
# TODO(mjkelly): Clean up these handlers.
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Remove TODO -- handlers have been cleaned up. | Remove TODO -- handlers have been cleaned up.
| Python | apache-2.0 | hjfreyer/marry-fuck-kill,hjfreyer/marry-fuck-kill | from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
- # TODO(mjkelly): Clean up these handlers.
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Remove TODO -- handlers have been cleaned up. | ## Code Before:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
# TODO(mjkelly): Clean up these handlers.
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
## Instruction:
Remove TODO -- handlers have been cleaned up.
## Code After:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
|
366937921cfb13fd83fb5964d0373be48e3c8564 | cmsplugin_plain_text/models.py | cmsplugin_plain_text/models.py | from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
| from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
def __str__(self):
return self.body
| Add `__str__` method to support Python 3 | Add `__str__` method to support Python 3
| Python | bsd-3-clause | chschuermann/cmsplugin-plain-text,chschuermann/cmsplugin-plain-text | from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
+ def __str__(self):
+ return self.body
+ | Add `__str__` method to support Python 3 | ## Code Before:
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
## Instruction:
Add `__str__` method to support Python 3
## Code After:
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
def __str__(self):
return self.body
|
08c2f9fe24b6ce7697bf725e70855e8d6861c370 | pandas/__init__.py | pandas/__init__.py |
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from geopandas_data import GeopandasDataFrame
from geopandas_reader import GeopandasReader
from geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from xray_data import XrayDataset
__all__ += ('XrayDataset',)
|
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from gaia.pandas.pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from gaia.pandas.geopandas_data import GeopandasDataFrame
from gaia.pandas.geopandas_reader import GeopandasReader
from gaia.pandas.geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from gaia.pandas.xray_data import XrayDataset
__all__ += ('XrayDataset',)
| Use only absolute imports for python 3 | Use only absolute imports for python 3
| Python | apache-2.0 | Kitware/romanesco,Kitware/romanesco,girder/girder_worker,girder/girder_worker,girder/girder_worker,Kitware/romanesco,Kitware/romanesco |
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
- from pandas_data import PandasDataFrame
+ from gaia.pandas.pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
- from geopandas_data import GeopandasDataFrame
+ from gaia.pandas.geopandas_data import GeopandasDataFrame
- from geopandas_reader import GeopandasReader
+ from gaia.pandas.geopandas_reader import GeopandasReader
- from geopandas_plot import GeopandasPlot
+ from gaia.pandas.geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
- from xray_data import XrayDataset
+ from gaia.pandas.xray_data import XrayDataset
__all__ += ('XrayDataset',)
| Use only absolute imports for python 3 | ## Code Before:
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from geopandas_data import GeopandasDataFrame
from geopandas_reader import GeopandasReader
from geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from xray_data import XrayDataset
__all__ += ('XrayDataset',)
## Instruction:
Use only absolute imports for python 3
## Code After:
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from gaia.pandas.pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from gaia.pandas.geopandas_data import GeopandasDataFrame
from gaia.pandas.geopandas_reader import GeopandasReader
from gaia.pandas.geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from gaia.pandas.xray_data import XrayDataset
__all__ += ('XrayDataset',)
|
08247c2d4cb3cf1879b568697d7888728ebb1c3b | parse_rest/role.py | parse_rest/role.py |
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
Role.Query = QueryManager(Role)
|
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
def removeRelation(self, key, className, objectsId):
self.manageRelation('RemoveRelation', key, className, objectsId)
def addRelation(self, key, className, objectsId):
self.manageRelation('AddRelation', key, className, objectsId)
def manageRelation(self, action, key, className, objectsId):
objects = [{
"__type": "Pointer",
"className": className,
"objectId": objectId
} for objectId in objectsId]
payload = {
key: {
"__op": action,
"objects": objects
}
}
self.__class__.PUT(self._absolute_url, **payload)
self.__dict__[key] = ''
Role.Query = QueryManager(Role)
| Handle adding and removing relations from Roles. | Handle adding and removing relations from Roles.
This adds addRelation and removeRelation capabilities to Role, making it possible to add users to the users column and roles to the roles column in a Role object, for example. This prevents the error of Role not having the attribute addRelation or removeRelation when trying to add users or roles to a Role, which is critical for Role functionality. | Python | mit | alacroix/ParsePy,milesrichardson/ParsePy,milesrichardson/ParsePy,alacroix/ParsePy |
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
+
+ def removeRelation(self, key, className, objectsId):
+ self.manageRelation('RemoveRelation', key, className, objectsId)
+
+ def addRelation(self, key, className, objectsId):
+ self.manageRelation('AddRelation', key, className, objectsId)
+
+ def manageRelation(self, action, key, className, objectsId):
+ objects = [{
+ "__type": "Pointer",
+ "className": className,
+ "objectId": objectId
+ } for objectId in objectsId]
+
+ payload = {
+ key: {
+ "__op": action,
+ "objects": objects
+ }
+ }
+ self.__class__.PUT(self._absolute_url, **payload)
+ self.__dict__[key] = ''
Role.Query = QueryManager(Role)
| Handle adding and removing relations from Roles. | ## Code Before:
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
Role.Query = QueryManager(Role)
## Instruction:
Handle adding and removing relations from Roles.
## Code After:
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
def removeRelation(self, key, className, objectsId):
self.manageRelation('RemoveRelation', key, className, objectsId)
def addRelation(self, key, className, objectsId):
self.manageRelation('AddRelation', key, className, objectsId)
def manageRelation(self, action, key, className, objectsId):
objects = [{
"__type": "Pointer",
"className": className,
"objectId": objectId
} for objectId in objectsId]
payload = {
key: {
"__op": action,
"objects": objects
}
}
self.__class__.PUT(self._absolute_url, **payload)
self.__dict__[key] = ''
Role.Query = QueryManager(Role)
|
02d67008d0f0bdc205ca9168384c4a951c106a28 | nintendo/common/transport.py | nintendo/common/transport.py |
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
|
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
def bind(self, addr=("", 0)): self.s.bind(addr)
def sendto(self, data, addr): self.s.sendto(data, addr)
def recvfrom(self, num):
try:
return self.s.recvfrom(num)
except BlockingIOError:
return None, None
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
| Add a few functions to Socket class | Add a few functions to Socket class
| Python | mit | Kinnay/NintendoClients |
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
+ def bind(self, addr=("", 0)): self.s.bind(addr)
+ def sendto(self, data, addr): self.s.sendto(data, addr)
+ def recvfrom(self, num):
+ try:
+ return self.s.recvfrom(num)
+ except BlockingIOError:
+ return None, None
+
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
| Add a few functions to Socket class | ## Code Before:
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
## Instruction:
Add a few functions to Socket class
## Code After:
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
def bind(self, addr=("", 0)): self.s.bind(addr)
def sendto(self, data, addr): self.s.sendto(data, addr)
def recvfrom(self, num):
try:
return self.s.recvfrom(num)
except BlockingIOError:
return None, None
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
|
f4c56937caacb4709847d67752f4ff3cba4568f6 | tests/test_it.py | tests/test_it.py | import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
skip_in_ci,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
@skip_in_ci
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
deck2pdf.main([test_slide_path, ])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
| import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
deck2pdf.main([test_slide_path, '-c', 'stub'])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
| Remove decorator 'skip_in_ci' from test_files | Remove decorator 'skip_in_ci' from test_files
Because implement stub of capture engine, 'Output slides pdf' test can run in CircleCI
| Python | mit | attakei/deck2pdf-python,attakei/deck2pdf-python,attakei/slide2pdf,attakei/deck2pdf,attakei/slide2pdf,attakei/deck2pdf | import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
- skip_in_ci,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
- @skip_in_ci
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
- deck2pdf.main([test_slide_path, ])
+ deck2pdf.main([test_slide_path, '-c', 'stub'])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
| Remove decorator 'skip_in_ci' from test_files | ## Code Before:
import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
skip_in_ci,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
@skip_in_ci
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
deck2pdf.main([test_slide_path, ])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
## Instruction:
Remove decorator 'skip_in_ci' from test_files
## Code After:
import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
deck2pdf.main([test_slide_path, '-c', 'stub'])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
|
d5b231fbc5dd32ded78e4499a49872487533cda4 | tests/test_main.py | tests/test_main.py | from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('gh:audreyr/cookiecutter-pypackage') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
| from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
def test_expand_abbreviations():
template = 'gh:audreyr/cookiecutter-pypackage'
# This is not a valid repo url just yet!
# First `main.expand_abbreviations` needs to translate it
assert is_repo_url(template) is False
expanded_template = expand_abbreviations(template, {})
assert is_repo_url(expanded_template) is True
| Implement a test specifically for abbreviations | Implement a test specifically for abbreviations
| Python | bsd-3-clause | willingc/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,michaeljoseph/cookiecutter,pjbull/cookiecutter,cguardia/cookiecutter,terryjbates/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecutter,cguardia/cookiecutter,willingc/cookiecutter,ramiroluz/cookiecutter,audreyr/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter | - from cookiecutter.main import is_repo_url
+ from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
- assert is_repo_url('gh:audreyr/cookiecutter-pypackage') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
+
+ def test_expand_abbreviations():
+ template = 'gh:audreyr/cookiecutter-pypackage'
+
+ # This is not a valid repo url just yet!
+ # First `main.expand_abbreviations` needs to translate it
+ assert is_repo_url(template) is False
+
+ expanded_template = expand_abbreviations(template, {})
+ assert is_repo_url(expanded_template) is True
+ | Implement a test specifically for abbreviations | ## Code Before:
from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('gh:audreyr/cookiecutter-pypackage') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
## Instruction:
Implement a test specifically for abbreviations
## Code After:
from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
def test_expand_abbreviations():
template = 'gh:audreyr/cookiecutter-pypackage'
# This is not a valid repo url just yet!
# First `main.expand_abbreviations` needs to translate it
assert is_repo_url(template) is False
expanded_template = expand_abbreviations(template, {})
assert is_repo_url(expanded_template) is True
|
1028afcdc1e8e1027b10fe5254f5fe5b9499eddd | tests/test_void.py | tests/test_void.py |
import RDF
from glharvest import util
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
model = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
|
import RDF
from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
| Fix imports for void tests | Fix imports for void tests
| Python | apache-2.0 | ec-geolink/glharvest,ec-geolink/glharvest,ec-geolink/glharvest |
import RDF
- from glharvest import util
+ from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
- model = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
+ m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
| Fix imports for void tests | ## Code Before:
import RDF
from glharvest import util
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
model = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
## Instruction:
Fix imports for void tests
## Code After:
import RDF
from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
|
43fd422599972f9385c9f3f9bc5a9a2e5947e0ea | web/webhooks.py | web/webhooks.py | from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
| import hashlib
import hmac
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
from web import jucybot
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def verify_signature(request, repo):
signature = request.META.get('HTTP_X_HUB_SIGNATURE')
if not signature:
return False
repo_secret = jucybot.getSecretForRepo(repo)
h = hmac.new(repo_secret, request.body, digestmod=hashlib.sha1)
reference = 'sha1=%s' % h.hexdigest()
return reference == signature
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
if not verify_signature(request, repo):
return HttpResponseNotFound('X-Hub-Signature did not verify')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
| Check HMAC digests in webhook notifications before handling them. | Check HMAC digests in webhook notifications before handling them.
Bump #1
| Python | apache-2.0 | Jucyio/Jucy,Jucyio/Jucy,Jucyio/Jucy | + import hashlib
+ import hmac
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
-
+ from web import jucybot
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
+ def verify_signature(request, repo):
+ signature = request.META.get('HTTP_X_HUB_SIGNATURE')
+ if not signature:
+ return False
+ repo_secret = jucybot.getSecretForRepo(repo)
+ h = hmac.new(repo_secret, request.body, digestmod=hashlib.sha1)
+ reference = 'sha1=%s' % h.hexdigest()
+ return reference == signature
+
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
+ if not verify_signature(request, repo):
+ return HttpResponseNotFound('X-Hub-Signature did not verify')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
| Check HMAC digests in webhook notifications before handling them. | ## Code Before:
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
## Instruction:
Check HMAC digests in webhook notifications before handling them.
## Code After:
import hashlib
import hmac
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
from web import jucybot
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def verify_signature(request, repo):
signature = request.META.get('HTTP_X_HUB_SIGNATURE')
if not signature:
return False
repo_secret = jucybot.getSecretForRepo(repo)
h = hmac.new(repo_secret, request.body, digestmod=hashlib.sha1)
reference = 'sha1=%s' % h.hexdigest()
return reference == signature
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
if not verify_signature(request, repo):
return HttpResponseNotFound('X-Hub-Signature did not verify')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
|
d2c368995e33b375404e3c01f79fdc5a14a48282 | polyaxon/libs/repos/utils.py | polyaxon/libs/repos/utils.py | from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_project_code_reference(project, commit=None):
if not project.has_code:
return None
repo = project.repo
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def get_code_reference(instance, commit):
return get_project_code_reference(instance.project, commit=commit)
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
if not commit and instance.specification and instance.specification.build:
commit = instance.specification.build.commit
code_reference = get_code_reference(instance=instance, commit=commit)
if code_reference:
instance.code_reference = code_reference
return instance
| from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_code_reference(instance, commit=None, external_repo=None):
project = instance.project
repo = project.repo if project.has_code else external_repo
if not repo:
return None
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
build = instance.specification.build if instance.specification else None
if not commit and build:
commit = build.commit
external_repo = build.git if build and build.git else None
code_reference = get_code_reference(instance=instance,
commit=commit,
external_repo=external_repo)
if code_reference:
instance.code_reference = code_reference
return instance
| Extend code references with external repos | Extend code references with external repos
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
- def get_project_code_reference(project, commit=None):
- if not project.has_code:
+ def get_code_reference(instance, commit=None, external_repo=None):
+ project = instance.project
+
+ repo = project.repo if project.has_code else external_repo
+
+ if not repo:
return None
-
- repo = project.repo
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
- def get_code_reference(instance, commit):
- return get_project_code_reference(instance.project, commit=commit)
-
-
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
- if not commit and instance.specification and instance.specification.build:
- commit = instance.specification.build.commit
+ build = instance.specification.build if instance.specification else None
+ if not commit and build:
+ commit = build.commit
+ external_repo = build.git if build and build.git else None
- code_reference = get_code_reference(instance=instance, commit=commit)
+ code_reference = get_code_reference(instance=instance,
+ commit=commit,
+ external_repo=external_repo)
if code_reference:
instance.code_reference = code_reference
return instance
| Extend code references with external repos | ## Code Before:
from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_project_code_reference(project, commit=None):
if not project.has_code:
return None
repo = project.repo
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def get_code_reference(instance, commit):
return get_project_code_reference(instance.project, commit=commit)
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
if not commit and instance.specification and instance.specification.build:
commit = instance.specification.build.commit
code_reference = get_code_reference(instance=instance, commit=commit)
if code_reference:
instance.code_reference = code_reference
return instance
## Instruction:
Extend code references with external repos
## Code After:
from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_code_reference(instance, commit=None, external_repo=None):
project = instance.project
repo = project.repo if project.has_code else external_repo
if not repo:
return None
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
build = instance.specification.build if instance.specification else None
if not commit and build:
commit = build.commit
external_repo = build.git if build and build.git else None
code_reference = get_code_reference(instance=instance,
commit=commit,
external_repo=external_repo)
if code_reference:
instance.code_reference = code_reference
return instance
|
db93242b97eb8733192d38c4b0af0377759fd647 | pysal/model/access/__init__.py | pysal/model/access/__init__.py | from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access_log_stream
from access import access
| from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access
| Update import for access changes | [BUG] Update import for access changes
| Python | bsd-3-clause | pysal/pysal,weikang9009/pysal,lanselin/pysal,sjsrey/pysal | from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
- from access import access_log_stream
from access import access
| Update import for access changes | ## Code Before:
from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access_log_stream
from access import access
## Instruction:
Update import for access changes
## Code After:
from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access
|
724335a9719174d3aeb745ed2d4c161507a08bd3 | pysparkling/fileio/textfile.py | pysparkling/fileio/textfile.py | from __future__ import absolute_import, unicode_literals
import logging
from io import StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
stream = self.codec.compress(stream.read().encode(encoding))
self.fs.dump(stream)
return self
| from __future__ import absolute_import, unicode_literals
import logging
from io import BytesIO, StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
stream = self.codec.compress(
BytesIO(stream.read().encode(encoding))
)
self.fs.dump(stream)
return self
| Add fileio.TextFile and use it when reading and writing text files in RDD and Context. | Add fileio.TextFile and use it when reading and writing text files in RDD and Context.
| Python | mit | giserh/pysparkling | from __future__ import absolute_import, unicode_literals
import logging
- from io import StringIO
+ from io import BytesIO, StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
- stream = self.codec.compress(stream.read().encode(encoding))
+ stream = self.codec.compress(
+ BytesIO(stream.read().encode(encoding))
+ )
self.fs.dump(stream)
return self
| Add fileio.TextFile and use it when reading and writing text files in RDD and Context. | ## Code Before:
from __future__ import absolute_import, unicode_literals
import logging
from io import StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
stream = self.codec.compress(stream.read().encode(encoding))
self.fs.dump(stream)
return self
## Instruction:
Add fileio.TextFile and use it when reading and writing text files in RDD and Context.
## Code After:
from __future__ import absolute_import, unicode_literals
import logging
from io import BytesIO, StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
stream = self.codec.compress(
BytesIO(stream.read().encode(encoding))
)
self.fs.dump(stream)
return self
|
1b33866dd7f140efa035dfd32e0a912dfcf60f35 | utils/kvtable.py | utils/kvtable.py | '''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
self.setting = Query()
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
if self.table.contains(self.setting.key == key):
self.table.update({'value': value}, self.setting.key == key)
else:
self.table.insert({'key': key, 'value': value})
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
| '''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
setting = Query()
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
self.table.upsert({
'key': key,
'value': value
}, self.setting.key == key)
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
| Use upsert to reduce chance of duplicates | Use upsert to reduce chance of duplicates
| Python | mit | randomic/antinub-gregbot | '''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
+ setting = Query()
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
- self.setting = Query()
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
- if self.table.contains(self.setting.key == key):
- self.table.update({'value': value}, self.setting.key == key)
- else:
- self.table.insert({'key': key, 'value': value})
+ self.table.upsert({
+ 'key': key,
+ 'value': value
+ }, self.setting.key == key)
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
| Use upsert to reduce chance of duplicates | ## Code Before:
'''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
self.setting = Query()
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
if self.table.contains(self.setting.key == key):
self.table.update({'value': value}, self.setting.key == key)
else:
self.table.insert({'key': key, 'value': value})
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
## Instruction:
Use upsert to reduce chance of duplicates
## Code After:
'''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
setting = Query()
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
self.table.upsert({
'key': key,
'value': value
}, self.setting.key == key)
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
|
02ef2f1cb4e1e0bf3696ea68b73d0d9c3b9c8657 | events/views.py | events/views.py | from datetime import date
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
return render_to_response('events/event_archive_month.html', {'month': month})
| from datetime import date, timedelta
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
previous = month - timedelta(days=15)
next = month + timedelta(days=45)
return render_to_response('events/event_archive_month.html', {
'month': month,
'previous_month': previous,
'next_month': next,
})
| Add links to previous and next month | Add links to previous and next month
| Python | agpl-3.0 | vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,mlhamel/agendadulibre | - from datetime import date
+ from datetime import date, timedelta
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
+ previous = month - timedelta(days=15)
+ next = month + timedelta(days=45)
- return render_to_response('events/event_archive_month.html', {'month': month})
+ return render_to_response('events/event_archive_month.html', {
+ 'month': month,
+ 'previous_month': previous,
+ 'next_month': next,
+ })
| Add links to previous and next month | ## Code Before:
from datetime import date
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
return render_to_response('events/event_archive_month.html', {'month': month})
## Instruction:
Add links to previous and next month
## Code After:
from datetime import date, timedelta
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
previous = month - timedelta(days=15)
next = month + timedelta(days=45)
return render_to_response('events/event_archive_month.html', {
'month': month,
'previous_month': previous,
'next_month': next,
})
|
a18f948a6b11522425aace5a591b5f622a5534d3 | payments/forms.py | payments/forms.py | from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
| from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
# pylint: disable=R0924
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
| Disable R0924 check on PlanForm | Disable R0924 check on PlanForm
This check fails on Django 1.4 but not Django 1.5
| Python | mit | crehana/django-stripe-payments,aibon/django-stripe-payments,jawed123/django-stripe-payments,aibon/django-stripe-payments,alexhayes/django-stripe-payments,adi-li/django-stripe-payments,alexhayes/django-stripe-payments,adi-li/django-stripe-payments,ZeevG/django-stripe-payments,jawed123/django-stripe-payments,grue/django-stripe-payments,boxysean/django-stripe-payments,ZeevG/django-stripe-payments,grue/django-stripe-payments,jamespacileo/django-stripe-payments,wahuneke/django-stripe-payments,jamespacileo/django-stripe-payments,wahuneke/django-stripe-payments,crehana/django-stripe-payments,pinax/django-stripe-payments,boxysean/django-stripe-payments,wahuneke/django-stripe-payments | from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
-
+ # pylint: disable=R0924
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
| Disable R0924 check on PlanForm | ## Code Before:
from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
## Instruction:
Disable R0924 check on PlanForm
## Code After:
from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
# pylint: disable=R0924
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
|
3ede075c812b116629c5f514596669b16c4784df | fulltext/backends/__json.py | fulltext/backends/__json.py | import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types):
text.write(obj)
text.write(u' ')
elif isinstance(obj, integer_types):
text.write(str(obj))
text.write(u' ')
def _get_file(f, **kwargs):
text, obj = StringIO(), json.loads(f.read().decode('utf8'))
_to_text(text, obj)
return text.getvalue()
| import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types + integer_types):
text.write(u'%s ' % obj)
else:
raise ValueError('Unrecognized type: %s' % obj.__class__)
def _get_file(f, **kwargs):
text, data = StringIO(), f.read()
obj = json.loads(data.decode('utf8'))
_to_text(text, obj)
return text.getvalue()
| Use format string. Readability. ValueError. | Use format string. Readability. ValueError.
| Python | mit | btimby/fulltext,btimby/fulltext | import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
- elif isinstance(obj, string_types):
+ elif isinstance(obj, string_types + integer_types):
- text.write(obj)
- text.write(u' ')
+ text.write(u'%s ' % obj)
+ else:
+ raise ValueError('Unrecognized type: %s' % obj.__class__)
- elif isinstance(obj, integer_types):
- text.write(str(obj))
- text.write(u' ')
def _get_file(f, **kwargs):
- text, obj = StringIO(), json.loads(f.read().decode('utf8'))
+ text, data = StringIO(), f.read()
+ obj = json.loads(data.decode('utf8'))
_to_text(text, obj)
return text.getvalue()
| Use format string. Readability. ValueError. | ## Code Before:
import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types):
text.write(obj)
text.write(u' ')
elif isinstance(obj, integer_types):
text.write(str(obj))
text.write(u' ')
def _get_file(f, **kwargs):
text, obj = StringIO(), json.loads(f.read().decode('utf8'))
_to_text(text, obj)
return text.getvalue()
## Instruction:
Use format string. Readability. ValueError.
## Code After:
import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types + integer_types):
text.write(u'%s ' % obj)
else:
raise ValueError('Unrecognized type: %s' % obj.__class__)
def _get_file(f, **kwargs):
text, data = StringIO(), f.read()
obj = json.loads(data.decode('utf8'))
_to_text(text, obj)
return text.getvalue()
|
6e583085ac056b7df2b29a94cd6743493c151684 | subjectivity_clues/clues.py | subjectivity_clues/clues.py | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
if __name__ == '__main__':
c = Clues()
| import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
PRIORPOLARITY = {
'positive': 1,
'negative': -1,
'both': 0,
'neutral': 0
}
TYPE = {
'strongsubj': 2,
'weaksubj': 1
}
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
def calculate(self, sentence):
related_words = 0
total_subjectivity = 0
total_priorpolarity = 0
for w in sentence.split(' '):
if w not in self.lexicons.keys():
continue
related_words += 1
total_subjectivity += self.TYPE[self.lexicons[w]['type']]
total_priorpolarity += self.PRIORPOLARITY[self.lexicons[w]['priorpolarity']]
return {
'sentence': sentence,
'related_words': related_words,
'total_subjectivity': total_subjectivity,
'total_priorpolarity': total_priorpolarity
}
if __name__ == '__main__':
c = Clues()
| Add calculation to the lexicon | Add calculation to the lexicon
| Python | apache-2.0 | chuajiesheng/twitter-sentiment-analysis | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
+
+ PRIORPOLARITY = {
+ 'positive': 1,
+ 'negative': -1,
+ 'both': 0,
+ 'neutral': 0
+ }
+
+ TYPE = {
+ 'strongsubj': 2,
+ 'weaksubj': 1
+ }
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
+ def calculate(self, sentence):
+ related_words = 0
+ total_subjectivity = 0
+ total_priorpolarity = 0
+
+ for w in sentence.split(' '):
+ if w not in self.lexicons.keys():
+ continue
+
+ related_words += 1
+ total_subjectivity += self.TYPE[self.lexicons[w]['type']]
+ total_priorpolarity += self.PRIORPOLARITY[self.lexicons[w]['priorpolarity']]
+
+ return {
+ 'sentence': sentence,
+ 'related_words': related_words,
+ 'total_subjectivity': total_subjectivity,
+ 'total_priorpolarity': total_priorpolarity
+ }
+
if __name__ == '__main__':
c = Clues()
| Add calculation to the lexicon | ## Code Before:
import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
if __name__ == '__main__':
c = Clues()
## Instruction:
Add calculation to the lexicon
## Code After:
import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
PRIORPOLARITY = {
'positive': 1,
'negative': -1,
'both': 0,
'neutral': 0
}
TYPE = {
'strongsubj': 2,
'weaksubj': 1
}
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
def calculate(self, sentence):
related_words = 0
total_subjectivity = 0
total_priorpolarity = 0
for w in sentence.split(' '):
if w not in self.lexicons.keys():
continue
related_words += 1
total_subjectivity += self.TYPE[self.lexicons[w]['type']]
total_priorpolarity += self.PRIORPOLARITY[self.lexicons[w]['priorpolarity']]
return {
'sentence': sentence,
'related_words': related_words,
'total_subjectivity': total_subjectivity,
'total_priorpolarity': total_priorpolarity
}
if __name__ == '__main__':
c = Clues()
|
dcc5c7be6f8463f41e1d1697bdba7fd576382259 | master/rc_force.py | master/rc_force.py | rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
| rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
| Add ppc64le tarball rc force builder | Add ppc64le tarball rc force builder
| Python | mit | staticfloat/julia-buildbot,staticfloat/julia-buildbot | rc_scheduler = ForceScheduler(
name="rc build",
- builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm"],
+ builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
| Add ppc64le tarball rc force builder | ## Code Before:
rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
## Instruction:
Add ppc64le tarball rc force builder
## Code After:
rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
|
f4be8fd80b1aad9babdfbc56dec331af635f5554 | migrations/versions/0165_another_letter_org.py | migrations/versions/0165_another_letter_org.py |
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
|
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
('503', 'East Riding of Yorkshire Council'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
| Add East Riding of Yorkshire Council to migration | Add East Riding of Yorkshire Council to migration
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
+ ('503', 'East Riding of Yorkshire Council'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
| Add East Riding of Yorkshire Council to migration | ## Code Before:
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
## Instruction:
Add East Riding of Yorkshire Council to migration
## Code After:
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
('503', 'East Riding of Yorkshire Council'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
|
dc0dfd4a763dceef655d62e8364b92a8073b7751 | chrome/chromehost.py | chrome/chromehost.py | import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_name = '/tmp/cachebrowser.sock'
sock.connect(socket_name)
message = read_from_chrome()
sock.send(message)
sock.send('\n')
response = ''
while True:
read = sock.recv(1024)
if len(read) == 0:
break
response += read
# response = sock.recv(1024)
send_to_chrome(response)
| import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# socket_name = '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))
message = read_from_chrome()
sock.send(message)
sock.send('\n')
# response = ''
# while True:
# read = sock.recv(1024)
# if len(read) == 0:
# break
# response += read
response = sock.recv(1024)
send_to_chrome(response)
# send_to_chrome("{}")
| Change chromhost to use normal sockets | Change chromhost to use normal sockets
| Python | mit | CacheBrowser/cachebrowser,NewBie1993/cachebrowser | import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ # sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- socket_name = '/tmp/cachebrowser.sock'
+ # socket_name = '/tmp/cachebrowser.sock'
- sock.connect(socket_name)
+ # sock.connect(socket_name)
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.connect(('127.0.0.1', 4242))
message = read_from_chrome()
sock.send(message)
sock.send('\n')
- response = ''
+ # response = ''
- while True:
+ # while True:
- read = sock.recv(1024)
+ # read = sock.recv(1024)
- if len(read) == 0:
+ # if len(read) == 0:
- break
+ # break
- response += read
+ # response += read
- # response = sock.recv(1024)
+ response = sock.recv(1024)
send_to_chrome(response)
+ # send_to_chrome("{}")
| Change chromhost to use normal sockets | ## Code Before:
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_name = '/tmp/cachebrowser.sock'
sock.connect(socket_name)
message = read_from_chrome()
sock.send(message)
sock.send('\n')
response = ''
while True:
read = sock.recv(1024)
if len(read) == 0:
break
response += read
# response = sock.recv(1024)
send_to_chrome(response)
## Instruction:
Change chromhost to use normal sockets
## Code After:
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# socket_name = '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))
message = read_from_chrome()
sock.send(message)
sock.send('\n')
# response = ''
# while True:
# read = sock.recv(1024)
# if len(read) == 0:
# break
# response += read
response = sock.recv(1024)
send_to_chrome(response)
# send_to_chrome("{}")
|
78ca616d611a6c9b8364cf25a21affd80e261ff8 | cutplanner/planner.py | cutplanner/planner.py | import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed.reverse
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
| import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = [Piece(i, s) for i, s in enumerate(needed)]
self.pieces_needed.reverse()
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
| Set up list of needed pieces on init | Set up list of needed pieces on init
| Python | mit | alanc10n/py-cutplanner | import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
+ self.pieces_needed = [Piece(i, s) for i, s in enumerate(needed)]
- self.pieces_needed = needed.reverse
+ self.pieces_needed.reverse()
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
| Set up list of needed pieces on init | ## Code Before:
import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed.reverse
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
## Instruction:
Set up list of needed pieces on init
## Code After:
import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = [Piece(i, s) for i, s in enumerate(needed)]
self.pieces_needed.reverse()
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
|
131f0d3a67bc6ba995d1f45dd8c85594d8d8e79c | tests/run_tests.py | tests/run_tests.py | """Python script to run all tests"""
import pytest
if __name__ == '__main__':
pytest.main()
| """Python script to run all tests"""
import sys
import pytest
if __name__ == '__main__':
sys.exit(pytest.main())
| Allow Jenkins to actually report build failures | Allow Jenkins to actually report build failures
| Python | mit | gatkin/declxml | """Python script to run all tests"""
+ import sys
+
import pytest
+
if __name__ == '__main__':
- pytest.main()
+ sys.exit(pytest.main())
| Allow Jenkins to actually report build failures | ## Code Before:
"""Python script to run all tests"""
import pytest
if __name__ == '__main__':
pytest.main()
## Instruction:
Allow Jenkins to actually report build failures
## Code After:
"""Python script to run all tests"""
import sys
import pytest
if __name__ == '__main__':
sys.exit(pytest.main())
|
2d8ddb4ab59bc7198b637bcc9e51914379ff408b | tests/test_i18n.py | tests/test_i18n.py | import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
humanize.i18n.deactivate()
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
| import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
try:
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
assert humanize.ordinal(5) == "5ый"
finally:
humanize.i18n.deactivate()
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
| Add i18n test for humanize.ordinal | Add i18n test for humanize.ordinal
| Python | mit | jmoiron/humanize,jmoiron/humanize | import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
+ assert humanize.ordinal(5) == "5th"
+ try:
- humanize.i18n.activate("ru_RU")
+ humanize.i18n.activate("ru_RU")
- assert humanize.naturaltime(three_seconds) == "3 секунды назад"
+ assert humanize.naturaltime(three_seconds) == "3 секунды назад"
+ assert humanize.ordinal(5) == "5ый"
+ finally:
+ humanize.i18n.deactivate()
+ assert humanize.naturaltime(three_seconds) == "3 seconds ago"
+ assert humanize.ordinal(5) == "5th"
- humanize.i18n.deactivate()
- assert humanize.naturaltime(three_seconds) == "3 seconds ago"
- | Add i18n test for humanize.ordinal | ## Code Before:
import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
humanize.i18n.deactivate()
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
## Instruction:
Add i18n test for humanize.ordinal
## Code After:
import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
try:
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
assert humanize.ordinal(5) == "5ый"
finally:
humanize.i18n.deactivate()
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
|
fb7754f15a8f0803c5417782e87d6fe153bf6d20 | migrations/versions/201503061726_573faf4ac644_added_end_date_to_full_text_index_events.py | migrations/versions/201503061726_573faf4ac644_added_end_date_to_full_text_index_events.py |
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_column('event_index', 'start_date', nullable=False, schema='events')
op.create_index('ix_start_date', 'event_index', ['start_date'], schema='events')
op.add_column('event_index',
sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'),
schema='events')
op.alter_column('event_index', 'end_date', server_default=None, schema='events')
op.create_index('ix_end_date', 'event_index', ['end_date'], schema='events')
def downgrade():
op.alter_column('event_index', 'start_date', nullable=True, schema='events')
op.drop_index('ix_start_date', table_name='event_index', schema='events')
op.drop_column('event_index', 'end_date', schema='events')
|
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_column('event_index', 'start_date', nullable=False, schema='events')
op.create_index('ix_events_event_index_start_date', 'event_index', ['start_date'], schema='events')
op.add_column('event_index',
sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'),
schema='events')
op.alter_column('event_index', 'end_date', server_default=None, schema='events')
op.create_index('ix_events_event_index_end_date', 'event_index', ['end_date'], schema='events')
def downgrade():
op.alter_column('event_index', 'start_date', nullable=True, schema='events')
op.drop_index('ix_events_event_index_start_date', table_name='event_index', schema='events')
op.drop_column('event_index', 'end_date', schema='events')
| Use index name matching the current naming schema | Use index name matching the current naming schema
| Python | mit | OmeGak/indico,mvidalgarcia/indico,pferreir/indico,indico/indico,DirkHoffmann/indico,indico/indico,mic4ael/indico,ThiefMaster/indico,ThiefMaster/indico,mvidalgarcia/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,indico/indico,OmeGak/indico,DirkHoffmann/indico,mvidalgarcia/indico,DirkHoffmann/indico,mic4ael/indico,ThiefMaster/indico,mic4ael/indico,mvidalgarcia/indico,OmeGak/indico,pferreir/indico,pferreir/indico,pferreir/indico,indico/indico |
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_column('event_index', 'start_date', nullable=False, schema='events')
- op.create_index('ix_start_date', 'event_index', ['start_date'], schema='events')
+ op.create_index('ix_events_event_index_start_date', 'event_index', ['start_date'], schema='events')
op.add_column('event_index',
sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'),
schema='events')
op.alter_column('event_index', 'end_date', server_default=None, schema='events')
- op.create_index('ix_end_date', 'event_index', ['end_date'], schema='events')
+ op.create_index('ix_events_event_index_end_date', 'event_index', ['end_date'], schema='events')
def downgrade():
op.alter_column('event_index', 'start_date', nullable=True, schema='events')
- op.drop_index('ix_start_date', table_name='event_index', schema='events')
+ op.drop_index('ix_events_event_index_start_date', table_name='event_index', schema='events')
-
op.drop_column('event_index', 'end_date', schema='events')
| Use index name matching the current naming schema | ## Code Before:
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_column('event_index', 'start_date', nullable=False, schema='events')
op.create_index('ix_start_date', 'event_index', ['start_date'], schema='events')
op.add_column('event_index',
sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'),
schema='events')
op.alter_column('event_index', 'end_date', server_default=None, schema='events')
op.create_index('ix_end_date', 'event_index', ['end_date'], schema='events')
def downgrade():
op.alter_column('event_index', 'start_date', nullable=True, schema='events')
op.drop_index('ix_start_date', table_name='event_index', schema='events')
op.drop_column('event_index', 'end_date', schema='events')
## Instruction:
Use index name matching the current naming schema
## Code After:
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_column('event_index', 'start_date', nullable=False, schema='events')
op.create_index('ix_events_event_index_start_date', 'event_index', ['start_date'], schema='events')
op.add_column('event_index',
sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'),
schema='events')
op.alter_column('event_index', 'end_date', server_default=None, schema='events')
op.create_index('ix_events_event_index_end_date', 'event_index', ['end_date'], schema='events')
def downgrade():
op.alter_column('event_index', 'start_date', nullable=True, schema='events')
op.drop_index('ix_events_event_index_start_date', table_name='event_index', schema='events')
op.drop_column('event_index', 'end_date', schema='events')
|
029a159fe3f920d59e0168af72177b343daa4256 | phased/__init__.py | phased/__init__.py | from django.conf import settings
def generate_secret_delimiter():
try:
from hashlib import sha1
except ImportError:
from sha import sha as sha1
return sha1(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
| from django.conf import settings
from django.utils.hashcompat import sha_constructor
def generate_secret_delimiter():
return sha_constructor(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
| Make use of Django's hashcompat module. | Make use of Django's hashcompat module. | Python | bsd-3-clause | OmarIthawi/django-phased,mab2k/django-phased,mab2k/django-phased,codysoyland/django-phased,OmarIthawi/django-phased | from django.conf import settings
+ from django.utils.hashcompat import sha_constructor
def generate_secret_delimiter():
- try:
- from hashlib import sha1
- except ImportError:
- from sha import sha as sha1
- return sha1(getattr(settings, 'SECRET_KEY', '')).hexdigest()
+ return sha_constructor(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
| Make use of Django's hashcompat module. | ## Code Before:
from django.conf import settings
def generate_secret_delimiter():
try:
from hashlib import sha1
except ImportError:
from sha import sha as sha1
return sha1(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
## Instruction:
Make use of Django's hashcompat module.
## Code After:
from django.conf import settings
from django.utils.hashcompat import sha_constructor
def generate_secret_delimiter():
return sha_constructor(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
|
39c0dfd7821355c9d2ff2274f4dd6292e959ed87 | pronto/__init__.py | pronto/__init__.py |
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship", "Parser"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
from .parser import Parser
except ImportError:
pass
|
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
except ImportError:
pass
| Remove Parser from __all__ (from pronto import *) | Remove Parser from __all__ (from pronto import *)
| Python | mit | althonos/pronto |
from __future__ import absolute_import
- __all__ = ["Ontology", "Term", "TermList", "Relationship", "Parser"]
+ __all__ = ["Ontology", "Term", "TermList", "Relationship"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
- from .parser import Parser
except ImportError:
pass
| Remove Parser from __all__ (from pronto import *) | ## Code Before:
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship", "Parser"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
from .parser import Parser
except ImportError:
pass
## Instruction:
Remove Parser from __all__ (from pronto import *)
## Code After:
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
except ImportError:
pass
|
176c03e26f46bad73df39c11ea4a190baca6fe54 | apps/authentication/tests.py | apps/authentication/tests.py | from django.core.urlresolvers import reverse
from django.test import TestCase
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
| from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
pipeline_settings = settings.PIPELINE
pipeline_settings['PIPELINE_ENABLED'] = False
with override_settings(PIPELINE_SETTINGS=pipeline_settings):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
| Make test not depend on django-pipeline | Make test not depend on django-pipeline
| Python | mit | microserv/microauth,microserv/microauth,microserv/microauth | + from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
+ from django.test.utils import override_settings
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
+ pipeline_settings = settings.PIPELINE
+ pipeline_settings['PIPELINE_ENABLED'] = False
+ with override_settings(PIPELINE_SETTINGS=pipeline_settings):
- url = reverse('microauth_authentication:index')
+ url = reverse('microauth_authentication:index')
- response = self.client.get(url)
+ response = self.client.get(url)
- self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
+ self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
| Make test not depend on django-pipeline | ## Code Before:
from django.core.urlresolvers import reverse
from django.test import TestCase
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
## Instruction:
Make test not depend on django-pipeline
## Code After:
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
pipeline_settings = settings.PIPELINE
pipeline_settings['PIPELINE_ENABLED'] = False
with override_settings(PIPELINE_SETTINGS=pipeline_settings):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
|