commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
c65a475c38a611cbf55f2dacbe22ccd50597c9ed
tests/test_database/test_sql/test_median.py
tests/test_database/test_sql/test_median.py
import unittest from tkp.db import execute, rollback class testMedian(unittest.TestCase): def setUp(self): try: execute('drop table median_test') except: rollback() execute('create table median_test (i int, f float)') execute('insert into median_test values (1, 1.1)') execute('insert into median_test values (2, 2.1)') execute('insert into median_test values (3, 3.1)') def tearDown(self): rollback() def test_median(self): cursor = execute('select median(i), median(f) from median_test') median_i, median_f = cursor.fetchall()[0] self.assertEqual(median_i, 2) self.assertEqual(median_f, 2.1)
import unittest import tkp from tkp.db import execute, rollback, Database from tkp.testutil import db_subs from numpy import median class testMedian(unittest.TestCase): def setUp(self): self.database = tkp.db.Database() self.dataset = tkp.db.DataSet(database=self.database, data={'description':"Median test" + self._testMethodName}) self.n_images = 5 self.im_params = db_subs.generate_timespaced_dbimages_data(self.n_images) for idx, impar in enumerate(self.im_params): impar['rms_max'] = (idx+1)*1e-4 self.image_ids = [] for img_pars in self.im_params: image,_,_ = db_subs.insert_image_and_simulated_sources( self.dataset,img_pars,[], new_source_sigma_margin=3) self.image_ids.append(image.id) def test_median(self): if Database().engine == 'monetdb': qry = (""" SELECT sys.median(id) as median_id ,sys.median(rms_max) as median_rms_max FROM image WHERE dataset = %(dataset_id)s """) else: qry = (""" SELECT median(id) as median_id ,median(rms_max) as median_rms_max FROM image WHERE dataset = %(dataset_id)s """) cursor = execute(qry, {'dataset_id': self.dataset.id}) results = db_subs.get_db_rows_as_dicts(cursor) # self.assertAlmostEqual(results[0]['median_id'], median(self.image_ids)) self.assertAlmostEqual(results[0]['median_rms_max'], median([p['rms_max'] for p in self.im_params]))
Use MonetDB friendly median query syntax in unit test.
Use MonetDB friendly median query syntax in unit test.
Python
bsd-2-clause
transientskp/tkp,mkuiack/tkp,bartscheers/tkp,mkuiack/tkp,transientskp/tkp,bartscheers/tkp
import unittest + import tkp - from tkp.db import execute, rollback + from tkp.db import execute, rollback, Database - + from tkp.testutil import db_subs + from numpy import median class testMedian(unittest.TestCase): def setUp(self): + self.database = tkp.db.Database() - try: - execute('drop table median_test') - except: - rollback() - execute('create table median_test (i int, f float)') - execute('insert into median_test values (1, 1.1)') - execute('insert into median_test values (2, 2.1)') - execute('insert into median_test values (3, 3.1)') + self.dataset = tkp.db.DataSet(database=self.database, + data={'description':"Median test" + + self._testMethodName}) + self.n_images = 5 - def tearDown(self): - rollback() + self.im_params = db_subs.generate_timespaced_dbimages_data(self.n_images) + for idx, impar in enumerate(self.im_params): + impar['rms_max'] = (idx+1)*1e-4 + + self.image_ids = [] + for img_pars in self.im_params: + image,_,_ = db_subs.insert_image_and_simulated_sources( + self.dataset,img_pars,[], + new_source_sigma_margin=3) + self.image_ids.append(image.id) + def test_median(self): - cursor = execute('select median(i), median(f) from median_test') - median_i, median_f = cursor.fetchall()[0] - self.assertEqual(median_i, 2) - self.assertEqual(median_f, 2.1) + if Database().engine == 'monetdb': + qry = (""" + SELECT sys.median(id) as median_id + ,sys.median(rms_max) as median_rms_max + FROM image + WHERE dataset = %(dataset_id)s + """) + else: + qry = (""" + SELECT median(id) as median_id + ,median(rms_max) as median_rms_max + FROM image + WHERE dataset = %(dataset_id)s + """) + cursor = execute(qry, {'dataset_id': self.dataset.id}) + results = db_subs.get_db_rows_as_dicts(cursor) + # self.assertAlmostEqual(results[0]['median_id'], median(self.image_ids)) + self.assertAlmostEqual(results[0]['median_rms_max'], + median([p['rms_max'] for p in self.im_params])) +
Use MonetDB friendly median query syntax in unit test.
## Code Before: import unittest from tkp.db import execute, rollback class testMedian(unittest.TestCase): def setUp(self): try: execute('drop table median_test') except: rollback() execute('create table median_test (i int, f float)') execute('insert into median_test values (1, 1.1)') execute('insert into median_test values (2, 2.1)') execute('insert into median_test values (3, 3.1)') def tearDown(self): rollback() def test_median(self): cursor = execute('select median(i), median(f) from median_test') median_i, median_f = cursor.fetchall()[0] self.assertEqual(median_i, 2) self.assertEqual(median_f, 2.1) ## Instruction: Use MonetDB friendly median query syntax in unit test. ## Code After: import unittest import tkp from tkp.db import execute, rollback, Database from tkp.testutil import db_subs from numpy import median class testMedian(unittest.TestCase): def setUp(self): self.database = tkp.db.Database() self.dataset = tkp.db.DataSet(database=self.database, data={'description':"Median test" + self._testMethodName}) self.n_images = 5 self.im_params = db_subs.generate_timespaced_dbimages_data(self.n_images) for idx, impar in enumerate(self.im_params): impar['rms_max'] = (idx+1)*1e-4 self.image_ids = [] for img_pars in self.im_params: image,_,_ = db_subs.insert_image_and_simulated_sources( self.dataset,img_pars,[], new_source_sigma_margin=3) self.image_ids.append(image.id) def test_median(self): if Database().engine == 'monetdb': qry = (""" SELECT sys.median(id) as median_id ,sys.median(rms_max) as median_rms_max FROM image WHERE dataset = %(dataset_id)s """) else: qry = (""" SELECT median(id) as median_id ,median(rms_max) as median_rms_max FROM image WHERE dataset = %(dataset_id)s """) cursor = execute(qry, {'dataset_id': self.dataset.id}) results = db_subs.get_db_rows_as_dicts(cursor) # self.assertAlmostEqual(results[0]['median_id'], median(self.image_ids)) self.assertAlmostEqual(results[0]['median_rms_max'], median([p['rms_max'] for p in self.im_params]))
import unittest + import tkp - from tkp.db import execute, rollback + from tkp.db import execute, rollback, Database ? ++++++++++ - + from tkp.testutil import db_subs + from numpy import median class testMedian(unittest.TestCase): def setUp(self): + self.database = tkp.db.Database() - try: - execute('drop table median_test') - except: - rollback() - execute('create table median_test (i int, f float)') - execute('insert into median_test values (1, 1.1)') - execute('insert into median_test values (2, 2.1)') - execute('insert into median_test values (3, 3.1)') + self.dataset = tkp.db.DataSet(database=self.database, + data={'description':"Median test" + + self._testMethodName}) + self.n_images = 5 - def tearDown(self): - rollback() + self.im_params = db_subs.generate_timespaced_dbimages_data(self.n_images) + for idx, impar in enumerate(self.im_params): + impar['rms_max'] = (idx+1)*1e-4 + + self.image_ids = [] + for img_pars in self.im_params: + image,_,_ = db_subs.insert_image_and_simulated_sources( + self.dataset,img_pars,[], + new_source_sigma_margin=3) + self.image_ids.append(image.id) + def test_median(self): - cursor = execute('select median(i), median(f) from median_test') - median_i, median_f = cursor.fetchall()[0] - self.assertEqual(median_i, 2) - self.assertEqual(median_f, 2.1) + if Database().engine == 'monetdb': + qry = (""" + SELECT sys.median(id) as median_id + ,sys.median(rms_max) as median_rms_max + FROM image + WHERE dataset = %(dataset_id)s + """) + else: + qry = (""" + SELECT median(id) as median_id + ,median(rms_max) as median_rms_max + FROM image + WHERE dataset = %(dataset_id)s + """) + cursor = execute(qry, {'dataset_id': self.dataset.id}) + results = db_subs.get_db_rows_as_dicts(cursor) + # self.assertAlmostEqual(results[0]['median_id'], median(self.image_ids)) + self.assertAlmostEqual(results[0]['median_rms_max'], + median([p['rms_max'] for p in self.im_params])) +
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])
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])
762ba71537cebac83970fbfb19725054b127191b
__init__.py
__init__.py
from .blendergltf import *
if 'loaded' in locals(): import imp imp.reload(blendergltf) from .blendergltf import * else: loaded = True from .blendergltf import *
Improve reloading of the module
Improve reloading of the module
Python
apache-2.0
Kupoman/blendergltf,lukesanantonio/blendergltf
+ if 'loaded' in locals(): + import imp + imp.reload(blendergltf) - from .blendergltf import * + from .blendergltf import * + else: + loaded = True + from .blendergltf import *
Improve reloading of the module
## Code Before: from .blendergltf import * ## Instruction: Improve reloading of the module ## Code After: if 'loaded' in locals(): import imp imp.reload(blendergltf) from .blendergltf import * else: loaded = True from .blendergltf import *
+ if 'loaded' in locals(): + import imp + imp.reload(blendergltf) - from .blendergltf import * + from .blendergltf import * ? ++++ + else: + loaded = True + from .blendergltf import *
4a41b33286cf881f0b3aa09c29a4aaa3568b5259
website/stats/plots/mimp.py
website/stats/plots/mimp.py
from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_type_name in glycosylation_sub_types: result = run_mimp(source_name, site_type_name, enzyme_type='catch-all') if result.empty: continue effect_counts = result.effect.value_counts() results[source_name] = effects, [effect_counts.get(effect, 0) for effect in effects] return results
from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_type_name in glycosylation_sub_types: result = run_mimp(source_name, site_type_name, enzyme_type='catch-all') if result.empty: continue effect_counts = result.effect.value_counts() results[source_name] = effects, [ int(effect_counts.get(effect, 0)) for effect in effects ] return results
Convert numpy int to native int for JSON serialization
Convert numpy int to native int for JSON serialization
Python
lgpl-2.1
reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations
from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_type_name in glycosylation_sub_types: result = run_mimp(source_name, site_type_name, enzyme_type='catch-all') if result.empty: continue effect_counts = result.effect.value_counts() - results[source_name] = effects, [effect_counts.get(effect, 0) for effect in effects] + results[source_name] = effects, [ + int(effect_counts.get(effect, 0)) + for effect in effects + ] return results
Convert numpy int to native int for JSON serialization
## Code Before: from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_type_name in glycosylation_sub_types: result = run_mimp(source_name, site_type_name, enzyme_type='catch-all') if result.empty: continue effect_counts = result.effect.value_counts() results[source_name] = effects, [effect_counts.get(effect, 0) for effect in effects] return results ## Instruction: Convert numpy int to native int for JSON serialization ## Code After: from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_type_name in glycosylation_sub_types: result = run_mimp(source_name, site_type_name, enzyme_type='catch-all') if result.empty: continue effect_counts = result.effect.value_counts() results[source_name] = effects, [ int(effect_counts.get(effect, 0)) for effect in effects ] return results
from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_type_name in glycosylation_sub_types: result = run_mimp(source_name, site_type_name, enzyme_type='catch-all') if result.empty: continue effect_counts = result.effect.value_counts() - results[source_name] = effects, [effect_counts.get(effect, 0) for effect in effects] + results[source_name] = effects, [ + int(effect_counts.get(effect, 0)) + for effect in effects + ] return results
ce38ad1884cdc602d1b70d5a23d749ff3683f440
reqon/utils.py
reqon/utils.py
def dict_in(value): ''' Checks for the existence of a dictionary in a list Arguments: value -- A list Returns: A Boolean ''' for item in value: if isinstance(item, dict): return True return False
def dict_in(value): ''' Checks for the existence of a dictionary in a list Arguments: value -- A list Returns: A Boolean ''' return any(isinstance(item, dict) for item in value)
Make the dict_in function sleeker and sexier
Make the dict_in function sleeker and sexier
Python
mit
dmpayton/reqon
def dict_in(value): ''' Checks for the existence of a dictionary in a list Arguments: value -- A list Returns: A Boolean ''' + return any(isinstance(item, dict) for item in value) - for item in value: - if isinstance(item, dict): - return True - return False
Make the dict_in function sleeker and sexier
## Code Before: def dict_in(value): ''' Checks for the existence of a dictionary in a list Arguments: value -- A list Returns: A Boolean ''' for item in value: if isinstance(item, dict): return True return False ## Instruction: Make the dict_in function sleeker and sexier ## Code After: def dict_in(value): ''' Checks for the existence of a dictionary in a list Arguments: value -- A list Returns: A Boolean ''' return any(isinstance(item, dict) for item in value)
def dict_in(value): ''' Checks for the existence of a dictionary in a list Arguments: value -- A list Returns: A Boolean ''' + return any(isinstance(item, dict) for item in value) - for item in value: - if isinstance(item, dict): - return True - return False
d6acda58c696c5b348da8c6a4fef3bf06cea0e58
weight/models.py
weight/models.py
from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
Add default ordering to weight entries
Add default ordering to weight entries
Python
agpl-3.0
kjagoo/wger_stark,wger-project/wger,wger-project/wger,wger-project/wger,kjagoo/wger_stark,wger-project/wger,rolandgeider/wger,petervanderdoes/wger,petervanderdoes/wger,petervanderdoes/wger,kjagoo/wger_stark,petervanderdoes/wger,DeveloperMal/wger,DeveloperMal/wger,DeveloperMal/wger,rolandgeider/wger,DeveloperMal/wger,kjagoo/wger_stark,rolandgeider/wger,rolandgeider/wger
from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) + # Metaclass to set some other properties + class Meta: + ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
Add default ordering to weight entries
## Code Before: from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight) ## Instruction: Add default ordering to weight entries ## Code After: from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) + # Metaclass to set some other properties + class Meta: + ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
c4153cc69238054ddbdb8b385325f5a8701e98f8
taxiexpress/serializers.py
taxiexpress/serializers.py
from django.forms import widgets from rest_framework import serializers from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'animals', 'appPayment') class DriverSerializer(serializers.ModelSerializer): valuation = serializers.SerializerMethodField('get_valuation') car = CarSerializer() def get_valuation(self, obj): return int(5*obj.positiveVotes/(obj.positiveVotes+obj.negativeVotes)) class Meta: model = Driver fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'valuation', 'car') class TravelSerializer(serializers.ModelSerializer): driver= DriverSerializer() class Meta: model = Travel fields = ('id', 'driver', 'starttime', 'endtime', 'cost', 'startpoint', 'origin', 'endpoint', 'destination') class CustomerSerializer(serializers.ModelSerializer): favlist = DriverSerializer(many=True) travel_set = TravelSerializer(many=True) class Meta: model = Customer fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'travel_set')
from django.forms import widgets from rest_framework import serializers from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'animals', 'appPayment') class DriverSerializer(serializers.ModelSerializer): valuation = serializers.SerializerMethodField('get_valuation') car = CarSerializer() def get_valuation(self, obj): return int(5*obj.positiveVotes/(obj.positiveVotes+obj.negativeVotes)) class Meta: model = Driver fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'valuation', 'car') class TravelSerializer(serializers.ModelSerializer): driver= DriverSerializer() class Meta: model = Travel fields = ('id', 'driver', 'starttime', 'endtime', 'cost', 'startpoint', 'origin', 'endpoint', 'destination') class CustomerSerializer(serializers.ModelSerializer): favlist = DriverSerializer(many=True) travel_set = TravelSerializer(many=True) class Meta: model = Customer fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'fAccessible', 'fAnimals', 'fAppPayment', 'fCapacity', 'travel_set')
Add filters to Customer serializer
Add filters to Customer serializer
Python
mit
TaxiExpress/server,TaxiExpress/server
from django.forms import widgets from rest_framework import serializers from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'animals', 'appPayment') class DriverSerializer(serializers.ModelSerializer): valuation = serializers.SerializerMethodField('get_valuation') car = CarSerializer() def get_valuation(self, obj): return int(5*obj.positiveVotes/(obj.positiveVotes+obj.negativeVotes)) class Meta: model = Driver fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'valuation', 'car') class TravelSerializer(serializers.ModelSerializer): driver= DriverSerializer() class Meta: model = Travel fields = ('id', 'driver', 'starttime', 'endtime', 'cost', 'startpoint', 'origin', 'endpoint', 'destination') class CustomerSerializer(serializers.ModelSerializer): favlist = DriverSerializer(many=True) travel_set = TravelSerializer(many=True) class Meta: model = Customer - fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'travel_set') + fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'fAccessible', 'fAnimals', 'fAppPayment', 'fCapacity', 'travel_set')
Add filters to Customer serializer
## Code Before: from django.forms import widgets from rest_framework import serializers from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'animals', 'appPayment') class DriverSerializer(serializers.ModelSerializer): valuation = serializers.SerializerMethodField('get_valuation') car = CarSerializer() def get_valuation(self, obj): return int(5*obj.positiveVotes/(obj.positiveVotes+obj.negativeVotes)) class Meta: model = Driver fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'valuation', 'car') class TravelSerializer(serializers.ModelSerializer): driver= DriverSerializer() class Meta: model = Travel fields = ('id', 'driver', 'starttime', 'endtime', 'cost', 'startpoint', 'origin', 'endpoint', 'destination') class CustomerSerializer(serializers.ModelSerializer): favlist = DriverSerializer(many=True) travel_set = TravelSerializer(many=True) class Meta: model = Customer fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'travel_set') ## Instruction: Add filters to Customer serializer ## Code After: from django.forms import widgets from rest_framework import serializers from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'animals', 'appPayment') class DriverSerializer(serializers.ModelSerializer): valuation = serializers.SerializerMethodField('get_valuation') car = CarSerializer() def get_valuation(self, obj): return int(5*obj.positiveVotes/(obj.positiveVotes+obj.negativeVotes)) class Meta: model = Driver fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'valuation', 'car') class TravelSerializer(serializers.ModelSerializer): driver= DriverSerializer() class Meta: model = Travel fields = ('id', 'driver', 'starttime', 'endtime', 'cost', 'startpoint', 'origin', 'endpoint', 'destination') class CustomerSerializer(serializers.ModelSerializer): favlist = DriverSerializer(many=True) travel_set = TravelSerializer(many=True) class Meta: model = Customer fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'fAccessible', 'fAnimals', 'fAppPayment', 'fCapacity', 'travel_set')
from django.forms import widgets from rest_framework import serializers from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'animals', 'appPayment') class DriverSerializer(serializers.ModelSerializer): valuation = serializers.SerializerMethodField('get_valuation') car = CarSerializer() def get_valuation(self, obj): return int(5*obj.positiveVotes/(obj.positiveVotes+obj.negativeVotes)) class Meta: model = Driver fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'valuation', 'car') class TravelSerializer(serializers.ModelSerializer): driver= DriverSerializer() class Meta: model = Travel fields = ('id', 'driver', 'starttime', 'endtime', 'cost', 'startpoint', 'origin', 'endpoint', 'destination') class CustomerSerializer(serializers.ModelSerializer): favlist = DriverSerializer(many=True) travel_set = TravelSerializer(many=True) class Meta: model = Customer - fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'travel_set') + fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'fAccessible', 'fAnimals', 'fAppPayment', 'fCapacity', 'travel_set') ? +++++++++++++++++++++++++++++++++++++++++++++++++++++++
e8c1ba2c63a1ea66aa2c08e606ac0614e6854565
interrupt.py
interrupt.py
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) return e
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) return e
Handle sigterm as well as sigint.
Handle sigterm as well as sigint.
Python
mit
rickbassham/videoencode,rickbassham/videoencode
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) return e
Handle sigterm as well as sigint.
## Code Before: import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) return e ## Instruction: Handle sigterm as well as sigint. ## Code After: import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) return e
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) return e
442f0df33b91fced038e2c497e6c03e0f82f55b2
qtpy/QtTest.py
qtpy/QtTest.py
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) elif PYSIDE: raise ImportError('QtTest support is incomplete for PySide') else: raise PythonQtError('No Qt bindings could be found')
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) elif PYSIDE: from PySide.QtTest import QTest else: raise PythonQtError('No Qt bindings could be found')
Add support for QTest with PySide
Add support for QTest with PySide
Python
mit
spyder-ide/qtpy,davvid/qtpy,goanpeca/qtpy,davvid/qtpy,goanpeca/qtpy
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) elif PYSIDE: - raise ImportError('QtTest support is incomplete for PySide') + from PySide.QtTest import QTest else: raise PythonQtError('No Qt bindings could be found')
Add support for QTest with PySide
## Code Before: from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) elif PYSIDE: raise ImportError('QtTest support is incomplete for PySide') else: raise PythonQtError('No Qt bindings could be found') ## Instruction: Add support for QTest with PySide ## Code After: from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) elif PYSIDE: from PySide.QtTest import QTest else: raise PythonQtError('No Qt bindings could be found')
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) elif PYSIDE: - raise ImportError('QtTest support is incomplete for PySide') + from PySide.QtTest import QTest else: raise PythonQtError('No Qt bindings could be found')
98f6a07188cc9a9aa9373c3795db49b1e576c2a8
iatidq/dqimportpublisherconditions.py
iatidq/dqimportpublisherconditions.py
from iatidq import db import models import csv import util import urllib2 def _importPCs(fh, local=True): results = {} for n, line in enumerate(fh): text = line.strip('\n') results[n]=text import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] for n, line in results.items(): data = test_functions[n](line) data["description"] = line tested_results.append(data) return tested_results def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh: return _importPCs(fh, local=True) def importPCsFromUrl(url): fh = urllib2.urlopen(url) return _importPCs(fh, local=False) if __name__ == "__main__": importPCs('../tests/organisation_structures.txt')
from iatidq import db import models import csv import util import urllib2 def _parsePCresults(results): import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] for n, line in results.items(): data = test_functions[n](line) data["description"] = line tested_results.append(data) return tested_results def importPCsFromText(text): results = {} for n, line in enumerate(text.split("\n")): results[n]=line return _parsePCresults(results) def _importPCs(fh, local=True): results = {} for n, line in enumerate(fh): text = line.strip('\n') results[n]=text return _parsePCresults(results) def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh: return _importPCs(fh, local=True) def importPCsFromUrl(url): fh = urllib2.urlopen(url) return _importPCs(fh, local=False) if __name__ == "__main__": importPCs('../tests/organisation_structures.txt')
Allow publisher conditions to be imported from text
Allow publisher conditions to be imported from text
Python
agpl-3.0
pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality
from iatidq import db import models import csv import util import urllib2 + def _parsePCresults(results): - def _importPCs(fh, local=True): - - results = {} - for n, line in enumerate(fh): - text = line.strip('\n') - results[n]=text - import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] for n, line in results.items(): data = test_functions[n](line) data["description"] = line tested_results.append(data) return tested_results + + def importPCsFromText(text): + results = {} + for n, line in enumerate(text.split("\n")): + results[n]=line + return _parsePCresults(results) + + def _importPCs(fh, local=True): + results = {} + for n, line in enumerate(fh): + text = line.strip('\n') + results[n]=text + return _parsePCresults(results) def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh: return _importPCs(fh, local=True) def importPCsFromUrl(url): fh = urllib2.urlopen(url) return _importPCs(fh, local=False) if __name__ == "__main__": importPCs('../tests/organisation_structures.txt')
Allow publisher conditions to be imported from text
## Code Before: from iatidq import db import models import csv import util import urllib2 def _importPCs(fh, local=True): results = {} for n, line in enumerate(fh): text = line.strip('\n') results[n]=text import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] for n, line in results.items(): data = test_functions[n](line) data["description"] = line tested_results.append(data) return tested_results def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh: return _importPCs(fh, local=True) def importPCsFromUrl(url): fh = urllib2.urlopen(url) return _importPCs(fh, local=False) if __name__ == "__main__": importPCs('../tests/organisation_structures.txt') ## Instruction: Allow publisher conditions to be imported from text ## Code After: from iatidq import db import models import csv import util import urllib2 def _parsePCresults(results): import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] for n, line in results.items(): data = test_functions[n](line) data["description"] = line tested_results.append(data) return tested_results def importPCsFromText(text): results = {} for n, line in enumerate(text.split("\n")): results[n]=line return _parsePCresults(results) def _importPCs(fh, local=True): results = {} for n, line in enumerate(fh): text = line.strip('\n') results[n]=text return _parsePCresults(results) def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh: return _importPCs(fh, local=True) def importPCsFromUrl(url): fh = urllib2.urlopen(url) return _importPCs(fh, local=False) if __name__ == "__main__": importPCs('../tests/organisation_structures.txt')
from iatidq import db import models import csv import util import urllib2 + def _parsePCresults(results): - def _importPCs(fh, local=True): - - results = {} - for n, line in enumerate(fh): - text = line.strip('\n') - results[n]=text - import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] for n, line in results.items(): data = test_functions[n](line) data["description"] = line tested_results.append(data) return tested_results + + def importPCsFromText(text): + results = {} + for n, line in enumerate(text.split("\n")): + results[n]=line + return _parsePCresults(results) + + def _importPCs(fh, local=True): + results = {} + for n, line in enumerate(fh): + text = line.strip('\n') + results[n]=text + return _parsePCresults(results) def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh: return _importPCs(fh, local=True) def importPCsFromUrl(url): fh = urllib2.urlopen(url) return _importPCs(fh, local=False) if __name__ == "__main__": importPCs('../tests/organisation_structures.txt')
f48554bcc5ac1161314592cb43ba65701d387289
tests/test_check_endpoint.py
tests/test_check_endpoint.py
import pytest def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert False def test_expiring_certificate_with_bad_cert(): assert false def test_send_email(): assert False
import pytest # We're going to fake a connection for purposes of testing. # So far all we use is getpeercert method, so that's all we need to fake class fake_connection(object): def __init__(self): pass def getpeercert(self): cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', 'subjectAltName': (('DNS', 'www.fake.com'),), 'subject': ((('countryName', u'US'),), (('stateOrProvinceName', u'Oregon'),), (('localityName', u'Springfield'),), (('organizationName', u'FakeCompany'),), (('commonName', u'fake.com'),))} return cert_details def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert False def test_expiring_certificate_with_bad_cert(): assert False def test_send_email(): assert False
Add fake connection class, PEP8 changes
Add fake connection class, PEP8 changes Also had a bad assert in there
Python
mit
twirrim/checkendpoint
import pytest + + # We're going to fake a connection for purposes of testing. + # So far all we use is getpeercert method, so that's all we need to fake + class fake_connection(object): + def __init__(self): + pass + + def getpeercert(self): + cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', + 'subjectAltName': (('DNS', 'www.fake.com'),), + 'subject': ((('countryName', u'US'),), + (('stateOrProvinceName', u'Oregon'),), + (('localityName', u'Springfield'),), + (('organizationName', u'FakeCompany'),), + (('commonName', u'fake.com'),))} + return cert_details + def test_get_connection(): assert False + def test_verify_hostname_with_valid_hostname(): assert False + def test_verify_hostname_with_valid_altname(): assert False + def test_verify_hostname_with_invalid_hostname(): assert False + def test_expiring_certificate_with_good_cert(): assert False + def test_expiring_certificate_with_bad_cert(): - assert false + assert False + def test_send_email(): assert False +
Add fake connection class, PEP8 changes
## Code Before: import pytest def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert False def test_expiring_certificate_with_bad_cert(): assert false def test_send_email(): assert False ## Instruction: Add fake connection class, PEP8 changes ## Code After: import pytest # We're going to fake a connection for purposes of testing. # So far all we use is getpeercert method, so that's all we need to fake class fake_connection(object): def __init__(self): pass def getpeercert(self): cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', 'subjectAltName': (('DNS', 'www.fake.com'),), 'subject': ((('countryName', u'US'),), (('stateOrProvinceName', u'Oregon'),), (('localityName', u'Springfield'),), (('organizationName', u'FakeCompany'),), (('commonName', u'fake.com'),))} return cert_details def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert False def test_expiring_certificate_with_bad_cert(): assert False def test_send_email(): assert False
import pytest + + # We're going to fake a connection for purposes of testing. + # So far all we use is getpeercert method, so that's all we need to fake + class fake_connection(object): + def __init__(self): + pass + + def getpeercert(self): + cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', + 'subjectAltName': (('DNS', 'www.fake.com'),), + 'subject': ((('countryName', u'US'),), + (('stateOrProvinceName', u'Oregon'),), + (('localityName', u'Springfield'),), + (('organizationName', u'FakeCompany'),), + (('commonName', u'fake.com'),))} + return cert_details + def test_get_connection(): assert False + def test_verify_hostname_with_valid_hostname(): assert False + def test_verify_hostname_with_valid_altname(): assert False + def test_verify_hostname_with_invalid_hostname(): assert False + def test_expiring_certificate_with_good_cert(): assert False + def test_expiring_certificate_with_bad_cert(): - assert false ? ^ + assert False ? ^ + def test_send_email(): assert False
3d7459f7b1d40bb94a64d3f08d41942feabf4c12
manager/jobs/migrations/0003_auto_20200723_0219.py
manager/jobs/migrations/0003_auto_20200723_0219.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ migrations.AlterField( model_name='job', name='id', field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False), ), migrations.AlterField( model_name='job', name='method', field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32), ), ]
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ migrations.RemoveField( model_name='job', name='id', ), migrations.AddField( model_name='job', name='id', field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False), ), migrations.AlterField( model_name='job', name='method', field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32), ), ]
Allow migration to run on Postgres
chore(Jobs): Allow migration to run on Postgres
Python
apache-2.0
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ + migrations.RemoveField( + model_name='job', + name='id', + ), - migrations.AlterField( + migrations.AddField( model_name='job', name='id', field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False), ), migrations.AlterField( model_name='job', name='method', field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32), ), ]
Allow migration to run on Postgres
## Code Before: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ migrations.AlterField( model_name='job', name='id', field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False), ), migrations.AlterField( model_name='job', name='method', field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32), ), ] ## Instruction: Allow migration to run on Postgres ## Code After: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ migrations.RemoveField( model_name='job', name='id', ), migrations.AddField( model_name='job', name='id', field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False), ), migrations.AlterField( model_name='job', name='method', field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32), ), ]
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ + migrations.RemoveField( + model_name='job', + name='id', + ), - migrations.AlterField( ? ^^^^ + migrations.AddField( ? ^^ model_name='job', name='id', field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False), ), migrations.AlterField( model_name='job', name='method', field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32), ), ]
b26ce5b5ff778208314bfd21014f88ee24917d7a
ideas/views.py
ideas/views.py
from .models import Idea from .serializers import IdeaSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET',]) def idea_list(request): if request.method == 'GET': ideas = Idea.objects.all() serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def results(request): if request.method == 'GET': ideas_ordered = Idea.objects.order_by('-votes') serializer = IdeaSerializer(ideas_ordered, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['POST',]) def vote(request): if request.method == 'POST': idea = Idea.objects.get(pk=request.data) idea.votes += 1 idea.save() serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK)
from .models import Idea from .serializers import IdeaSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET',]) def idea_list(request): if request.method == 'GET': ideas = Idea.objects.all() serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def idea(request, pk): if request.method == 'GET': idea = Idea.objects.get(pk=pk) serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def results(request): if request.method == 'GET': ideas_ordered = Idea.objects.order_by('-votes') serializer = IdeaSerializer(ideas_ordered, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['POST',]) def vote(request, pk): if request.method == 'POST': idea = Idea.objects.get(pk=pk) idea.votes += 1 idea.save() serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK)
Add GET for idea and refactor vote
Add GET for idea and refactor vote
Python
mit
neosergio/vote_hackatrix_backend
from .models import Idea from .serializers import IdeaSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET',]) def idea_list(request): if request.method == 'GET': ideas = Idea.objects.all() serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) + def idea(request, pk): + if request.method == 'GET': + idea = Idea.objects.get(pk=pk) + serializer = IdeaSerializer(idea) + return Response(serializer.data, status=status.HTTP_200_OK) + + @api_view(['GET',]) def results(request): if request.method == 'GET': ideas_ordered = Idea.objects.order_by('-votes') serializer = IdeaSerializer(ideas_ordered, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['POST',]) - def vote(request): + def vote(request, pk): if request.method == 'POST': - idea = Idea.objects.get(pk=request.data) + idea = Idea.objects.get(pk=pk) idea.votes += 1 idea.save() serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK)
Add GET for idea and refactor vote
## Code Before: from .models import Idea from .serializers import IdeaSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET',]) def idea_list(request): if request.method == 'GET': ideas = Idea.objects.all() serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def results(request): if request.method == 'GET': ideas_ordered = Idea.objects.order_by('-votes') serializer = IdeaSerializer(ideas_ordered, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['POST',]) def vote(request): if request.method == 'POST': idea = Idea.objects.get(pk=request.data) idea.votes += 1 idea.save() serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK) ## Instruction: Add GET for idea and refactor vote ## Code After: from .models import Idea from .serializers import IdeaSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET',]) def idea_list(request): if request.method == 'GET': ideas = Idea.objects.all() serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def idea(request, pk): if request.method == 'GET': idea = Idea.objects.get(pk=pk) serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def results(request): if request.method == 'GET': ideas_ordered = Idea.objects.order_by('-votes') serializer = IdeaSerializer(ideas_ordered, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['POST',]) def vote(request, pk): if request.method == 'POST': idea = Idea.objects.get(pk=pk) idea.votes += 1 idea.save() serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK)
from .models import Idea from .serializers import IdeaSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET',]) def idea_list(request): if request.method == 'GET': ideas = Idea.objects.all() serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) + def idea(request, pk): + if request.method == 'GET': + idea = Idea.objects.get(pk=pk) + serializer = IdeaSerializer(idea) + return Response(serializer.data, status=status.HTTP_200_OK) + + @api_view(['GET',]) def results(request): if request.method == 'GET': ideas_ordered = Idea.objects.order_by('-votes') serializer = IdeaSerializer(ideas_ordered, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['POST',]) - def vote(request): + def vote(request, pk): ? ++++ if request.method == 'POST': - idea = Idea.objects.get(pk=request.data) ? ^^^^^^^^^^^^ + idea = Idea.objects.get(pk=pk) ? ^^ idea.votes += 1 idea.save() serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK)
5d36b16fde863cccf404f658f53eac600ac9ddb1
foomodules/link_harvester/common_handlers.py
foomodules/link_harvester/common_handlers.py
import re import socket import urllib from bs4 import BeautifulSoup WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/") def default_handler(metadata): return {key: getattr(metadata, key) for key in ["original_url", "url", "title", "description", "human_readable_type"]} def wurstball_handler(metadata): if WURSTBALL_RE.match(metadata.url) is None: return None ret = default_handler(metadata) soup = BeautifulSoup(metadata.buf) img_url = soup.find(id="content-main").img["src"] try: response = urllib.request.urlopen(img_url, timeout=5) img_data = response.read() except (socket.timeout, urllib.error.URLError, urllib.error.HTTPError): return ret mime_type = response.getheader("Content-Type") ret.update({"image_mime_type": mime_type, "image_buffer": img_data, "image_url": img_url}) return ret
import logging import re import socket import urllib from bs4 import BeautifulSoup logger = logging.getLogger(__name__) WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/") def default_handler(metadata): return {key: getattr(metadata, key) for key in ["original_url", "url", "title", "description", "human_readable_type"]} def wurstball_handler(metadata): if WURSTBALL_RE.match(metadata.url) is None: return None ret = default_handler(metadata) soup = BeautifulSoup(metadata.buf) img_url = soup.find(id="content-main").img["src"] try: response = urllib.request.urlopen(img_url, timeout=5) img_data = response.read() except (socket.timeout, urllib.error.URLError, urllib.error.HTTPError) as err: logger.warn("Could not download Wurstball image: {}".format(err)) return ret mime_type = response.getheader("Content-Type") ret.update({"image_mime_type": mime_type, "image_buffer": img_data, "image_url": img_url}) return ret
Print warning when wurstball downloads fail
Print warning when wurstball downloads fail
Python
mit
horazont/xmpp-crowd
+ import logging import re import socket import urllib from bs4 import BeautifulSoup - + logger = logging.getLogger(__name__) WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/") def default_handler(metadata): return {key: getattr(metadata, key) for key in ["original_url", "url", "title", "description", "human_readable_type"]} def wurstball_handler(metadata): if WURSTBALL_RE.match(metadata.url) is None: return None ret = default_handler(metadata) soup = BeautifulSoup(metadata.buf) img_url = soup.find(id="content-main").img["src"] try: response = urllib.request.urlopen(img_url, timeout=5) img_data = response.read() except (socket.timeout, urllib.error.URLError, - urllib.error.HTTPError): + urllib.error.HTTPError) as err: + logger.warn("Could not download Wurstball image: {}".format(err)) return ret mime_type = response.getheader("Content-Type") ret.update({"image_mime_type": mime_type, "image_buffer": img_data, "image_url": img_url}) return ret
Print warning when wurstball downloads fail
## Code Before: import re import socket import urllib from bs4 import BeautifulSoup WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/") def default_handler(metadata): return {key: getattr(metadata, key) for key in ["original_url", "url", "title", "description", "human_readable_type"]} def wurstball_handler(metadata): if WURSTBALL_RE.match(metadata.url) is None: return None ret = default_handler(metadata) soup = BeautifulSoup(metadata.buf) img_url = soup.find(id="content-main").img["src"] try: response = urllib.request.urlopen(img_url, timeout=5) img_data = response.read() except (socket.timeout, urllib.error.URLError, urllib.error.HTTPError): return ret mime_type = response.getheader("Content-Type") ret.update({"image_mime_type": mime_type, "image_buffer": img_data, "image_url": img_url}) return ret ## Instruction: Print warning when wurstball downloads fail ## Code After: import logging import re import socket import urllib from bs4 import BeautifulSoup logger = logging.getLogger(__name__) WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/") def default_handler(metadata): return {key: getattr(metadata, key) for key in ["original_url", "url", "title", "description", "human_readable_type"]} def wurstball_handler(metadata): if WURSTBALL_RE.match(metadata.url) is None: return None ret = default_handler(metadata) soup = BeautifulSoup(metadata.buf) img_url = soup.find(id="content-main").img["src"] try: response = urllib.request.urlopen(img_url, timeout=5) img_data = response.read() except (socket.timeout, urllib.error.URLError, urllib.error.HTTPError) as err: logger.warn("Could not download Wurstball image: {}".format(err)) return ret mime_type = response.getheader("Content-Type") ret.update({"image_mime_type": mime_type, "image_buffer": img_data, "image_url": img_url}) return ret
+ import logging import re import socket import urllib from bs4 import BeautifulSoup - + logger = logging.getLogger(__name__) WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/") def default_handler(metadata): return {key: getattr(metadata, key) for key in ["original_url", "url", "title", "description", "human_readable_type"]} def wurstball_handler(metadata): if WURSTBALL_RE.match(metadata.url) is None: return None ret = default_handler(metadata) soup = BeautifulSoup(metadata.buf) img_url = soup.find(id="content-main").img["src"] try: response = urllib.request.urlopen(img_url, timeout=5) img_data = response.read() except (socket.timeout, urllib.error.URLError, - urllib.error.HTTPError): + urllib.error.HTTPError) as err: ? +++++++ + logger.warn("Could not download Wurstball image: {}".format(err)) return ret mime_type = response.getheader("Content-Type") ret.update({"image_mime_type": mime_type, "image_buffer": img_data, "image_url": img_url}) return ret
42be4a39b9241ff3138efa52b316070713fc552a
people/serializers.py
people/serializers.py
from rest_framework import serializers from people.models import Customer from people.models import InternalUser class CustomerSerializer(serializers.ModelSerializer): phone_number = serializers.IntegerField(validators=[lambda x: len(str(x)) == 10]) class Meta: model = Customer fields = '__all__' class InternalUserSerializer(serializers.ModelSerializer): class Meta: model = InternalUser fields = '__all__'
from django.contrib.gis import serializers from rest_framework import serializers from people.models import Customer from people.models import InternalUser class CustomerSerializer(serializers.ModelSerializer): phone_number = serializers.IntegerField() def validate_phone_number(self, val): if len(str(val)) != 10: raise serializers.ValidationError('The phone number must be 10 digits long') class Meta: model = Customer fields = '__all__' class InternalUserSerializer(serializers.ModelSerializer): class Meta: model = InternalUser fields = '__all__'
Put validators in phone numbers
Put validators in phone numbers
Python
apache-2.0
rameshgopalakrishnan/v_excel_inventory,rameshgopalakrishnan/v_excel_inventory,rameshgopalakrishnan/v_excel_inventory
+ from django.contrib.gis import serializers from rest_framework import serializers from people.models import Customer from people.models import InternalUser class CustomerSerializer(serializers.ModelSerializer): - phone_number = serializers.IntegerField(validators=[lambda x: len(str(x)) == 10]) + phone_number = serializers.IntegerField() + + def validate_phone_number(self, val): + if len(str(val)) != 10: + raise serializers.ValidationError('The phone number must be 10 digits long') class Meta: model = Customer fields = '__all__' class InternalUserSerializer(serializers.ModelSerializer): class Meta: model = InternalUser fields = '__all__'
Put validators in phone numbers
## Code Before: from rest_framework import serializers from people.models import Customer from people.models import InternalUser class CustomerSerializer(serializers.ModelSerializer): phone_number = serializers.IntegerField(validators=[lambda x: len(str(x)) == 10]) class Meta: model = Customer fields = '__all__' class InternalUserSerializer(serializers.ModelSerializer): class Meta: model = InternalUser fields = '__all__' ## Instruction: Put validators in phone numbers ## Code After: from django.contrib.gis import serializers from rest_framework import serializers from people.models import Customer from people.models import InternalUser class CustomerSerializer(serializers.ModelSerializer): phone_number = serializers.IntegerField() def validate_phone_number(self, val): if len(str(val)) != 10: raise serializers.ValidationError('The phone number must be 10 digits long') class Meta: model = Customer fields = '__all__' class InternalUserSerializer(serializers.ModelSerializer): class Meta: model = InternalUser fields = '__all__'
+ from django.contrib.gis import serializers from rest_framework import serializers from people.models import Customer from people.models import InternalUser class CustomerSerializer(serializers.ModelSerializer): - phone_number = serializers.IntegerField(validators=[lambda x: len(str(x)) == 10]) + phone_number = serializers.IntegerField() + + def validate_phone_number(self, val): + if len(str(val)) != 10: + raise serializers.ValidationError('The phone number must be 10 digits long') class Meta: model = Customer fields = '__all__' class InternalUserSerializer(serializers.ModelSerializer): class Meta: model = InternalUser fields = '__all__'
1b103d314e94e3c1dba9d9d08a2655c62f26d18c
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
import ibmcnx.functions dbs = AdminConfig.list( 'DataSource', AdminControl.getCell()) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
import ibmcnx.functions cell = '/' + AdminControl.getCell() + '/' dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
Create script to save documentation to a file
4: Create script to save documentation to a file Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
import ibmcnx.functions + cell = '/' + AdminControl.getCell() + '/' - dbs = AdminConfig.list( 'DataSource', AdminControl.getCell()) + dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
Create script to save documentation to a file
## Code Before: import ibmcnx.functions dbs = AdminConfig.list( 'DataSource', AdminControl.getCell()) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 ) ## Instruction: Create script to save documentation to a file ## Code After: import ibmcnx.functions cell = '/' + AdminControl.getCell() + '/' dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
import ibmcnx.functions + cell = '/' + AdminControl.getCell() + '/' - dbs = AdminConfig.list( 'DataSource', AdminControl.getCell()) ? ^^^^^^^^^^^^^^^^^ ^ - + dbs = AdminConfig.list( 'DataSource', cell ) ? ^ ^ for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
adb658a874a7d0437607bf828e99adf2dee74438
openassessment/fileupload/backends/__init__.py
openassessment/fileupload/backends/__init__.py
""" File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): # Use S3 backend by default (current behaviour) backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend() elif backend_setting == "filesystem": return filesystem.Backend() elif backend_setting == "swift": return swift.Backend() elif backend_setting == "django": return django_storage.Backend() else: raise ValueError("Invalid ORA2_FILEUPLOAD_BACKEND setting value: %s" % backend_setting)
""" File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): # .. setting_name: ORA2_FILEUPLOAD_BACKEND # .. setting_default: s3 # .. setting_description: The backend used to upload the ora2 submissions attachments # the supported values are: s3, filesystem, swift and django. backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend() elif backend_setting == "filesystem": return filesystem.Backend() elif backend_setting == "swift": return swift.Backend() elif backend_setting == "django": return django_storage.Backend() else: raise ValueError("Invalid ORA2_FILEUPLOAD_BACKEND setting value: %s" % backend_setting)
Add annotation for ORA2_FILEUPLOAD_BACKEND setting
Add annotation for ORA2_FILEUPLOAD_BACKEND setting
Python
agpl-3.0
edx/edx-ora2,edx/edx-ora2,EDUlib/edx-ora2,edx/edx-ora2,EDUlib/edx-ora2,EDUlib/edx-ora2,EDUlib/edx-ora2,edx/edx-ora2
""" File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): - # Use S3 backend by default (current behaviour) + # .. setting_name: ORA2_FILEUPLOAD_BACKEND + # .. setting_default: s3 + # .. setting_description: The backend used to upload the ora2 submissions attachments + # the supported values are: s3, filesystem, swift and django. backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend() elif backend_setting == "filesystem": return filesystem.Backend() elif backend_setting == "swift": return swift.Backend() elif backend_setting == "django": return django_storage.Backend() else: raise ValueError("Invalid ORA2_FILEUPLOAD_BACKEND setting value: %s" % backend_setting)
Add annotation for ORA2_FILEUPLOAD_BACKEND setting
## Code Before: """ File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): # Use S3 backend by default (current behaviour) backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend() elif backend_setting == "filesystem": return filesystem.Backend() elif backend_setting == "swift": return swift.Backend() elif backend_setting == "django": return django_storage.Backend() else: raise ValueError("Invalid ORA2_FILEUPLOAD_BACKEND setting value: %s" % backend_setting) ## Instruction: Add annotation for ORA2_FILEUPLOAD_BACKEND setting ## Code After: """ File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): # .. setting_name: ORA2_FILEUPLOAD_BACKEND # .. setting_default: s3 # .. setting_description: The backend used to upload the ora2 submissions attachments # the supported values are: s3, filesystem, swift and django. backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend() elif backend_setting == "filesystem": return filesystem.Backend() elif backend_setting == "swift": return swift.Backend() elif backend_setting == "django": return django_storage.Backend() else: raise ValueError("Invalid ORA2_FILEUPLOAD_BACKEND setting value: %s" % backend_setting)
""" File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): - # Use S3 backend by default (current behaviour) + # .. setting_name: ORA2_FILEUPLOAD_BACKEND + # .. setting_default: s3 + # .. setting_description: The backend used to upload the ora2 submissions attachments + # the supported values are: s3, filesystem, swift and django. backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend() elif backend_setting == "filesystem": return filesystem.Backend() elif backend_setting == "swift": return swift.Backend() elif backend_setting == "django": return django_storage.Backend() else: raise ValueError("Invalid ORA2_FILEUPLOAD_BACKEND setting value: %s" % backend_setting)
61f06da13bef77f576a0c2dea77febf0d2d4b6fb
subl.py
subl.py
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if file != None and not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
Allow autocomplete on non-persisted swift files
Allow autocomplete on non-persisted swift files
Python
mit
Dan2552/SourceKittenSubl,Dan2552/SourceKittenSubl,Dan2552/SourceKittenSubl
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() + - if not file.endswith(".swift"): + if file != None and not file.endswith(".swift"): return None + project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
Allow autocomplete on non-persisted swift files
## Code Before: from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) ## Instruction: Allow autocomplete on non-persisted swift files ## Code After: from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if file != None and not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() + - if not file.endswith(".swift"): + if file != None and not file.endswith(".swift"): ? +++++++++++++++++ return None + project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
5f113ffd768431991f87cea1f5f804a25a1777d3
frappe/patches/v13_0/replace_old_data_import.py
frappe/patches/v13_0/replace_old_data_import.py
from __future__ import unicode_literals import frappe def execute(): frappe.db.sql( """INSERT INTO `tabData Import Legacy` SELECT * FROM `tabData Import`""" ) frappe.db.commit() frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`") frappe.reload_doc("core", "doctype", "data_import") frappe.get_doc("DocType", "Data Import").on_update()
from __future__ import unicode_literals import frappe def execute(): frappe.rename_doc('DocType', 'Data Import', 'Data Import Legacy') frappe.db.commit() frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`") frappe.reload_doc("core", "doctype", "data_import") frappe.get_doc("DocType", "Data Import").on_update()
Use rename doc instead of manually moving the data
fix: Use rename doc instead of manually moving the data
Python
mit
StrellaGroup/frappe,saurabh6790/frappe,mhbu50/frappe,yashodhank/frappe,frappe/frappe,yashodhank/frappe,almeidapaulopt/frappe,yashodhank/frappe,frappe/frappe,mhbu50/frappe,almeidapaulopt/frappe,adityahase/frappe,saurabh6790/frappe,frappe/frappe,adityahase/frappe,mhbu50/frappe,adityahase/frappe,almeidapaulopt/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,adityahase/frappe,StrellaGroup/frappe,saurabh6790/frappe,saurabh6790/frappe,StrellaGroup/frappe
from __future__ import unicode_literals import frappe def execute(): + frappe.rename_doc('DocType', 'Data Import', 'Data Import Legacy') - frappe.db.sql( - """INSERT INTO `tabData Import Legacy` SELECT * FROM `tabData Import`""" - ) frappe.db.commit() frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`") frappe.reload_doc("core", "doctype", "data_import") frappe.get_doc("DocType", "Data Import").on_update()
Use rename doc instead of manually moving the data
## Code Before: from __future__ import unicode_literals import frappe def execute(): frappe.db.sql( """INSERT INTO `tabData Import Legacy` SELECT * FROM `tabData Import`""" ) frappe.db.commit() frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`") frappe.reload_doc("core", "doctype", "data_import") frappe.get_doc("DocType", "Data Import").on_update() ## Instruction: Use rename doc instead of manually moving the data ## Code After: from __future__ import unicode_literals import frappe def execute(): frappe.rename_doc('DocType', 'Data Import', 'Data Import Legacy') frappe.db.commit() frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`") frappe.reload_doc("core", "doctype", "data_import") frappe.get_doc("DocType", "Data Import").on_update()
from __future__ import unicode_literals import frappe def execute(): + frappe.rename_doc('DocType', 'Data Import', 'Data Import Legacy') - frappe.db.sql( - """INSERT INTO `tabData Import Legacy` SELECT * FROM `tabData Import`""" - ) frappe.db.commit() frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`") frappe.reload_doc("core", "doctype", "data_import") frappe.get_doc("DocType", "Data Import").on_update()
150dad224dd985762714b73e9a91d084efb11e06
ob_pipelines/sample.py
ob_pipelines/sample.py
import os from luigi import Parameter from ob_airtable import get_record_by_name, get_record AIRTABLE_EXPT_TABLE = 'Genomics%20Expt' AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample' S3_BUCKET = os.environ.get('S3_BUCKET') def get_samples(expt_id): expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE) sample_keys = expt['fields']['Genomics samples'] for sample_key in sample_keys: sample = get_record(sample_key, AIRTABLE_SAMPLE_TABLE) yield sample['fields']['Name'] class Sample(object): sample_id = Parameter() @property def sample(self): if not hasattr(self, '_sample'): self._sample = get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields'] return self._sample @property def sample_folder(self): return '{expt}/{sample}'.format( bucket=S3_BUCKET, expt = self.experiment['Name'], sample=self.sample_id) @property def experiment(self): if not hasattr(self, '_experiment'): expt_key = self.sample['Experiment'][0] self._experiment = get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields'] return self._experiment
import os from luigi import Parameter from ob_airtable import AirtableClient AIRTABLE_EXPT_TABLE = 'Genomics%20Expt' AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample' S3_BUCKET = os.environ.get('S3_BUCKET') client = AirtableClient() def get_samples(expt_id): expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE) sample_keys = expt['fields']['Genomics samples'] for sample_key in sample_keys: sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE) yield sample['fields']['Name'] class Sample(object): sample_id = Parameter() @property def sample(self): if not hasattr(self, '_sample'): self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields'] return self._sample @property def sample_folder(self): return '{expt}/{sample}'.format( bucket=S3_BUCKET, expt = self.experiment['Name'], sample=self.sample_id) @property def experiment(self): if not hasattr(self, '_experiment'): expt_key = self.sample['Experiment'][0] self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields'] return self._experiment
Update to match changes in ob-airtable
Update to match changes in ob-airtable
Python
apache-2.0
outlierbio/ob-pipelines,outlierbio/ob-pipelines,outlierbio/ob-pipelines
import os from luigi import Parameter - from ob_airtable import get_record_by_name, get_record + from ob_airtable import AirtableClient AIRTABLE_EXPT_TABLE = 'Genomics%20Expt' AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample' S3_BUCKET = os.environ.get('S3_BUCKET') + client = AirtableClient() def get_samples(expt_id): - expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE) + expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE) sample_keys = expt['fields']['Genomics samples'] for sample_key in sample_keys: - sample = get_record(sample_key, AIRTABLE_SAMPLE_TABLE) + sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE) yield sample['fields']['Name'] class Sample(object): sample_id = Parameter() @property def sample(self): if not hasattr(self, '_sample'): - self._sample = get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields'] + self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields'] return self._sample @property def sample_folder(self): return '{expt}/{sample}'.format( bucket=S3_BUCKET, expt = self.experiment['Name'], sample=self.sample_id) @property def experiment(self): if not hasattr(self, '_experiment'): expt_key = self.sample['Experiment'][0] - self._experiment = get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields'] + self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields'] return self._experiment
Update to match changes in ob-airtable
## Code Before: import os from luigi import Parameter from ob_airtable import get_record_by_name, get_record AIRTABLE_EXPT_TABLE = 'Genomics%20Expt' AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample' S3_BUCKET = os.environ.get('S3_BUCKET') def get_samples(expt_id): expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE) sample_keys = expt['fields']['Genomics samples'] for sample_key in sample_keys: sample = get_record(sample_key, AIRTABLE_SAMPLE_TABLE) yield sample['fields']['Name'] class Sample(object): sample_id = Parameter() @property def sample(self): if not hasattr(self, '_sample'): self._sample = get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields'] return self._sample @property def sample_folder(self): return '{expt}/{sample}'.format( bucket=S3_BUCKET, expt = self.experiment['Name'], sample=self.sample_id) @property def experiment(self): if not hasattr(self, '_experiment'): expt_key = self.sample['Experiment'][0] self._experiment = get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields'] return self._experiment ## Instruction: Update to match changes in ob-airtable ## Code After: import os from luigi import Parameter from ob_airtable import AirtableClient AIRTABLE_EXPT_TABLE = 'Genomics%20Expt' AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample' S3_BUCKET = os.environ.get('S3_BUCKET') client = AirtableClient() def get_samples(expt_id): expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE) sample_keys = expt['fields']['Genomics samples'] for sample_key in sample_keys: sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE) yield sample['fields']['Name'] class Sample(object): sample_id = Parameter() @property def sample(self): if not hasattr(self, '_sample'): self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields'] return self._sample @property def sample_folder(self): return '{expt}/{sample}'.format( bucket=S3_BUCKET, expt = self.experiment['Name'], sample=self.sample_id) @property def experiment(self): if not hasattr(self, '_experiment'): expt_key = self.sample['Experiment'][0] self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields'] return self._experiment
import os from luigi import Parameter - from ob_airtable import get_record_by_name, get_record + from ob_airtable import AirtableClient AIRTABLE_EXPT_TABLE = 'Genomics%20Expt' AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample' S3_BUCKET = os.environ.get('S3_BUCKET') + client = AirtableClient() def get_samples(expt_id): - expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE) + expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE) ? +++++++ sample_keys = expt['fields']['Genomics samples'] for sample_key in sample_keys: - sample = get_record(sample_key, AIRTABLE_SAMPLE_TABLE) + sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE) ? +++++++ yield sample['fields']['Name'] class Sample(object): sample_id = Parameter() @property def sample(self): if not hasattr(self, '_sample'): - self._sample = get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields'] + self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields'] ? +++++++ return self._sample @property def sample_folder(self): return '{expt}/{sample}'.format( bucket=S3_BUCKET, expt = self.experiment['Name'], sample=self.sample_id) @property def experiment(self): if not hasattr(self, '_experiment'): expt_key = self.sample['Experiment'][0] - self._experiment = get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields'] + self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields'] ? +++++++ return self._experiment
aa86dfda0b92ac99c86053db7fb43bd8cecccc83
kpi/interfaces/sync_backend_media.py
kpi/interfaces/sync_backend_media.py
class SyncBackendMediaInterface: """ This interface defines required properties and methods of objects passed to deployment back-end class on media synchronization. """ @property def backend_data_value(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def backend_uniqid(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') def delete(self, **kwargs): raise NotImplementedError('This method should be implemented in ' 'subclasses') @property def deleted_at(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def filename(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def hash(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def is_remote_url(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def mimetype(self): raise NotImplementedError('This property should be implemented in ' 'subclasses')
from kpi.exceptions import AbstractMethodError, AbstractPropertyError class SyncBackendMediaInterface: """ This interface defines required properties and methods of objects passed to deployment back-end class on media synchronization. """ @property def backend_data_value(self): raise AbstractPropertyError @property def backend_uniqid(self): raise AbstractPropertyError def delete(self, **kwargs): raise AbstractMethodError @property def deleted_at(self): raise AbstractPropertyError @property def filename(self): raise AbstractPropertyError @property def hash(self): raise AbstractPropertyError @property def is_remote_url(self): raise AbstractPropertyError @property def mimetype(self): raise AbstractPropertyError
Use new exceptions: AbstractMethodError, AbstractPropertyError
Use new exceptions: AbstractMethodError, AbstractPropertyError
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
+ from kpi.exceptions import AbstractMethodError, AbstractPropertyError + class SyncBackendMediaInterface: """ This interface defines required properties and methods of objects passed to deployment back-end class on media synchronization. """ @property def backend_data_value(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def backend_uniqid(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') def delete(self, **kwargs): + raise AbstractMethodError - raise NotImplementedError('This method should be implemented in ' - 'subclasses') @property def deleted_at(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def filename(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def hash(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def is_remote_url(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def mimetype(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses')
Use new exceptions: AbstractMethodError, AbstractPropertyError
## Code Before: class SyncBackendMediaInterface: """ This interface defines required properties and methods of objects passed to deployment back-end class on media synchronization. """ @property def backend_data_value(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def backend_uniqid(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') def delete(self, **kwargs): raise NotImplementedError('This method should be implemented in ' 'subclasses') @property def deleted_at(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def filename(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def hash(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def is_remote_url(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') @property def mimetype(self): raise NotImplementedError('This property should be implemented in ' 'subclasses') ## Instruction: Use new exceptions: AbstractMethodError, AbstractPropertyError ## Code After: from kpi.exceptions import AbstractMethodError, AbstractPropertyError class SyncBackendMediaInterface: """ This interface defines required properties and methods of objects passed to deployment back-end class on media synchronization. """ @property def backend_data_value(self): raise AbstractPropertyError @property def backend_uniqid(self): raise AbstractPropertyError def delete(self, **kwargs): raise AbstractMethodError @property def deleted_at(self): raise AbstractPropertyError @property def filename(self): raise AbstractPropertyError @property def hash(self): raise AbstractPropertyError @property def is_remote_url(self): raise AbstractPropertyError @property def mimetype(self): raise AbstractPropertyError
+ from kpi.exceptions import AbstractMethodError, AbstractPropertyError + class SyncBackendMediaInterface: """ This interface defines required properties and methods of objects passed to deployment back-end class on media synchronization. """ @property def backend_data_value(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def backend_uniqid(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') def delete(self, **kwargs): + raise AbstractMethodError - raise NotImplementedError('This method should be implemented in ' - 'subclasses') @property def deleted_at(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def filename(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def hash(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def is_remote_url(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses') @property def mimetype(self): + raise AbstractPropertyError - raise NotImplementedError('This property should be implemented in ' - 'subclasses')
8fa895189696e83e6120875886bc8888e0509195
bin/confluent-server.py
bin/confluent-server.py
import sys import os path = os.path.dirname(os.path.realpath(__file__)) path = os.path.realpath(os.path.join(path, '..')) sys.path.append(path) from confluent import main main.run()
import sys import os path = os.path.dirname(os.path.realpath(__file__)) path = os.path.realpath(os.path.join(path, '..')) sys.path.append(path) from confluent import main #import cProfile #import time #p = cProfile.Profile(time.clock) #p.enable() #try: main.run() #except: # pass #p.disable() #p.print_stats(sort='cumulative') #p.print_stats(sort='time')
Put comments in to hint a decent strategy to profile runtime performance
Put comments in to hint a decent strategy to profile runtime performance To do performance optimization in this sort of application, this is about as well as I have been able to manage in python. I will say perl with NYTProf seems to be significantly better for data, but this is servicable. I tried yappi, but it goes wildly inaccurate with this codebase. Because of the eventlet plumbing, cProfile is still pretty misleading. Best strategy seems to be review cumulative time with a healthy grain of salt around the top items until you get down to info that makes sense. For example, trampoline unfairly gets a great deal of the 'blame' by taking on nearly all the activity. internal time seems to miss a great deal of important information.
Python
apache-2.0
chenglch/confluent,whowutwut/confluent,jufm/confluent,jufm/confluent,michaelfardu/thinkconfluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent,whowutwut/confluent,chenglch/confluent,michaelfardu/thinkconfluent,jufm/confluent,michaelfardu/thinkconfluent,xcat2/confluent,xcat2/confluent,xcat2/confluent,jjohnson42/confluent,jufm/confluent,chenglch/confluent,whowutwut/confluent,whowutwut/confluent,michaelfardu/thinkconfluent,chenglch/confluent,jjohnson42/confluent,xcat2/confluent,jjohnson42/confluent,jufm/confluent,chenglch/confluent,michaelfardu/thinkconfluent
import sys import os path = os.path.dirname(os.path.realpath(__file__)) path = os.path.realpath(os.path.join(path, '..')) sys.path.append(path) from confluent import main + #import cProfile + #import time + #p = cProfile.Profile(time.clock) + #p.enable() + #try: main.run() + #except: + # pass + #p.disable() + #p.print_stats(sort='cumulative') + #p.print_stats(sort='time')
Put comments in to hint a decent strategy to profile runtime performance
## Code Before: import sys import os path = os.path.dirname(os.path.realpath(__file__)) path = os.path.realpath(os.path.join(path, '..')) sys.path.append(path) from confluent import main main.run() ## Instruction: Put comments in to hint a decent strategy to profile runtime performance ## Code After: import sys import os path = os.path.dirname(os.path.realpath(__file__)) path = os.path.realpath(os.path.join(path, '..')) sys.path.append(path) from confluent import main #import cProfile #import time #p = cProfile.Profile(time.clock) #p.enable() #try: main.run() #except: # pass #p.disable() #p.print_stats(sort='cumulative') #p.print_stats(sort='time')
import sys import os path = os.path.dirname(os.path.realpath(__file__)) path = os.path.realpath(os.path.join(path, '..')) sys.path.append(path) from confluent import main + #import cProfile + #import time + #p = cProfile.Profile(time.clock) + #p.enable() + #try: main.run() + #except: + # pass + #p.disable() + #p.print_stats(sort='cumulative') + #p.print_stats(sort='time')
06ec0a7f0a6a53fddfb2038b0ae8cc1bad2c8511
blankspot/node_registration/models.py
blankspot/node_registration/models.py
from django.db import models class Contact(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) def __unicode__(self): return (self.nick) def get_absolute_url(self): return reverse('contact-detail', kwargs={'pk': self.pk}) class Position(models.Model): contact = models.ForeignKey('Contact') street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation.
Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation.
Python
agpl-3.0
frlan/blankspot
from django.db import models - class Contact(models.Model): + class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) - - def __unicode__(self): - return (self.nick) - - def get_absolute_url(self): - return reverse('contact-detail', kwargs={'pk': self.pk}) - - class Position(models.Model): - contact = models.ForeignKey('Contact') street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation.
## Code Before: from django.db import models class Contact(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) def __unicode__(self): return (self.nick) def get_absolute_url(self): return reverse('contact-detail', kwargs={'pk': self.pk}) class Position(models.Model): contact = models.ForeignKey('Contact') street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk}) ## Instruction: Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation. ## Code After: from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
from django.db import models - class Contact(models.Model): ? ^ ---- + class Position(models.Model): ? ^^^^^^ first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) - - def __unicode__(self): - return (self.nick) - - def get_absolute_url(self): - return reverse('contact-detail', kwargs={'pk': self.pk}) - - class Position(models.Model): - contact = models.ForeignKey('Contact') street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
b352c3e1f5e8812d29f2e8a1bca807bea5da8cc4
test/test_hx_launcher.py
test/test_hx_launcher.py
import pytest_twisted from hendrix.ux import main from hendrix.options import HendrixOptionParser def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
from hendrix.options import HendrixOptionParser from hendrix.ux import main def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
Test for the hx launcher.
Test for the hx launcher.
Python
mit
hangarunderground/hendrix,hendrix/hendrix,hangarunderground/hendrix,hendrix/hendrix,jMyles/hendrix,hendrix/hendrix,jMyles/hendrix,hangarunderground/hendrix,hangarunderground/hendrix,jMyles/hendrix
+ from hendrix.options import HendrixOptionParser - import pytest_twisted - from hendrix.ux import main - from hendrix.options import HendrixOptionParser def test_no_arguments_gives_help_text(mocker): - class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
Test for the hx launcher.
## Code Before: import pytest_twisted from hendrix.ux import main from hendrix.options import HendrixOptionParser def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([]) ## Instruction: Test for the hx launcher. ## Code After: from hendrix.options import HendrixOptionParser from hendrix.ux import main def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
+ from hendrix.options import HendrixOptionParser - import pytest_twisted - from hendrix.ux import main - from hendrix.options import HendrixOptionParser def test_no_arguments_gives_help_text(mocker): - class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
0ee942eaffc2a60b87c21eeec75f01eb1a50b8e0
tests/demo_project/manage.py
tests/demo_project/manage.py
import os import sys from pathlib import Path if __name__ == "__main__": # We add ourselves into the python path, so we can find # the package later. demo_root =os.path.dirname(os.path.abspath(__file__)) crud_install = os.path.dirname(os.path.dirname(demo_root)) sys.path.insert(0, crud_install) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
import os import sys from pathlib import Path if __name__ == "__main__": # We add ourselves into the python path, so we can find # the package later. demo_root =os.path.dirname(os.path.abspath(__file__)) crud_install = os.path.dirname(os.path.dirname(demo_root)) sys.path.insert(0, crud_install) sys.path.insert(0, demo_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
Make sure the demo project is in the pythonpath
Make sure the demo project is in the pythonpath
Python
bsd-3-clause
oscarmlage/django-cruds-adminlte,oscarmlage/django-cruds-adminlte,oscarmlage/django-cruds-adminlte
import os import sys from pathlib import Path if __name__ == "__main__": # We add ourselves into the python path, so we can find # the package later. demo_root =os.path.dirname(os.path.abspath(__file__)) crud_install = os.path.dirname(os.path.dirname(demo_root)) sys.path.insert(0, crud_install) + sys.path.insert(0, demo_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
Make sure the demo project is in the pythonpath
## Code Before: import os import sys from pathlib import Path if __name__ == "__main__": # We add ourselves into the python path, so we can find # the package later. demo_root =os.path.dirname(os.path.abspath(__file__)) crud_install = os.path.dirname(os.path.dirname(demo_root)) sys.path.insert(0, crud_install) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) ## Instruction: Make sure the demo project is in the pythonpath ## Code After: import os import sys from pathlib import Path if __name__ == "__main__": # We add ourselves into the python path, so we can find # the package later. demo_root =os.path.dirname(os.path.abspath(__file__)) crud_install = os.path.dirname(os.path.dirname(demo_root)) sys.path.insert(0, crud_install) sys.path.insert(0, demo_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
import os import sys from pathlib import Path if __name__ == "__main__": # We add ourselves into the python path, so we can find # the package later. demo_root =os.path.dirname(os.path.abspath(__file__)) crud_install = os.path.dirname(os.path.dirname(demo_root)) sys.path.insert(0, crud_install) + sys.path.insert(0, demo_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
fc6042cf57752ca139c52889ec5e00c02b618d0d
setup.py
setup.py
from distutils.core import setup, Command class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) with open('README.rst') as file: long_description = file.read() setup( name='webpay', packages=['webpay'], version='0.1.0', author='webpay', author_email='administrators@webpay.jp', url='https://github.com/webpay/webpay-python', description='WebPay Python bindings', cmdclass={'test': PyTest}, long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules' ], requires=[ 'requests (== 2.0.1)' ] )
from distutils.core import setup, Command class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) with open('README.rst') as file: long_description = file.read() setup( name='webpay', packages=['webpay', 'webpay.api', 'webpay.model'], version='0.1.0', author='webpay', author_email='administrators@webpay.jp', url='https://github.com/webpay/webpay-python', description='WebPay Python bindings', cmdclass={'test': PyTest}, long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules' ], requires=[ 'requests (== 2.0.1)' ] )
Add api and model to packages
Add api and model to packages
Python
mit
yamaneko1212/webpay-python
from distutils.core import setup, Command class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) with open('README.rst') as file: long_description = file.read() setup( name='webpay', - packages=['webpay'], + packages=['webpay', 'webpay.api', 'webpay.model'], version='0.1.0', author='webpay', author_email='administrators@webpay.jp', url='https://github.com/webpay/webpay-python', description='WebPay Python bindings', cmdclass={'test': PyTest}, long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules' ], requires=[ 'requests (== 2.0.1)' ] )
Add api and model to packages
## Code Before: from distutils.core import setup, Command class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) with open('README.rst') as file: long_description = file.read() setup( name='webpay', packages=['webpay'], version='0.1.0', author='webpay', author_email='administrators@webpay.jp', url='https://github.com/webpay/webpay-python', description='WebPay Python bindings', cmdclass={'test': PyTest}, long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules' ], requires=[ 'requests (== 2.0.1)' ] ) ## Instruction: Add api and model to packages ## Code After: from distutils.core import setup, Command class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) with open('README.rst') as file: long_description = file.read() setup( name='webpay', packages=['webpay', 'webpay.api', 'webpay.model'], version='0.1.0', author='webpay', author_email='administrators@webpay.jp', url='https://github.com/webpay/webpay-python', description='WebPay Python bindings', cmdclass={'test': PyTest}, long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules' ], requires=[ 'requests (== 2.0.1)' ] )
from distutils.core import setup, Command class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) with open('README.rst') as file: long_description = file.read() setup( name='webpay', - packages=['webpay'], + packages=['webpay', 'webpay.api', 'webpay.model'], version='0.1.0', author='webpay', author_email='administrators@webpay.jp', url='https://github.com/webpay/webpay-python', description='WebPay Python bindings', cmdclass={'test': PyTest}, long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules' ], requires=[ 'requests (== 2.0.1)' ] )
c5496fddccffd2f16c0b4a140506b9d577d50b61
eventlog/models.py
eventlog/models.py
from django.conf import settings from django.db import models from django.utils import timezone import jsonfield from .signals import event_logged class Log(models.Model): user = models.ForeignKey( getattr(settings, "AUTH_USER_MODEL", "auth.User"), null=True, on_delete=models.SET_NULL ) timestamp = models.DateTimeField(default=timezone.now, db_index=True) action = models.CharField(max_length=50, db_index=True) extra = jsonfield.JSONField() class Meta: ordering = ["-timestamp"] def log(user, action, extra=None): if (user is not None and not user.is_authenticated()): user = None if extra is None: extra = {} event = Log.objects.create(user=user, action=action, extra=extra) event_logged.send(sender=Log, event=event) return event
from django.conf import settings from django.db import models from django.utils import timezone import jsonfield from .signals import event_logged class Log(models.Model): user = models.ForeignKey( getattr(settings, "AUTH_USER_MODEL", "auth.User"), null=True, on_delete=models.SET_NULL ) timestamp = models.DateTimeField(default=timezone.now, db_index=True) action = models.CharField(max_length=50, db_index=True) extra = jsonfield.JSONField() @property def template_fragment_name(self): return "eventlog/{}.html".format(self.action.lower()) class Meta: ordering = ["-timestamp"] def log(user, action, extra=None): if (user is not None and not user.is_authenticated()): user = None if extra is None: extra = {} event = Log.objects.create(user=user, action=action, extra=extra) event_logged.send(sender=Log, event=event) return event
Add property to provide template fragment name
Add property to provide template fragment name
Python
mit
jawed123/pinax-eventlog,pinax/pinax-eventlog,KleeTaurus/pinax-eventlog,rosscdh/pinax-eventlog
from django.conf import settings from django.db import models from django.utils import timezone import jsonfield from .signals import event_logged class Log(models.Model): user = models.ForeignKey( getattr(settings, "AUTH_USER_MODEL", "auth.User"), null=True, on_delete=models.SET_NULL ) timestamp = models.DateTimeField(default=timezone.now, db_index=True) action = models.CharField(max_length=50, db_index=True) extra = jsonfield.JSONField() + @property + def template_fragment_name(self): + return "eventlog/{}.html".format(self.action.lower()) + class Meta: ordering = ["-timestamp"] def log(user, action, extra=None): if (user is not None and not user.is_authenticated()): user = None if extra is None: extra = {} event = Log.objects.create(user=user, action=action, extra=extra) event_logged.send(sender=Log, event=event) return event
Add property to provide template fragment name
## Code Before: from django.conf import settings from django.db import models from django.utils import timezone import jsonfield from .signals import event_logged class Log(models.Model): user = models.ForeignKey( getattr(settings, "AUTH_USER_MODEL", "auth.User"), null=True, on_delete=models.SET_NULL ) timestamp = models.DateTimeField(default=timezone.now, db_index=True) action = models.CharField(max_length=50, db_index=True) extra = jsonfield.JSONField() class Meta: ordering = ["-timestamp"] def log(user, action, extra=None): if (user is not None and not user.is_authenticated()): user = None if extra is None: extra = {} event = Log.objects.create(user=user, action=action, extra=extra) event_logged.send(sender=Log, event=event) return event ## Instruction: Add property to provide template fragment name ## Code After: from django.conf import settings from django.db import models from django.utils import timezone import jsonfield from .signals import event_logged class Log(models.Model): user = models.ForeignKey( getattr(settings, "AUTH_USER_MODEL", "auth.User"), null=True, on_delete=models.SET_NULL ) timestamp = models.DateTimeField(default=timezone.now, db_index=True) action = models.CharField(max_length=50, db_index=True) extra = jsonfield.JSONField() @property def template_fragment_name(self): return "eventlog/{}.html".format(self.action.lower()) class Meta: ordering = ["-timestamp"] def log(user, action, extra=None): if (user is not None and not user.is_authenticated()): user = None if extra is None: extra = {} event = Log.objects.create(user=user, action=action, extra=extra) event_logged.send(sender=Log, event=event) return event
from django.conf import settings from django.db import models from django.utils import timezone import jsonfield from .signals import event_logged class Log(models.Model): user = models.ForeignKey( getattr(settings, "AUTH_USER_MODEL", "auth.User"), null=True, on_delete=models.SET_NULL ) timestamp = models.DateTimeField(default=timezone.now, db_index=True) action = models.CharField(max_length=50, db_index=True) extra = jsonfield.JSONField() + @property + def template_fragment_name(self): + return "eventlog/{}.html".format(self.action.lower()) + class Meta: ordering = ["-timestamp"] def log(user, action, extra=None): if (user is not None and not user.is_authenticated()): user = None if extra is None: extra = {} event = Log.objects.create(user=user, action=action, extra=extra) event_logged.send(sender=Log, event=event) return event
f68808dc85b2bb0ea8fb0d7de4669099740cdb61
mesoblog/models.py
mesoblog/models.py
from django.db import models # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" # Article model represents one article in the blog. class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) contents = models.TextField() date_published = models.DateTimeField() published = models.BooleanField() categories = models.ManyToManyField(Category) def __str__(self): return self.title+" ["+str(self.id)+"]"
from django.db import models # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" # Article model represents one article in the blog. class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) contents = models.TextField() date_published = models.DateTimeField() published = models.BooleanField() primary_category = models.ForeignKey(Category, related_name='+') categories = models.ManyToManyField(Category) def __str__(self): return self.title+" ["+str(self.id)+"]"
Add a primary category which will decide which category is shown as current in the chrome for this article.
Add a primary category which will decide which category is shown as current in the chrome for this article. TODO: Enforce including the primary category as one of the categories for the article, both in UI and server side.
Python
mit
grundleborg/mesosphere
from django.db import models # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" # Article model represents one article in the blog. class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) contents = models.TextField() date_published = models.DateTimeField() published = models.BooleanField() + primary_category = models.ForeignKey(Category, related_name='+') categories = models.ManyToManyField(Category) def __str__(self): return self.title+" ["+str(self.id)+"]"
Add a primary category which will decide which category is shown as current in the chrome for this article.
## Code Before: from django.db import models # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" # Article model represents one article in the blog. class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) contents = models.TextField() date_published = models.DateTimeField() published = models.BooleanField() categories = models.ManyToManyField(Category) def __str__(self): return self.title+" ["+str(self.id)+"]" ## Instruction: Add a primary category which will decide which category is shown as current in the chrome for this article. ## Code After: from django.db import models # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" # Article model represents one article in the blog. class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) contents = models.TextField() date_published = models.DateTimeField() published = models.BooleanField() primary_category = models.ForeignKey(Category, related_name='+') categories = models.ManyToManyField(Category) def __str__(self): return self.title+" ["+str(self.id)+"]"
from django.db import models # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" # Article model represents one article in the blog. class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) contents = models.TextField() date_published = models.DateTimeField() published = models.BooleanField() + primary_category = models.ForeignKey(Category, related_name='+') categories = models.ManyToManyField(Category) def __str__(self): return self.title+" ["+str(self.id)+"]"
4ecd19f7a1a36a424021e42c64fb273d7591ef1f
haas/plugin_manager.py
haas/plugin_manager.py
from __future__ import absolute_import, unicode_literals from .utils import find_module_by_name class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None: return None try: module, module_attributes = find_module_by_name(class_spec) except ImportError: return None if len(module_attributes) != 1: return None klass = getattr(module, module_attributes[0], None) if klass is None: return None return klass def load_plugin(self, class_spec): klass = self.load_plugin_class(class_spec) if klass is None: return None return klass()
from __future__ import absolute_import, unicode_literals import logging from .utils import get_module_by_name logger = logging.getLogger(__name__) class PluginError(Exception): pass class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None or '.' not in class_spec: msg = 'Malformed plugin factory specification {0!r}'.format( class_spec) logger.error(msg) raise PluginError(msg) module_name, factory_name = class_spec.rsplit('.', 1) try: module = get_module_by_name(module_name) except ImportError: msg = 'Unable to import {0!r}'.format(class_spec) logger.exception(msg) raise PluginError(msg) try: klass = getattr(module, factory_name) except AttributeError: msg = 'Module %r has no attribute {0!r}'.format( module.__name__, factory_name) logger.error(msg) raise PluginError(msg) return klass def load_plugin(self, class_spec): if class_spec is None: return None klass = self.load_plugin_class(class_spec) return klass()
Add logging and raise exceptions when loading plugin factories
Add logging and raise exceptions when loading plugin factories
Python
bsd-3-clause
sjagoe/haas,itziakos/haas,sjagoe/haas,scalative/haas,itziakos/haas,scalative/haas
from __future__ import absolute_import, unicode_literals + import logging + - from .utils import find_module_by_name + from .utils import get_module_by_name + + logger = logging.getLogger(__name__) + + + class PluginError(Exception): + + pass class PluginManager(object): def load_plugin_class(self, class_spec): - if class_spec is None: - return None + if class_spec is None or '.' not in class_spec: + msg = 'Malformed plugin factory specification {0!r}'.format( + class_spec) + logger.error(msg) + raise PluginError(msg) + module_name, factory_name = class_spec.rsplit('.', 1) try: - module, module_attributes = find_module_by_name(class_spec) + module = get_module_by_name(module_name) except ImportError: - return None - if len(module_attributes) != 1: - return None - klass = getattr(module, module_attributes[0], None) - if klass is None: - return None + msg = 'Unable to import {0!r}'.format(class_spec) + logger.exception(msg) + raise PluginError(msg) + try: + klass = getattr(module, factory_name) + except AttributeError: + msg = 'Module %r has no attribute {0!r}'.format( + module.__name__, factory_name) + logger.error(msg) + raise PluginError(msg) return klass def load_plugin(self, class_spec): + if class_spec is None: + return None klass = self.load_plugin_class(class_spec) - if klass is None: - return None return klass()
Add logging and raise exceptions when loading plugin factories
## Code Before: from __future__ import absolute_import, unicode_literals from .utils import find_module_by_name class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None: return None try: module, module_attributes = find_module_by_name(class_spec) except ImportError: return None if len(module_attributes) != 1: return None klass = getattr(module, module_attributes[0], None) if klass is None: return None return klass def load_plugin(self, class_spec): klass = self.load_plugin_class(class_spec) if klass is None: return None return klass() ## Instruction: Add logging and raise exceptions when loading plugin factories ## Code After: from __future__ import absolute_import, unicode_literals import logging from .utils import get_module_by_name logger = logging.getLogger(__name__) class PluginError(Exception): pass class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None or '.' not in class_spec: msg = 'Malformed plugin factory specification {0!r}'.format( class_spec) logger.error(msg) raise PluginError(msg) module_name, factory_name = class_spec.rsplit('.', 1) try: module = get_module_by_name(module_name) except ImportError: msg = 'Unable to import {0!r}'.format(class_spec) logger.exception(msg) raise PluginError(msg) try: klass = getattr(module, factory_name) except AttributeError: msg = 'Module %r has no attribute {0!r}'.format( module.__name__, factory_name) logger.error(msg) raise PluginError(msg) return klass def load_plugin(self, class_spec): if class_spec is None: return None klass = self.load_plugin_class(class_spec) return klass()
from __future__ import absolute_import, unicode_literals + import logging + - from .utils import find_module_by_name ? ^^^^ + from .utils import get_module_by_name ? ^^^ + + logger = logging.getLogger(__name__) + + + class PluginError(Exception): + + pass class PluginManager(object): def load_plugin_class(self, class_spec): - if class_spec is None: - return None + if class_spec is None or '.' not in class_spec: + msg = 'Malformed plugin factory specification {0!r}'.format( + class_spec) + logger.error(msg) + raise PluginError(msg) + module_name, factory_name = class_spec.rsplit('.', 1) try: - module, module_attributes = find_module_by_name(class_spec) + module = get_module_by_name(module_name) except ImportError: - return None - if len(module_attributes) != 1: - return None - klass = getattr(module, module_attributes[0], None) - if klass is None: - return None + msg = 'Unable to import {0!r}'.format(class_spec) + logger.exception(msg) + raise PluginError(msg) + try: + klass = getattr(module, factory_name) + except AttributeError: + msg = 'Module %r has no attribute {0!r}'.format( + module.__name__, factory_name) + logger.error(msg) + raise PluginError(msg) return klass def load_plugin(self, class_spec): + if class_spec is None: + return None klass = self.load_plugin_class(class_spec) - if klass is None: - return None return klass()
8a25b5f76ffe5b32f6c1a8d691c3d78ce3fb07c8
fluent_contents/utils/search.py
fluent_contents/utils/search.py
from django.utils.encoding import force_unicode from django.utils.html import strip_tags import six def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking for just the PluginHtmlField here. if value and isinstance(value, six.string_types): value = get_cleaned_string(value) values.append(value) return values def get_search_text(contentitem): bits = get_search_field_values(contentitem) return clean_join(u" ", bits) def get_cleaned_string(data): """ Cleanup a string/HTML output to consist of words only. """ return strip_tags(force_unicode(data)) def clean_join(separator, iterable): """ Filters out iterable to only join non empty items. """ return separator.join(filter(None, iterable)) #def get_cleaned_bits(data): # return smart_split(get_cleaned_bits(data))
from django.utils.encoding import force_text from django.utils.html import strip_tags import six def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking for just the PluginHtmlField here. if value and isinstance(value, six.string_types): value = get_cleaned_string(value) values.append(value) return values def get_search_text(contentitem): bits = get_search_field_values(contentitem) return clean_join(u" ", bits) def get_cleaned_string(data): """ Cleanup a string/HTML output to consist of words only. """ return strip_tags(force_text(data)) def clean_join(separator, iterable): """ Filters out iterable to only join non empty items. """ return separator.join(filter(None, iterable)) #def get_cleaned_bits(data): # return smart_split(get_cleaned_bits(data))
Fix force_unicode for Python 3, use force_text()
Fix force_unicode for Python 3, use force_text()
Python
apache-2.0
django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents
- from django.utils.encoding import force_unicode + from django.utils.encoding import force_text from django.utils.html import strip_tags import six def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking for just the PluginHtmlField here. if value and isinstance(value, six.string_types): value = get_cleaned_string(value) values.append(value) return values def get_search_text(contentitem): bits = get_search_field_values(contentitem) return clean_join(u" ", bits) def get_cleaned_string(data): """ Cleanup a string/HTML output to consist of words only. """ - return strip_tags(force_unicode(data)) + return strip_tags(force_text(data)) def clean_join(separator, iterable): """ Filters out iterable to only join non empty items. """ return separator.join(filter(None, iterable)) #def get_cleaned_bits(data): # return smart_split(get_cleaned_bits(data))
Fix force_unicode for Python 3, use force_text()
## Code Before: from django.utils.encoding import force_unicode from django.utils.html import strip_tags import six def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking for just the PluginHtmlField here. if value and isinstance(value, six.string_types): value = get_cleaned_string(value) values.append(value) return values def get_search_text(contentitem): bits = get_search_field_values(contentitem) return clean_join(u" ", bits) def get_cleaned_string(data): """ Cleanup a string/HTML output to consist of words only. """ return strip_tags(force_unicode(data)) def clean_join(separator, iterable): """ Filters out iterable to only join non empty items. """ return separator.join(filter(None, iterable)) #def get_cleaned_bits(data): # return smart_split(get_cleaned_bits(data)) ## Instruction: Fix force_unicode for Python 3, use force_text() ## Code After: from django.utils.encoding import force_text from django.utils.html import strip_tags import six def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking for just the PluginHtmlField here. if value and isinstance(value, six.string_types): value = get_cleaned_string(value) values.append(value) return values def get_search_text(contentitem): bits = get_search_field_values(contentitem) return clean_join(u" ", bits) def get_cleaned_string(data): """ Cleanup a string/HTML output to consist of words only. """ return strip_tags(force_text(data)) def clean_join(separator, iterable): """ Filters out iterable to only join non empty items. """ return separator.join(filter(None, iterable)) #def get_cleaned_bits(data): # return smart_split(get_cleaned_bits(data))
- from django.utils.encoding import force_unicode ? ^^^^^^ + from django.utils.encoding import force_text ? ^ ++ from django.utils.html import strip_tags import six def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking for just the PluginHtmlField here. if value and isinstance(value, six.string_types): value = get_cleaned_string(value) values.append(value) return values def get_search_text(contentitem): bits = get_search_field_values(contentitem) return clean_join(u" ", bits) def get_cleaned_string(data): """ Cleanup a string/HTML output to consist of words only. """ - return strip_tags(force_unicode(data)) ? ^^^^^^ + return strip_tags(force_text(data)) ? ^ ++ def clean_join(separator, iterable): """ Filters out iterable to only join non empty items. """ return separator.join(filter(None, iterable)) #def get_cleaned_bits(data): # return smart_split(get_cleaned_bits(data))
8baa86cb381aaf52b16c7e0647a0b50cdbbd677a
st2common/st2common/util/db.py
st2common/st2common/util/db.py
from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) if isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} if isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value
from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) elif isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) # Recursively traverse the dict and list to convert values. if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} elif isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value
Use if-elif instead of multiple if statements to check types
Use if-elif instead of multiple if statements to check types Use if-elif instead of multiple if statements to check types when converting from MongoDB BaseDict and BaseList to python dict and list types. Once the value is converted, use another if-elif block to recursively evaluate and convert the values of dict and list.
Python
apache-2.0
nzlosh/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2
from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): + # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) - - if isinstance(value, mongoengine.base.datastructures.BaseList): + elif isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) + # Recursively traverse the dict and list to convert values. if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} - - if isinstance(value, list): + elif isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value
Use if-elif instead of multiple if statements to check types
## Code Before: from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) if isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} if isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value ## Instruction: Use if-elif instead of multiple if statements to check types ## Code After: from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) elif isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) # Recursively traverse the dict and list to convert values. if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} elif isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value
from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): + # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) - - if isinstance(value, mongoengine.base.datastructures.BaseList): + elif isinstance(value, mongoengine.base.datastructures.BaseList): ? ++ value = list(value) + # Recursively traverse the dict and list to convert values. if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} - - if isinstance(value, list): + elif isinstance(value, list): ? ++ value = [mongodb_to_python_types(v) for v in value] return value
c784fb30beac7abe958867345161f74876ca940d
causalinfo/__init__.py
causalinfo/__init__.py
from .probability import ( vs, Variable, make_variables, UniformDist, JointDist, JointDistByState ) from .network import CausalGraph, Equation from .measure import MeasureCause, MeasureSuccess from .payoff import PayoffMatrix import equations __version__ = "0.1.0" __title__ = "causalinfo" __description__ = "Attributes without boilerplate." __uri__ = "http://github/brettc/causalinfo/" __author__ = "Brett Calcott" __email__ = "brett.calcott@gmail.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Brett Calcott" __all__ = [ "CausalGraph", "Equation", "vs", "Variable", "make_variables", "UniformDist", "JointDist", "JointDistByState", "MeasureCause", "MeasureSuccess", "PayoffMatrix", "equations", ]
from .probability import ( vs, Variable, make_variables, UniformDist, JointDist, JointDistByState ) from .network import CausalGraph, Equation from .measure import MeasureCause, MeasureSuccess from .payoff import PayoffMatrix import equations __version__ = "0.1.0" __title__ = "causalinfo" __description__ = "Information Measures on Causal Graphs." __uri__ = "http://github/brettc/causalinfo/" __author__ = "Brett Calcott" __email__ = "brett.calcott@gmail.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Brett Calcott" __all__ = [ "CausalGraph", "Equation", "vs", "Variable", "make_variables", "UniformDist", "JointDist", "JointDistByState", "MeasureCause", "MeasureSuccess", "PayoffMatrix", "equations", ]
Fix silly boiler plate copy issue.
Fix silly boiler plate copy issue.
Python
mit
brettc/causalinfo
from .probability import ( vs, Variable, make_variables, UniformDist, JointDist, JointDistByState ) from .network import CausalGraph, Equation from .measure import MeasureCause, MeasureSuccess from .payoff import PayoffMatrix import equations __version__ = "0.1.0" __title__ = "causalinfo" - __description__ = "Attributes without boilerplate." + __description__ = "Information Measures on Causal Graphs." __uri__ = "http://github/brettc/causalinfo/" __author__ = "Brett Calcott" __email__ = "brett.calcott@gmail.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Brett Calcott" __all__ = [ "CausalGraph", "Equation", "vs", "Variable", "make_variables", "UniformDist", "JointDist", "JointDistByState", "MeasureCause", "MeasureSuccess", "PayoffMatrix", "equations", ]
Fix silly boiler plate copy issue.
## Code Before: from .probability import ( vs, Variable, make_variables, UniformDist, JointDist, JointDistByState ) from .network import CausalGraph, Equation from .measure import MeasureCause, MeasureSuccess from .payoff import PayoffMatrix import equations __version__ = "0.1.0" __title__ = "causalinfo" __description__ = "Attributes without boilerplate." __uri__ = "http://github/brettc/causalinfo/" __author__ = "Brett Calcott" __email__ = "brett.calcott@gmail.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Brett Calcott" __all__ = [ "CausalGraph", "Equation", "vs", "Variable", "make_variables", "UniformDist", "JointDist", "JointDistByState", "MeasureCause", "MeasureSuccess", "PayoffMatrix", "equations", ] ## Instruction: Fix silly boiler plate copy issue. ## Code After: from .probability import ( vs, Variable, make_variables, UniformDist, JointDist, JointDistByState ) from .network import CausalGraph, Equation from .measure import MeasureCause, MeasureSuccess from .payoff import PayoffMatrix import equations __version__ = "0.1.0" __title__ = "causalinfo" __description__ = "Information Measures on Causal Graphs." __uri__ = "http://github/brettc/causalinfo/" __author__ = "Brett Calcott" __email__ = "brett.calcott@gmail.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Brett Calcott" __all__ = [ "CausalGraph", "Equation", "vs", "Variable", "make_variables", "UniformDist", "JointDist", "JointDistByState", "MeasureCause", "MeasureSuccess", "PayoffMatrix", "equations", ]
from .probability import ( vs, Variable, make_variables, UniformDist, JointDist, JointDistByState ) from .network import CausalGraph, Equation from .measure import MeasureCause, MeasureSuccess from .payoff import PayoffMatrix import equations __version__ = "0.1.0" __title__ = "causalinfo" - __description__ = "Attributes without boilerplate." + __description__ = "Information Measures on Causal Graphs." __uri__ = "http://github/brettc/causalinfo/" __author__ = "Brett Calcott" __email__ = "brett.calcott@gmail.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Brett Calcott" __all__ = [ "CausalGraph", "Equation", "vs", "Variable", "make_variables", "UniformDist", "JointDist", "JointDistByState", "MeasureCause", "MeasureSuccess", "PayoffMatrix", "equations", ]
e288e8a52df0ac67a24271c40e23ae054e39fa52
monascaclient/common/monasca_manager.py
monascaclient/common/monasca_manager.py
from monascaclient.openstack.common.apiclient import base class MonascaManager(base.BaseManager): def __init__(self, client, **kwargs): super(MonascaManager, self).__init__(client) def get_headers(self): headers = self.client.credentials_headers() return headers def get_dimensions_url_string(self, dimdict): dim_list = list() for k, v in dimdict.items(): # In case user specifies a dimension multiple times if isinstance(v, (list, tuple)): v = v[-1] dim_str = k + ':' + v dim_list.append(dim_str) return ','.join(dim_list)
from monascaclient.openstack.common.apiclient import base class MonascaManager(base.BaseManager): def __init__(self, client, **kwargs): super(MonascaManager, self).__init__(client) def get_headers(self): headers = self.client.credentials_headers() return headers def get_dimensions_url_string(self, dimdict): dim_list = list() for k, v in dimdict.items(): # In case user specifies a dimension multiple times if isinstance(v, (list, tuple)): v = v[-1] if v: dim_str = k + ':' + v else: dim_str = k dim_list.append(dim_str) return ','.join(dim_list)
Fix metric dimensions having only key
Fix metric dimensions having only key When metric dimensions have only key, query parameter will be ending with ':' delimiter. But api can not handle this query parameter. So change to eliminate ':' delimiter when metric dimensions have only key. Change-Id: I1327f8fe641fe98cf16c28911ef19908468d1bc0
Python
apache-2.0
openstack/python-monascaclient,stackforge/python-monascaclient,sapcc/python-monascaclient,sapcc/python-monascaclient,stackforge/python-monascaclient,openstack/python-monascaclient
from monascaclient.openstack.common.apiclient import base class MonascaManager(base.BaseManager): def __init__(self, client, **kwargs): super(MonascaManager, self).__init__(client) def get_headers(self): headers = self.client.credentials_headers() return headers def get_dimensions_url_string(self, dimdict): dim_list = list() for k, v in dimdict.items(): # In case user specifies a dimension multiple times if isinstance(v, (list, tuple)): v = v[-1] + if v: - dim_str = k + ':' + v + dim_str = k + ':' + v + else: + dim_str = k dim_list.append(dim_str) return ','.join(dim_list)
Fix metric dimensions having only key
## Code Before: from monascaclient.openstack.common.apiclient import base class MonascaManager(base.BaseManager): def __init__(self, client, **kwargs): super(MonascaManager, self).__init__(client) def get_headers(self): headers = self.client.credentials_headers() return headers def get_dimensions_url_string(self, dimdict): dim_list = list() for k, v in dimdict.items(): # In case user specifies a dimension multiple times if isinstance(v, (list, tuple)): v = v[-1] dim_str = k + ':' + v dim_list.append(dim_str) return ','.join(dim_list) ## Instruction: Fix metric dimensions having only key ## Code After: from monascaclient.openstack.common.apiclient import base class MonascaManager(base.BaseManager): def __init__(self, client, **kwargs): super(MonascaManager, self).__init__(client) def get_headers(self): headers = self.client.credentials_headers() return headers def get_dimensions_url_string(self, dimdict): dim_list = list() for k, v in dimdict.items(): # In case user specifies a dimension multiple times if isinstance(v, (list, tuple)): v = v[-1] if v: dim_str = k + ':' + v else: dim_str = k dim_list.append(dim_str) return ','.join(dim_list)
from monascaclient.openstack.common.apiclient import base class MonascaManager(base.BaseManager): def __init__(self, client, **kwargs): super(MonascaManager, self).__init__(client) def get_headers(self): headers = self.client.credentials_headers() return headers def get_dimensions_url_string(self, dimdict): dim_list = list() for k, v in dimdict.items(): # In case user specifies a dimension multiple times if isinstance(v, (list, tuple)): v = v[-1] + if v: - dim_str = k + ':' + v + dim_str = k + ':' + v ? ++++ + else: + dim_str = k dim_list.append(dim_str) return ','.join(dim_list)
8e45eb77394ad47579f5726e8f2e63794b8e10c5
farnsworth/wsgi.py
farnsworth/wsgi.py
import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Fix python-path when WSGIPythonPath is not defined
Fix python-path when WSGIPythonPath is not defined
Python
bsd-2-clause
knagra/farnsworth,knagra/farnsworth,knagra/farnsworth,knagra/farnsworth
import os + import sys + sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Fix python-path when WSGIPythonPath is not defined
## Code Before: import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) ## Instruction: Fix python-path when WSGIPythonPath is not defined ## Code After: import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
import os + import sys + sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
904db705daf24d68fcc9ac6010b55b93c7dc4544
txircd/modules/core/accounts.py
txircd/modules/core/accounts.py
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None accounts = Accounts()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html irc.RPL_LOGGEDIN = "900" irc.RPL_LOGGEDOUT = "901" class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet), ("usermetadataupdate", 10, self.sendLoginNumeric) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer): if key == "account": if value is None: user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out") else: user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value)) accounts = Accounts()
Add automatic sending of 900/901 numerics for account status
Add automatic sending of 900/901 numerics for account status
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd
from twisted.plugin import IPlugin + from twisted.words.protocols import irc from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements + + # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html + irc.RPL_LOGGEDIN = "900" + irc.RPL_LOGGEDOUT = "901" class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): - return [ ("usercansetmetadata", 10, self.denyMetadataSet) ] + return [ ("usercansetmetadata", 10, self.denyMetadataSet), + ("usermetadataupdate", 10, self.sendLoginNumeric) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None + + def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer): + if key == "account": + if value is None: + user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out") + else: + user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value)) accounts = Accounts()
Add automatic sending of 900/901 numerics for account status
## Code Before: from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None accounts = Accounts() ## Instruction: Add automatic sending of 900/901 numerics for account status ## Code After: from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html irc.RPL_LOGGEDIN = "900" irc.RPL_LOGGEDOUT = "901" class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet), ("usermetadataupdate", 10, self.sendLoginNumeric) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer): if key == "account": if value is None: user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out") else: user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value)) accounts = Accounts()
from twisted.plugin import IPlugin + from twisted.words.protocols import irc from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements + + # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html + irc.RPL_LOGGEDIN = "900" + irc.RPL_LOGGEDOUT = "901" class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): - return [ ("usercansetmetadata", 10, self.denyMetadataSet) ] ? ^^ + return [ ("usercansetmetadata", 10, self.denyMetadataSet), ? ^ + ("usermetadataupdate", 10, self.sendLoginNumeric) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None + + def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer): + if key == "account": + if value is None: + user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out") + else: + user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value)) accounts = Accounts()
c20482f8c9c20b4d934e16a583697e2f8f520553
yesimeanit/showoff/newsletter_subscriptions/forms.py
yesimeanit/showoff/newsletter_subscriptions/forms.py
from django import forms from django.utils.translation import ugettext_lazy as _ from .models import NewsletterSubscription class SubscribtionForm(forms.ModelForm): class Meta: model = NewsletterSubscription fields = ('salutation', 'first_name', 'last_name', 'email') def clean_email(self): email = self.cleaned_data.get('email') if email and NewsletterSubscription.objects.active().filter(email=email).count(): raise forms.ValidationError(_('This e-mail address already has an active subscription.')) return email class UnsubscriptionForm(forms.ModelForm): class Meta: model = NewsletterSubscription fields = ('email',)
from django import forms from django.utils.translation import ugettext_lazy as _ from .models import NewsletterSubscription class SubscribtionForm(forms.ModelForm): salutation = forms.ChoiceField(choices=NewsletterSubscription.SALUTATION_CHOICES, required=False, label=_('salutation'), widget=forms.RadioSelect) class Meta: model = NewsletterSubscription fields = ('salutation', 'first_name', 'last_name', 'email') def clean_email(self): email = self.cleaned_data.get('email') if email and NewsletterSubscription.objects.active().filter(email=email).count(): raise forms.ValidationError(_('This e-mail address already has an active subscription.')) return email class UnsubscriptionForm(forms.ModelForm): class Meta: model = NewsletterSubscription fields = ('email',)
Customize salutation form field a bit
Customize salutation form field a bit
Python
bsd-3-clause
guetux/django-yesimeanit
from django import forms from django.utils.translation import ugettext_lazy as _ from .models import NewsletterSubscription class SubscribtionForm(forms.ModelForm): + salutation = forms.ChoiceField(choices=NewsletterSubscription.SALUTATION_CHOICES, + required=False, label=_('salutation'), widget=forms.RadioSelect) + class Meta: model = NewsletterSubscription fields = ('salutation', 'first_name', 'last_name', 'email') def clean_email(self): email = self.cleaned_data.get('email') if email and NewsletterSubscription.objects.active().filter(email=email).count(): raise forms.ValidationError(_('This e-mail address already has an active subscription.')) return email class UnsubscriptionForm(forms.ModelForm): class Meta: model = NewsletterSubscription fields = ('email',)
Customize salutation form field a bit
## Code Before: from django import forms from django.utils.translation import ugettext_lazy as _ from .models import NewsletterSubscription class SubscribtionForm(forms.ModelForm): class Meta: model = NewsletterSubscription fields = ('salutation', 'first_name', 'last_name', 'email') def clean_email(self): email = self.cleaned_data.get('email') if email and NewsletterSubscription.objects.active().filter(email=email).count(): raise forms.ValidationError(_('This e-mail address already has an active subscription.')) return email class UnsubscriptionForm(forms.ModelForm): class Meta: model = NewsletterSubscription fields = ('email',) ## Instruction: Customize salutation form field a bit ## Code After: from django import forms from django.utils.translation import ugettext_lazy as _ from .models import NewsletterSubscription class SubscribtionForm(forms.ModelForm): salutation = forms.ChoiceField(choices=NewsletterSubscription.SALUTATION_CHOICES, required=False, label=_('salutation'), widget=forms.RadioSelect) class Meta: model = NewsletterSubscription fields = ('salutation', 'first_name', 'last_name', 'email') def clean_email(self): email = self.cleaned_data.get('email') if email and NewsletterSubscription.objects.active().filter(email=email).count(): raise forms.ValidationError(_('This e-mail address already has an active subscription.')) return email class UnsubscriptionForm(forms.ModelForm): class Meta: model = NewsletterSubscription fields = ('email',)
from django import forms from django.utils.translation import ugettext_lazy as _ from .models import NewsletterSubscription class SubscribtionForm(forms.ModelForm): + salutation = forms.ChoiceField(choices=NewsletterSubscription.SALUTATION_CHOICES, + required=False, label=_('salutation'), widget=forms.RadioSelect) + class Meta: model = NewsletterSubscription fields = ('salutation', 'first_name', 'last_name', 'email') def clean_email(self): email = self.cleaned_data.get('email') if email and NewsletterSubscription.objects.active().filter(email=email).count(): raise forms.ValidationError(_('This e-mail address already has an active subscription.')) return email class UnsubscriptionForm(forms.ModelForm): class Meta: model = NewsletterSubscription fields = ('email',)
4ee589cd8fd7e60606524e26a3b69e202242b75c
meinberlin/apps/servicekonto/apps.py
meinberlin/apps/servicekonto/apps.py
from allauth.socialaccount import providers from django.apps import AppConfig from .provider import ServiceKontoProvider class Config(AppConfig): name = 'meinberlin.apps.servicekonto' label = 'meinberlin_servicekonto' def ready(self): providers.registry.register(ServiceKontoProvider)
from allauth.socialaccount import providers from django.apps import AppConfig class Config(AppConfig): name = 'meinberlin.apps.servicekonto' label = 'meinberlin_servicekonto' def ready(self): from .provider import ServiceKontoProvider providers.registry.register(ServiceKontoProvider)
Fix servicekonto import to be lazy on ready
Fix servicekonto import to be lazy on ready
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
from allauth.socialaccount import providers from django.apps import AppConfig - - from .provider import ServiceKontoProvider class Config(AppConfig): name = 'meinberlin.apps.servicekonto' label = 'meinberlin_servicekonto' def ready(self): + from .provider import ServiceKontoProvider providers.registry.register(ServiceKontoProvider)
Fix servicekonto import to be lazy on ready
## Code Before: from allauth.socialaccount import providers from django.apps import AppConfig from .provider import ServiceKontoProvider class Config(AppConfig): name = 'meinberlin.apps.servicekonto' label = 'meinberlin_servicekonto' def ready(self): providers.registry.register(ServiceKontoProvider) ## Instruction: Fix servicekonto import to be lazy on ready ## Code After: from allauth.socialaccount import providers from django.apps import AppConfig class Config(AppConfig): name = 'meinberlin.apps.servicekonto' label = 'meinberlin_servicekonto' def ready(self): from .provider import ServiceKontoProvider providers.registry.register(ServiceKontoProvider)
from allauth.socialaccount import providers from django.apps import AppConfig - - from .provider import ServiceKontoProvider class Config(AppConfig): name = 'meinberlin.apps.servicekonto' label = 'meinberlin_servicekonto' def ready(self): + from .provider import ServiceKontoProvider providers.registry.register(ServiceKontoProvider)
db6b869eae416e72fa30b1d7271b0ed1d7dc1a55
sqlalchemy_json/__init__.py
sqlalchemy_json/__init__.py
from sqlalchemy.ext.mutable import ( Mutable, MutableDict) from sqlalchemy_utils.types.json import JSONType from . track import ( TrackedDict, TrackedList) __all__ = 'MutableJson', 'NestedMutableJson' class NestedMutableDict(TrackedDict, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, dict): return cls(value) return super(cls).coerce(key, value) class NestedMutableList(TrackedList, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, list): return cls(value) return super(cls).coerce(key, value) class NestedMutable(Mutable): """SQLAlchemy `mutable` extension with nested change tracking.""" @classmethod def coerce(cls, key, value): """Convert plain dictionary to NestedMutable.""" if isinstance(value, cls): return value if isinstance(value, dict): return NestedMutableDict.coerce(key, value) if isinstance(value, list): return NestedMutableList.coerce(key, value) return super(cls).coerce(key, value) class MutableJson(JSONType): """JSON type for SQLAlchemy with change tracking at top level.""" class NestedMutableJson(JSONType): """JSON type for SQLAlchemy with nested change tracking.""" MutableDict.associate_with(MutableJson) NestedMutable.associate_with(NestedMutableJson)
from sqlalchemy.ext.mutable import ( Mutable, MutableDict) from sqlalchemy_utils.types.json import JSONType from . track import ( TrackedDict, TrackedList) __all__ = 'MutableJson', 'NestedMutableJson' class NestedMutableDict(TrackedDict, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, dict): return cls(value) return super(cls).coerce(key, value) class NestedMutableList(TrackedList, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, list): return cls(value) return super(cls).coerce(key, value) class NestedMutable(Mutable): """SQLAlchemy `mutable` extension with nested change tracking.""" @classmethod def coerce(cls, key, value): """Convert plain dictionary to NestedMutable.""" if value is None: return value if isinstance(value, cls): return value if isinstance(value, dict): return NestedMutableDict.coerce(key, value) if isinstance(value, list): return NestedMutableList.coerce(key, value) return super(cls).coerce(key, value) class MutableJson(JSONType): """JSON type for SQLAlchemy with change tracking at top level.""" class NestedMutableJson(JSONType): """JSON type for SQLAlchemy with nested change tracking.""" MutableDict.associate_with(MutableJson) NestedMutable.associate_with(NestedMutableJson)
Fix error when setting JSON value to be `None`
Fix error when setting JSON value to be `None` Previously this would raise an attribute error as `None` does not have the `coerce` attribute.
Python
bsd-2-clause
edelooff/sqlalchemy-json
from sqlalchemy.ext.mutable import ( Mutable, MutableDict) from sqlalchemy_utils.types.json import JSONType from . track import ( TrackedDict, TrackedList) __all__ = 'MutableJson', 'NestedMutableJson' class NestedMutableDict(TrackedDict, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, dict): return cls(value) return super(cls).coerce(key, value) class NestedMutableList(TrackedList, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, list): return cls(value) return super(cls).coerce(key, value) class NestedMutable(Mutable): """SQLAlchemy `mutable` extension with nested change tracking.""" @classmethod def coerce(cls, key, value): """Convert plain dictionary to NestedMutable.""" + if value is None: + return value if isinstance(value, cls): return value if isinstance(value, dict): return NestedMutableDict.coerce(key, value) if isinstance(value, list): return NestedMutableList.coerce(key, value) return super(cls).coerce(key, value) class MutableJson(JSONType): """JSON type for SQLAlchemy with change tracking at top level.""" class NestedMutableJson(JSONType): """JSON type for SQLAlchemy with nested change tracking.""" MutableDict.associate_with(MutableJson) NestedMutable.associate_with(NestedMutableJson)
Fix error when setting JSON value to be `None`
## Code Before: from sqlalchemy.ext.mutable import ( Mutable, MutableDict) from sqlalchemy_utils.types.json import JSONType from . track import ( TrackedDict, TrackedList) __all__ = 'MutableJson', 'NestedMutableJson' class NestedMutableDict(TrackedDict, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, dict): return cls(value) return super(cls).coerce(key, value) class NestedMutableList(TrackedList, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, list): return cls(value) return super(cls).coerce(key, value) class NestedMutable(Mutable): """SQLAlchemy `mutable` extension with nested change tracking.""" @classmethod def coerce(cls, key, value): """Convert plain dictionary to NestedMutable.""" if isinstance(value, cls): return value if isinstance(value, dict): return NestedMutableDict.coerce(key, value) if isinstance(value, list): return NestedMutableList.coerce(key, value) return super(cls).coerce(key, value) class MutableJson(JSONType): """JSON type for SQLAlchemy with change tracking at top level.""" class NestedMutableJson(JSONType): """JSON type for SQLAlchemy with nested change tracking.""" MutableDict.associate_with(MutableJson) NestedMutable.associate_with(NestedMutableJson) ## Instruction: Fix error when setting JSON value to be `None` ## Code After: from sqlalchemy.ext.mutable import ( Mutable, MutableDict) from sqlalchemy_utils.types.json import JSONType from . track import ( TrackedDict, TrackedList) __all__ = 'MutableJson', 'NestedMutableJson' class NestedMutableDict(TrackedDict, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, dict): return cls(value) return super(cls).coerce(key, value) class NestedMutableList(TrackedList, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, list): return cls(value) return super(cls).coerce(key, value) class NestedMutable(Mutable): """SQLAlchemy `mutable` extension with nested change tracking.""" @classmethod def coerce(cls, key, value): """Convert plain dictionary to NestedMutable.""" if value is None: return value if isinstance(value, cls): return value if isinstance(value, dict): return NestedMutableDict.coerce(key, value) if isinstance(value, list): return NestedMutableList.coerce(key, value) return super(cls).coerce(key, value) class MutableJson(JSONType): """JSON type for SQLAlchemy with change tracking at top level.""" class NestedMutableJson(JSONType): """JSON type for SQLAlchemy with nested change tracking.""" MutableDict.associate_with(MutableJson) NestedMutable.associate_with(NestedMutableJson)
from sqlalchemy.ext.mutable import ( Mutable, MutableDict) from sqlalchemy_utils.types.json import JSONType from . track import ( TrackedDict, TrackedList) __all__ = 'MutableJson', 'NestedMutableJson' class NestedMutableDict(TrackedDict, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, dict): return cls(value) return super(cls).coerce(key, value) class NestedMutableList(TrackedList, Mutable): @classmethod def coerce(cls, key, value): if isinstance(value, cls): return value if isinstance(value, list): return cls(value) return super(cls).coerce(key, value) class NestedMutable(Mutable): """SQLAlchemy `mutable` extension with nested change tracking.""" @classmethod def coerce(cls, key, value): """Convert plain dictionary to NestedMutable.""" + if value is None: + return value if isinstance(value, cls): return value if isinstance(value, dict): return NestedMutableDict.coerce(key, value) if isinstance(value, list): return NestedMutableList.coerce(key, value) return super(cls).coerce(key, value) class MutableJson(JSONType): """JSON type for SQLAlchemy with change tracking at top level.""" class NestedMutableJson(JSONType): """JSON type for SQLAlchemy with nested change tracking.""" MutableDict.associate_with(MutableJson) NestedMutable.associate_with(NestedMutableJson)
3ec71d3925a3551f6f25fc25e827c88caaff1fdd
tests/integration/test_redirection_external.py
tests/integration/test_redirection_external.py
"""Check external REDIRECTIONS""" import pytest from nikola import __main__ from .helper import append_config, cd from .test_demo_build import prepare_demo_site from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test_check_files, test_check_links, test_index_in_sitemap, ) @pytest.fixture(scope="module") def build(target_dir): """Fill the site with demo content and build it.""" prepare_demo_site(target_dir) append_config( target_dir, """ REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ] """, ) with cd(target_dir): __main__.main(["build"])
"""Check external REDIRECTIONS""" import os import pytest from nikola import __main__ from .helper import append_config, cd from .test_demo_build import prepare_demo_site from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test_check_files, test_check_links, test_index_in_sitemap, ) def test_external_redirection(build, output_dir): ext_link = os.path.join(output_dir, 'external.html') assert os.path.exists(ext_link) with open(ext_link) as ext_link_fd: ext_link_content = ext_link_fd.read() redirect_tag = '<meta http-equiv="refresh" content="0; url=http://www.example.com/">' assert redirect_tag in ext_link_content @pytest.fixture(scope="module") def build(target_dir): """Fill the site with demo content and build it.""" prepare_demo_site(target_dir) append_config( target_dir, """ REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ] """, ) with cd(target_dir): __main__.main(["build"])
Add test for external redirection.
Add test for external redirection.
Python
mit
okin/nikola,okin/nikola,okin/nikola,getnikola/nikola,getnikola/nikola,getnikola/nikola,okin/nikola,getnikola/nikola
"""Check external REDIRECTIONS""" + + import os import pytest from nikola import __main__ from .helper import append_config, cd from .test_demo_build import prepare_demo_site from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test_check_files, test_check_links, test_index_in_sitemap, ) + + + def test_external_redirection(build, output_dir): + ext_link = os.path.join(output_dir, 'external.html') + + assert os.path.exists(ext_link) + with open(ext_link) as ext_link_fd: + ext_link_content = ext_link_fd.read() + + redirect_tag = '<meta http-equiv="refresh" content="0; url=http://www.example.com/">' + assert redirect_tag in ext_link_content @pytest.fixture(scope="module") def build(target_dir): """Fill the site with demo content and build it.""" prepare_demo_site(target_dir) append_config( target_dir, """ REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ] """, ) with cd(target_dir): __main__.main(["build"])
Add test for external redirection.
## Code Before: """Check external REDIRECTIONS""" import pytest from nikola import __main__ from .helper import append_config, cd from .test_demo_build import prepare_demo_site from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test_check_files, test_check_links, test_index_in_sitemap, ) @pytest.fixture(scope="module") def build(target_dir): """Fill the site with demo content and build it.""" prepare_demo_site(target_dir) append_config( target_dir, """ REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ] """, ) with cd(target_dir): __main__.main(["build"]) ## Instruction: Add test for external redirection. ## Code After: """Check external REDIRECTIONS""" import os import pytest from nikola import __main__ from .helper import append_config, cd from .test_demo_build import prepare_demo_site from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test_check_files, test_check_links, test_index_in_sitemap, ) def test_external_redirection(build, output_dir): ext_link = os.path.join(output_dir, 'external.html') assert os.path.exists(ext_link) with open(ext_link) as ext_link_fd: ext_link_content = ext_link_fd.read() redirect_tag = '<meta http-equiv="refresh" content="0; url=http://www.example.com/">' assert redirect_tag in ext_link_content @pytest.fixture(scope="module") def build(target_dir): """Fill the site with demo content and build it.""" prepare_demo_site(target_dir) append_config( target_dir, """ REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ] """, ) with cd(target_dir): __main__.main(["build"])
"""Check external REDIRECTIONS""" + + import os import pytest from nikola import __main__ from .helper import append_config, cd from .test_demo_build import prepare_demo_site from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test_check_files, test_check_links, test_index_in_sitemap, ) + def test_external_redirection(build, output_dir): + ext_link = os.path.join(output_dir, 'external.html') + + assert os.path.exists(ext_link) + with open(ext_link) as ext_link_fd: + ext_link_content = ext_link_fd.read() + + redirect_tag = '<meta http-equiv="refresh" content="0; url=http://www.example.com/">' + assert redirect_tag in ext_link_content + + @pytest.fixture(scope="module") def build(target_dir): """Fill the site with demo content and build it.""" prepare_demo_site(target_dir) append_config( target_dir, """ REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ] """, ) with cd(target_dir): __main__.main(["build"])
534066b1228bb0070c1d62445155afa696a37921
contrail_provisioning/config/templates/contrail_plugin_ini.py
contrail_provisioning/config/templates/contrail_plugin_ini.py
import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ #use_ssl = False #insecure = False #certfile=$__contrail_api_server_cert_file__ #keyfile=$__contrail_api_server_key_file__ #cafile=$__contrail_api_server_ca_file__ contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None [COLLECTOR] analytics_api_ip = $__contrail_analytics_server_ip__ analytics_api_port = $__contrail_analytics_server_port__ [KEYSTONE] auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0 admin_user=$__contrail_admin_user__ admin_password=$__contrail_admin_password__ admin_tenant_name=$__contrail_admin_tenant_name__ """)
import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ #use_ssl = False #insecure = False #certfile=$__contrail_api_server_cert_file__ #keyfile=$__contrail_api_server_key_file__ #cafile=$__contrail_api_server_ca_file__ contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None,service-interface:None,vf-binding:None [COLLECTOR] analytics_api_ip = $__contrail_analytics_server_ip__ analytics_api_port = $__contrail_analytics_server_port__ [KEYSTONE] auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0 admin_user=$__contrail_admin_user__ admin_password=$__contrail_admin_password__ admin_tenant_name=$__contrail_admin_tenant_name__ """)
Enable service-interface and vf-binding extensions by default in contrail based provisioning.
Enable service-interface and vf-binding extensions by default in contrail based provisioning. Change-Id: I5916f41cdf12ad54e74c0f76de244ed60f57aea5 Partial-Bug: 1556336
Python
apache-2.0
Juniper/contrail-provisioning,Juniper/contrail-provisioning
import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ #use_ssl = False #insecure = False #certfile=$__contrail_api_server_cert_file__ #keyfile=$__contrail_api_server_key_file__ #cafile=$__contrail_api_server_ca_file__ - contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None + contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None,service-interface:None,vf-binding:None [COLLECTOR] analytics_api_ip = $__contrail_analytics_server_ip__ analytics_api_port = $__contrail_analytics_server_port__ [KEYSTONE] auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0 admin_user=$__contrail_admin_user__ admin_password=$__contrail_admin_password__ admin_tenant_name=$__contrail_admin_tenant_name__ """)
Enable service-interface and vf-binding extensions by default in contrail based provisioning.
## Code Before: import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ #use_ssl = False #insecure = False #certfile=$__contrail_api_server_cert_file__ #keyfile=$__contrail_api_server_key_file__ #cafile=$__contrail_api_server_ca_file__ contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None [COLLECTOR] analytics_api_ip = $__contrail_analytics_server_ip__ analytics_api_port = $__contrail_analytics_server_port__ [KEYSTONE] auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0 admin_user=$__contrail_admin_user__ admin_password=$__contrail_admin_password__ admin_tenant_name=$__contrail_admin_tenant_name__ """) ## Instruction: Enable service-interface and vf-binding extensions by default in contrail based provisioning. ## Code After: import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ #use_ssl = False #insecure = False #certfile=$__contrail_api_server_cert_file__ #keyfile=$__contrail_api_server_key_file__ #cafile=$__contrail_api_server_ca_file__ contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None,service-interface:None,vf-binding:None [COLLECTOR] analytics_api_ip = $__contrail_analytics_server_ip__ analytics_api_port = $__contrail_analytics_server_port__ [KEYSTONE] auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0 admin_user=$__contrail_admin_user__ admin_password=$__contrail_admin_password__ admin_tenant_name=$__contrail_admin_tenant_name__ """)
import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ #use_ssl = False #insecure = False #certfile=$__contrail_api_server_cert_file__ #keyfile=$__contrail_api_server_key_file__ #cafile=$__contrail_api_server_ca_file__ - contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None + contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None,service-interface:None,vf-binding:None ? +++++++++++++++++++++++++++++++++++++++ [COLLECTOR] analytics_api_ip = $__contrail_analytics_server_ip__ analytics_api_port = $__contrail_analytics_server_port__ [KEYSTONE] auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0 admin_user=$__contrail_admin_user__ admin_password=$__contrail_admin_password__ admin_tenant_name=$__contrail_admin_tenant_name__ """)
b6b627cb4c5d6b7dc1636794de870a2bf6da262b
cookiecutter/replay.py
cookiecutter/replay.py
from __future__ import unicode_literals from .compat import is_string def dump(template_name, context): if not is_string(template_name): raise TypeError('Template name is required to be of type str')
from __future__ import unicode_literals from .compat import is_string def dump(template_name, context): if not is_string(template_name): raise TypeError('Template name is required to be of type str') if not isinstance(context, dict): raise TypeError('Context is required to be of type dict')
Raise a TypeError if context is not a dict
Raise a TypeError if context is not a dict
Python
bsd-3-clause
pjbull/cookiecutter,hackebrot/cookiecutter,cguardia/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,agconti/cookiecutter,michaeljoseph/cookiecutter,venumech/cookiecutter,christabor/cookiecutter,michaeljoseph/cookiecutter,terryjbates/cookiecutter,takeflight/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,willingc/cookiecutter,audreyr/cookiecutter,ramiroluz/cookiecutter,benthomasson/cookiecutter,moi65/cookiecutter,benthomasson/cookiecutter,audreyr/cookiecutter,takeflight/cookiecutter,willingc/cookiecutter,venumech/cookiecutter,agconti/cookiecutter,stevepiercy/cookiecutter,terryjbates/cookiecutter,cguardia/cookiecutter,dajose/cookiecutter,ramiroluz/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,Springerle/cookiecutter,Springerle/cookiecutter,christabor/cookiecutter,moi65/cookiecutter
from __future__ import unicode_literals from .compat import is_string def dump(template_name, context): if not is_string(template_name): raise TypeError('Template name is required to be of type str') + if not isinstance(context, dict): + raise TypeError('Context is required to be of type dict') +
Raise a TypeError if context is not a dict
## Code Before: from __future__ import unicode_literals from .compat import is_string def dump(template_name, context): if not is_string(template_name): raise TypeError('Template name is required to be of type str') ## Instruction: Raise a TypeError if context is not a dict ## Code After: from __future__ import unicode_literals from .compat import is_string def dump(template_name, context): if not is_string(template_name): raise TypeError('Template name is required to be of type str') if not isinstance(context, dict): raise TypeError('Context is required to be of type dict')
from __future__ import unicode_literals from .compat import is_string def dump(template_name, context): if not is_string(template_name): raise TypeError('Template name is required to be of type str') + + if not isinstance(context, dict): + raise TypeError('Context is required to be of type dict')
17d91eff7de5517aa89330a08f3c84fa46d02538
tests/test_exc.py
tests/test_exc.py
import pytest from cihai import exc def test_base_exception(): with pytest.raises( exc.CihaiException, message="Make sure no one removes or renames base CihaiException", ): raise exc.CihaiException() with pytest.raises(Exception, message="Extends python base exception"): raise exc.CihaiException()
import pytest from cihai import exc def test_base_exception(): with pytest.raises(exc.CihaiException): raise exc.CihaiException() # Make sure its base of CihaiException with pytest.raises(Exception): raise exc.CihaiException() # Extends python base exception
Update exception test for pytest 5+
Update exception test for pytest 5+ pytest 3 had message for raises, this is removed in current versions.
Python
mit
cihai/cihai,cihai/cihai
- import pytest from cihai import exc def test_base_exception(): + with pytest.raises(exc.CihaiException): + raise exc.CihaiException() # Make sure its base of CihaiException - with pytest.raises( - exc.CihaiException, - message="Make sure no one removes or renames base CihaiException", - ): - raise exc.CihaiException() - with pytest.raises(Exception, message="Extends python base exception"): - raise exc.CihaiException() + with pytest.raises(Exception): + raise exc.CihaiException() # Extends python base exception
Update exception test for pytest 5+
## Code Before: import pytest from cihai import exc def test_base_exception(): with pytest.raises( exc.CihaiException, message="Make sure no one removes or renames base CihaiException", ): raise exc.CihaiException() with pytest.raises(Exception, message="Extends python base exception"): raise exc.CihaiException() ## Instruction: Update exception test for pytest 5+ ## Code After: import pytest from cihai import exc def test_base_exception(): with pytest.raises(exc.CihaiException): raise exc.CihaiException() # Make sure its base of CihaiException with pytest.raises(Exception): raise exc.CihaiException() # Extends python base exception
- import pytest from cihai import exc def test_base_exception(): - with pytest.raises( - exc.CihaiException, - message="Make sure no one removes or renames base CihaiException", - ): - raise exc.CihaiException() ? ^^^ ^ - + with pytest.raises(exc.CihaiException): ? ++++ ^^^^^^^ ^^ + + raise exc.CihaiException() # Make sure its base of CihaiException - with pytest.raises(Exception, message="Extends python base exception"): - raise exc.CihaiException() + with pytest.raises(Exception): + raise exc.CihaiException() # Extends python base exception
2e95901ee37100f855a5f30e6143920ef2b56904
odinweb/_compat.py
odinweb/_compat.py
from __future__ import unicode_literals import sys __all__ = ( 'PY2', 'PY3', 'string_types', 'integer_types', 'text_type', 'binary_type', 'range', 'with_metaclass' ) PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, text_type = str binary_type = bytes else: string_types = basestring, integer_types = (int, long) text_type = unicode binary_type = str if PY2: range = xrange else: range = range def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
import sys __all__ = ( 'PY2', 'PY3', 'string_types', 'integer_types', 'text_type', 'binary_type', 'range', 'with_metaclass' ) PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, text_type = str binary_type = bytes else: string_types = basestring, integer_types = (int, long) text_type = unicode binary_type = str if PY2: range = xrange else: range = range def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
Remove unicode literals to fix with_metaclass method
Remove unicode literals to fix with_metaclass method
Python
bsd-3-clause
python-odin/odinweb,python-odin/odinweb
- from __future__ import unicode_literals - import sys __all__ = ( 'PY2', 'PY3', 'string_types', 'integer_types', 'text_type', 'binary_type', 'range', 'with_metaclass' ) PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, text_type = str binary_type = bytes else: string_types = basestring, integer_types = (int, long) text_type = unicode binary_type = str if PY2: range = xrange else: range = range def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
Remove unicode literals to fix with_metaclass method
## Code Before: from __future__ import unicode_literals import sys __all__ = ( 'PY2', 'PY3', 'string_types', 'integer_types', 'text_type', 'binary_type', 'range', 'with_metaclass' ) PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, text_type = str binary_type = bytes else: string_types = basestring, integer_types = (int, long) text_type = unicode binary_type = str if PY2: range = xrange else: range = range def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) ## Instruction: Remove unicode literals to fix with_metaclass method ## Code After: import sys __all__ = ( 'PY2', 'PY3', 'string_types', 'integer_types', 'text_type', 'binary_type', 'range', 'with_metaclass' ) PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, text_type = str binary_type = bytes else: string_types = basestring, integer_types = (int, long) text_type = unicode binary_type = str if PY2: range = xrange else: range = range def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
- from __future__ import unicode_literals - import sys __all__ = ( 'PY2', 'PY3', 'string_types', 'integer_types', 'text_type', 'binary_type', 'range', 'with_metaclass' ) PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, text_type = str binary_type = bytes else: string_types = basestring, integer_types = (int, long) text_type = unicode binary_type = str if PY2: range = xrange else: range = range def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
91b3891078b889db98d3832f0c06e465a86e52ef
django_tenants/staticfiles/storage.py
django_tenants/staticfiles/storage.py
import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) def path(self, name): """ if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") """ return super(TenantStaticFilesStorage, self).path(name)
import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) """ def path(self, name): if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") return super(TenantStaticFilesStorage, self).path(name) """
Fix regression in path handling of TenantStaticFileStorage.
Fix regression in path handling of TenantStaticFileStorage. Fixes #197.
Python
mit
tomturner/django-tenants,tomturner/django-tenants,tomturner/django-tenants
import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) + """ def path(self, name): - """ if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") - """ return super(TenantStaticFilesStorage, self).path(name) + """
Fix regression in path handling of TenantStaticFileStorage.
## Code Before: import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) def path(self, name): """ if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") """ return super(TenantStaticFilesStorage, self).path(name) ## Instruction: Fix regression in path handling of TenantStaticFileStorage. ## Code After: import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) """ def path(self, name): if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") return super(TenantStaticFilesStorage, self).path(name) """
import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) + """ def path(self, name): - """ if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") - """ return super(TenantStaticFilesStorage, self).path(name) + """
1a88833845776d7592bbdef33571cd2da836cb91
ookoobah/tools.py
ookoobah/tools.py
class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) return True class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
Return update flag from erase tool.
Return update flag from erase tool. Fixes a bug introduced a couple commits earlier.
Python
mit
vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah
class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) + return True class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
Return update flag from erase tool.
## Code Before: class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states() ## Instruction: Return update flag from erase tool. ## Code After: class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) return True class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) + return True class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
2231c0384e56af56285999bc0bf7a096d3dd1cb9
pyuploadcare/dj/models.py
pyuploadcare/dj/models.py
from django.db import models from django.core.exceptions import ValidationError from pyuploadcare.dj import forms, UploadCare from pyuploadcare.file import File class FileField(models.Field): __metaclass__ = models.SubfieldBase description = "UploadCare file id/URI with cached data" def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return None if isinstance(value, basestring): return UploadCare().file(value) if isinstance(value, File): return value raise ValidationError('Invalid value for a field') def get_prep_value(self, value): return value.serialize() def get_db_prep_save(self, value, connection=None): if value: value.store() return value.serialize() def value_to_string(self, obj): assert False def formfield(self, **kwargs): defaults = {'widget': forms.FileWidget, 'form_class': forms.FileField} defaults.update(kwargs) # yay for super! return super(FileField, self).formfield(**defaults)
from django.db import models from django.core.exceptions import ValidationError from pyuploadcare.dj import forms, UploadCare from pyuploadcare.exceptions import InvalidRequestError from pyuploadcare.file import File class FileField(models.Field): __metaclass__ = models.SubfieldBase description = "UploadCare file id/URI with cached data" def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return None if isinstance(value, File): return value if not isinstance(value, basestring): raise ValidationError( u'Invalid value for a field: string was expected' ) try: return UploadCare().file(value) except InvalidRequestError as exc: raise ValidationError( u'Invalid value for a field: {exc}'.format(exc=exc) ) def get_prep_value(self, value): return value.serialize() def get_db_prep_save(self, value, connection=None): if value: value.store() return value.serialize() def value_to_string(self, obj): assert False def formfield(self, **kwargs): defaults = {'widget': forms.FileWidget, 'form_class': forms.FileField} defaults.update(kwargs) # yay for super! return super(FileField, self).formfield(**defaults)
Add handling of InvalidRequestError in ``to_python`
Add handling of InvalidRequestError in ``to_python`
Python
mit
uploadcare/pyuploadcare
from django.db import models from django.core.exceptions import ValidationError from pyuploadcare.dj import forms, UploadCare + from pyuploadcare.exceptions import InvalidRequestError from pyuploadcare.file import File class FileField(models.Field): __metaclass__ = models.SubfieldBase description = "UploadCare file id/URI with cached data" def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return None - if isinstance(value, basestring): - return UploadCare().file(value) - if isinstance(value, File): return value - raise ValidationError('Invalid value for a field') + if not isinstance(value, basestring): + raise ValidationError( + u'Invalid value for a field: string was expected' + ) + + try: + return UploadCare().file(value) + except InvalidRequestError as exc: + raise ValidationError( + u'Invalid value for a field: {exc}'.format(exc=exc) + ) def get_prep_value(self, value): return value.serialize() def get_db_prep_save(self, value, connection=None): if value: value.store() return value.serialize() def value_to_string(self, obj): assert False def formfield(self, **kwargs): defaults = {'widget': forms.FileWidget, 'form_class': forms.FileField} defaults.update(kwargs) # yay for super! return super(FileField, self).formfield(**defaults)
Add handling of InvalidRequestError in ``to_python`
## Code Before: from django.db import models from django.core.exceptions import ValidationError from pyuploadcare.dj import forms, UploadCare from pyuploadcare.file import File class FileField(models.Field): __metaclass__ = models.SubfieldBase description = "UploadCare file id/URI with cached data" def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return None if isinstance(value, basestring): return UploadCare().file(value) if isinstance(value, File): return value raise ValidationError('Invalid value for a field') def get_prep_value(self, value): return value.serialize() def get_db_prep_save(self, value, connection=None): if value: value.store() return value.serialize() def value_to_string(self, obj): assert False def formfield(self, **kwargs): defaults = {'widget': forms.FileWidget, 'form_class': forms.FileField} defaults.update(kwargs) # yay for super! return super(FileField, self).formfield(**defaults) ## Instruction: Add handling of InvalidRequestError in ``to_python` ## Code After: from django.db import models from django.core.exceptions import ValidationError from pyuploadcare.dj import forms, UploadCare from pyuploadcare.exceptions import InvalidRequestError from pyuploadcare.file import File class FileField(models.Field): __metaclass__ = models.SubfieldBase description = "UploadCare file id/URI with cached data" def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return None if isinstance(value, File): return value if not isinstance(value, basestring): raise ValidationError( u'Invalid value for a field: string was expected' ) try: return UploadCare().file(value) except InvalidRequestError as exc: raise ValidationError( u'Invalid value for a field: {exc}'.format(exc=exc) ) def get_prep_value(self, value): return value.serialize() def get_db_prep_save(self, value, connection=None): if value: value.store() return value.serialize() def value_to_string(self, obj): assert False def formfield(self, **kwargs): defaults = {'widget': forms.FileWidget, 'form_class': forms.FileField} defaults.update(kwargs) # yay for super! return super(FileField, self).formfield(**defaults)
from django.db import models from django.core.exceptions import ValidationError from pyuploadcare.dj import forms, UploadCare + from pyuploadcare.exceptions import InvalidRequestError from pyuploadcare.file import File class FileField(models.Field): __metaclass__ = models.SubfieldBase description = "UploadCare file id/URI with cached data" def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return None - if isinstance(value, basestring): - return UploadCare().file(value) - if isinstance(value, File): return value - raise ValidationError('Invalid value for a field') + if not isinstance(value, basestring): + raise ValidationError( + u'Invalid value for a field: string was expected' + ) + + try: + return UploadCare().file(value) + except InvalidRequestError as exc: + raise ValidationError( + u'Invalid value for a field: {exc}'.format(exc=exc) + ) def get_prep_value(self, value): return value.serialize() def get_db_prep_save(self, value, connection=None): if value: value.store() return value.serialize() def value_to_string(self, obj): assert False def formfield(self, **kwargs): defaults = {'widget': forms.FileWidget, 'form_class': forms.FileField} defaults.update(kwargs) # yay for super! return super(FileField, self).formfield(**defaults)
72ce164a461987f7b9d35ac9a2b3a36386b7f8c9
ui/Interactor.py
ui/Interactor.py
class Interactor(object): """ Interactor """ def __init__(self): super(Interactor, self).__init__() def AddObserver(self, obj, eventName, callbackFunction): """ Creates a callback and stores the callback so that later on the callbacks can be properly cleaned up. """ if not hasattr(self, "_callbacks"): self._callbacks = [] callback = obj.AddObserver(eventName, callbackFunction) self._callbacks.append((obj, callback)) def cleanUpCallbacks(self): """ Cleans up the vtkCallBacks """ if not hasattr(self, "_callbacks"): return for obj, callback in self._callbacks: obj.RemoveObserver(callback) self._callbacks = []
class Interactor(object): """ Interactor """ def __init__(self): super(Interactor, self).__init__() def AddObserver(self, obj, eventName, callbackFunction, priority=None): """ Creates a callback and stores the callback so that later on the callbacks can be properly cleaned up. """ if not hasattr(self, "_callbacks"): self._callbacks = [] if priority is not None: callback = obj.AddObserver(eventName, callbackFunction, priority) else: callback = obj.AddObserver(eventName, callbackFunction) self._callbacks.append((obj, callback)) def cleanUpCallbacks(self): """ Cleans up the vtkCallBacks """ if not hasattr(self, "_callbacks"): return for obj, callback in self._callbacks: obj.RemoveObserver(callback) self._callbacks = []
Add possibility of passing priority for adding an observer
Add possibility of passing priority for adding an observer
Python
mit
berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop
class Interactor(object): """ Interactor """ def __init__(self): super(Interactor, self).__init__() - def AddObserver(self, obj, eventName, callbackFunction): + def AddObserver(self, obj, eventName, callbackFunction, priority=None): """ Creates a callback and stores the callback so that later on the callbacks can be properly cleaned up. """ if not hasattr(self, "_callbacks"): self._callbacks = [] + if priority is not None: + callback = obj.AddObserver(eventName, callbackFunction, priority) + else: - callback = obj.AddObserver(eventName, callbackFunction) + callback = obj.AddObserver(eventName, callbackFunction) self._callbacks.append((obj, callback)) def cleanUpCallbacks(self): """ Cleans up the vtkCallBacks """ if not hasattr(self, "_callbacks"): return for obj, callback in self._callbacks: obj.RemoveObserver(callback) self._callbacks = []
Add possibility of passing priority for adding an observer
## Code Before: class Interactor(object): """ Interactor """ def __init__(self): super(Interactor, self).__init__() def AddObserver(self, obj, eventName, callbackFunction): """ Creates a callback and stores the callback so that later on the callbacks can be properly cleaned up. """ if not hasattr(self, "_callbacks"): self._callbacks = [] callback = obj.AddObserver(eventName, callbackFunction) self._callbacks.append((obj, callback)) def cleanUpCallbacks(self): """ Cleans up the vtkCallBacks """ if not hasattr(self, "_callbacks"): return for obj, callback in self._callbacks: obj.RemoveObserver(callback) self._callbacks = [] ## Instruction: Add possibility of passing priority for adding an observer ## Code After: class Interactor(object): """ Interactor """ def __init__(self): super(Interactor, self).__init__() def AddObserver(self, obj, eventName, callbackFunction, priority=None): """ Creates a callback and stores the callback so that later on the callbacks can be properly cleaned up. """ if not hasattr(self, "_callbacks"): self._callbacks = [] if priority is not None: callback = obj.AddObserver(eventName, callbackFunction, priority) else: callback = obj.AddObserver(eventName, callbackFunction) self._callbacks.append((obj, callback)) def cleanUpCallbacks(self): """ Cleans up the vtkCallBacks """ if not hasattr(self, "_callbacks"): return for obj, callback in self._callbacks: obj.RemoveObserver(callback) self._callbacks = []
class Interactor(object): """ Interactor """ def __init__(self): super(Interactor, self).__init__() - def AddObserver(self, obj, eventName, callbackFunction): + def AddObserver(self, obj, eventName, callbackFunction, priority=None): ? +++++++++++++++ """ Creates a callback and stores the callback so that later on the callbacks can be properly cleaned up. """ if not hasattr(self, "_callbacks"): self._callbacks = [] + if priority is not None: + callback = obj.AddObserver(eventName, callbackFunction, priority) + else: - callback = obj.AddObserver(eventName, callbackFunction) + callback = obj.AddObserver(eventName, callbackFunction) ? + self._callbacks.append((obj, callback)) def cleanUpCallbacks(self): """ Cleans up the vtkCallBacks """ if not hasattr(self, "_callbacks"): return for obj, callback in self._callbacks: obj.RemoveObserver(callback) self._callbacks = []
d57a1b223b46923bfe5211d4f189b65cfcbffcad
msoffcrypto/format/base.py
msoffcrypto/format/base.py
import abc # For 2 and 3 compatibility # https://stackoverflow.com/questions/35673474/ ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) class BaseOfficeFile(ABC): def __init__(self): pass @abc.abstractmethod def load_key(self): pass @abc.abstractmethod def decrypt(self): pass
import abc # For 2 and 3 compatibility # https://stackoverflow.com/questions/35673474/ ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) class BaseOfficeFile(ABC): def __init__(self): pass @abc.abstractmethod def load_key(self): pass @abc.abstractmethod def decrypt(self): pass @abc.abstractmethod def is_encrypted(self): pass
Add is_encrypted() to abstract methods
Add is_encrypted() to abstract methods
Python
mit
nolze/ms-offcrypto-tool,nolze/ms-offcrypto-tool,nolze/msoffcrypto-tool,nolze/msoffcrypto-tool
import abc # For 2 and 3 compatibility # https://stackoverflow.com/questions/35673474/ ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) class BaseOfficeFile(ABC): def __init__(self): pass @abc.abstractmethod def load_key(self): pass @abc.abstractmethod def decrypt(self): pass + @abc.abstractmethod + def is_encrypted(self): + pass +
Add is_encrypted() to abstract methods
## Code Before: import abc # For 2 and 3 compatibility # https://stackoverflow.com/questions/35673474/ ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) class BaseOfficeFile(ABC): def __init__(self): pass @abc.abstractmethod def load_key(self): pass @abc.abstractmethod def decrypt(self): pass ## Instruction: Add is_encrypted() to abstract methods ## Code After: import abc # For 2 and 3 compatibility # https://stackoverflow.com/questions/35673474/ ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) class BaseOfficeFile(ABC): def __init__(self): pass @abc.abstractmethod def load_key(self): pass @abc.abstractmethod def decrypt(self): pass @abc.abstractmethod def is_encrypted(self): pass
import abc # For 2 and 3 compatibility # https://stackoverflow.com/questions/35673474/ ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) class BaseOfficeFile(ABC): def __init__(self): pass @abc.abstractmethod def load_key(self): pass @abc.abstractmethod def decrypt(self): pass + + @abc.abstractmethod + def is_encrypted(self): + pass
e951dde14f65e188118c2eb9e8825d317ada488a
yunity/groups/models.py
yunity/groups/models.py
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL)
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups')
Add related name for group member
Add related name for group member
Python
agpl-3.0
yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) - members = ManyToManyField(settings.AUTH_USER_MODEL) + members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups')
Add related name for group member
## Code Before: from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL) ## Instruction: Add related name for group member ## Code After: from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups')
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) - members = ManyToManyField(settings.AUTH_USER_MODEL) + members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups') ? +++++++++++++++++++++++
e05ea934335eac29c0b2f164eab600008546324c
recurring_contract/migrations/1.2/post-migration.py
recurring_contract/migrations/1.2/post-migration.py
import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET recurring_value = {0}, advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
Remove wrong migration of contracts.
Remove wrong migration of contracts.
Python
agpl-3.0
CompassionCH/compassion-accounting,ndtran/compassion-accounting,ndtran/compassion-accounting,ecino/compassion-accounting,ecino/compassion-accounting,CompassionCH/compassion-accounting,ndtran/compassion-accounting
import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group - SET recurring_value = {0}, advance_billing_months = {0} + SET advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
Remove wrong migration of contracts.
## Code Before: import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET recurring_value = {0}, advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) ) ## Instruction: Remove wrong migration of contracts. ## Code After: import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group - SET recurring_value = {0}, advance_billing_months = {0} ? ----------------------- + SET advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
e70f30758a501db12af4fbbfc4204e2858967c8b
conllu/compat.py
conllu/compat.py
try: from io import StringIO except ImportError: from StringIO import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original def string_to_file(string): return StringIO(string) def capture_print(func, args=None): f = StringIO() with redirect_stdout(f): if args: func(args) else: func() return f.getvalue() try: from re import fullmatch except ImportError: from re import match def fullmatch(pattern, *args): if not pattern.endswith("$"): pattern += "$" return match(pattern, *args) try: unicode('') except NameError: unicode = str def text(value): return unicode(value)
try: from io import StringIO except ImportError: from StringIO import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original def string_to_file(string): return StringIO(string) def capture_print(func, args=None): f = StringIO() with redirect_stdout(f): if args: func(args) else: func() return f.getvalue() try: from re import fullmatch except ImportError: from re import match def fullmatch(regex, *args): if not regex.pattern.endswith("$"): return match(regex.pattern + "$", *args) return match(regex.pattern, *args) try: unicode('') except NameError: unicode = str def text(value): return unicode(value)
Make fullmatch work on python 2.7.
Bug: Make fullmatch work on python 2.7.
Python
mit
EmilStenstrom/conllu
try: from io import StringIO except ImportError: from StringIO import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original def string_to_file(string): return StringIO(string) def capture_print(func, args=None): f = StringIO() with redirect_stdout(f): if args: func(args) else: func() return f.getvalue() try: from re import fullmatch except ImportError: from re import match + - def fullmatch(pattern, *args): + def fullmatch(regex, *args): - if not pattern.endswith("$"): + if not regex.pattern.endswith("$"): - pattern += "$" + return match(regex.pattern + "$", *args) + - return match(pattern, *args) + return match(regex.pattern, *args) try: unicode('') except NameError: unicode = str def text(value): return unicode(value)
Make fullmatch work on python 2.7.
## Code Before: try: from io import StringIO except ImportError: from StringIO import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original def string_to_file(string): return StringIO(string) def capture_print(func, args=None): f = StringIO() with redirect_stdout(f): if args: func(args) else: func() return f.getvalue() try: from re import fullmatch except ImportError: from re import match def fullmatch(pattern, *args): if not pattern.endswith("$"): pattern += "$" return match(pattern, *args) try: unicode('') except NameError: unicode = str def text(value): return unicode(value) ## Instruction: Make fullmatch work on python 2.7. ## Code After: try: from io import StringIO except ImportError: from StringIO import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original def string_to_file(string): return StringIO(string) def capture_print(func, args=None): f = StringIO() with redirect_stdout(f): if args: func(args) else: func() return f.getvalue() try: from re import fullmatch except ImportError: from re import match def fullmatch(regex, *args): if not regex.pattern.endswith("$"): return match(regex.pattern + "$", *args) return match(regex.pattern, *args) try: unicode('') except NameError: unicode = str def text(value): return unicode(value)
try: from io import StringIO except ImportError: from StringIO import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original def string_to_file(string): return StringIO(string) def capture_print(func, args=None): f = StringIO() with redirect_stdout(f): if args: func(args) else: func() return f.getvalue() try: from re import fullmatch except ImportError: from re import match + - def fullmatch(pattern, *args): ? ^^^^ ^^ + def fullmatch(regex, *args): ? ^ ^^^ - if not pattern.endswith("$"): + if not regex.pattern.endswith("$"): ? ++++++ - pattern += "$" + return match(regex.pattern + "$", *args) + - return match(pattern, *args) + return match(regex.pattern, *args) ? ++++++ try: unicode('') except NameError: unicode = str def text(value): return unicode(value)
4dfbe6ea079b32644c9086351f911ce1a2b2b0e1
easy_maps/geocode.py
easy_maps/geocode.py
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) return g.geocode(address, exactly_one=False)[0] except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) results = g.geocode(address, exactly_one=False) if results is not None: return results[0] raise Error('No results found') except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
Resolve the 500 error when google send a no results info
Resolve the 500 error when google send a no results info
Python
mit
duixteam/django-easy-maps,kmike/django-easy-maps,Gonzasestopal/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps,Gonzasestopal/django-easy-maps
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError + class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) - return g.geocode(address, exactly_one=False)[0] + results = g.geocode(address, exactly_one=False) + if results is not None: + return results[0] + raise Error('No results found') except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
Resolve the 500 error when google send a no results info
## Code Before: from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) return g.geocode(address, exactly_one=False)[0] except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e) ## Instruction: Resolve the 500 error when google send a no results info ## Code After: from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) results = g.geocode(address, exactly_one=False) if results is not None: return results[0] raise Error('No results found') except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError + class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) - return g.geocode(address, exactly_one=False)[0] ? ^^^ --- + results = g.geocode(address, exactly_one=False) ? +++ ^^^ + if results is not None: + return results[0] + raise Error('No results found') except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
cfc9c21121f06007dd582fe6cd0162e4df2a21d5
tests/test_cle_gdb.py
tests/test_cle_gdb.py
import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] nose.tools.assert_equal(libc.rebase_addr, 0x7ffff7a17000) nose.tools.assert_equal(ld.rebase_addr, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] nose.tools.assert_equal(libc.mapped_base, 0x7ffff7a17000) nose.tools.assert_equal(ld.mapped_base, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
Test fix. rebase_addr to mapped_base
fix: Test fix. rebase_addr to mapped_base
Python
bsd-2-clause
schieb/angr,iamahuman/angr,iamahuman/angr,f-prettyland/angr,axt/angr,f-prettyland/angr,angr/angr,tyb0807/angr,chubbymaggie/angr,axt/angr,tyb0807/angr,schieb/angr,schieb/angr,angr/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/angr,iamahuman/angr,angr/angr,f-prettyland/angr,axt/angr
import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] - nose.tools.assert_equal(libc.rebase_addr, 0x7ffff7a17000) + nose.tools.assert_equal(libc.mapped_base, 0x7ffff7a17000) - nose.tools.assert_equal(ld.rebase_addr, 0x7ffff7ddc000) + nose.tools.assert_equal(ld.mapped_base, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
Test fix. rebase_addr to mapped_base
## Code Before: import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] nose.tools.assert_equal(libc.rebase_addr, 0x7ffff7a17000) nose.tools.assert_equal(ld.rebase_addr, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs() ## Instruction: Test fix. rebase_addr to mapped_base ## Code After: import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] nose.tools.assert_equal(libc.mapped_base, 0x7ffff7a17000) nose.tools.assert_equal(ld.mapped_base, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] - nose.tools.assert_equal(libc.rebase_addr, 0x7ffff7a17000) ? ^ ----- + nose.tools.assert_equal(libc.mapped_base, 0x7ffff7a17000) ? ^^^^ ++ - nose.tools.assert_equal(ld.rebase_addr, 0x7ffff7ddc000) ? ^ ----- + nose.tools.assert_equal(ld.mapped_base, 0x7ffff7ddc000) ? ^^^^ ++ def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
3f178359b8649b6b92900ae790e894971405b720
main.py
main.py
from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) #The execution for line in commands: seats = execute.execute_cmmds(seats, line) counted_after = count.count_array(x, y, seats) counter_occupied = 1000000 - counted_after return counter_occupied results = main(1000, 1000, 'inputfile.txt') print("Cool")
from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) #The execution for line in commands: seats = execute.execute_cmmds(seats, line) counted_after = count.count_array(x, y, seats) counter_occupied = 1000000 - counted_after return counter_occupied results = main(1000, 1000, 'inputfile.txt') print("Cool") print("Other")
CLEAN TEMPLATE Clean up the project template further still
CLEAN TEMPLATE Clean up the project template further still
Python
bsd-2-clause
kevindiltinero/seass3
from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) #The execution for line in commands: seats = execute.execute_cmmds(seats, line) counted_after = count.count_array(x, y, seats) counter_occupied = 1000000 - counted_after return counter_occupied results = main(1000, 1000, 'inputfile.txt') print("Cool") + print("Other")
CLEAN TEMPLATE Clean up the project template further still
## Code Before: from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) #The execution for line in commands: seats = execute.execute_cmmds(seats, line) counted_after = count.count_array(x, y, seats) counter_occupied = 1000000 - counted_after return counter_occupied results = main(1000, 1000, 'inputfile.txt') print("Cool") ## Instruction: CLEAN TEMPLATE Clean up the project template further still ## Code After: from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) #The execution for line in commands: seats = execute.execute_cmmds(seats, line) counted_after = count.count_array(x, y, seats) counter_occupied = 1000000 - counted_after return counter_occupied results = main(1000, 1000, 'inputfile.txt') print("Cool") print("Other")
from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) #The execution for line in commands: seats = execute.execute_cmmds(seats, line) counted_after = count.count_array(x, y, seats) counter_occupied = 1000000 - counted_after return counter_occupied results = main(1000, 1000, 'inputfile.txt') print("Cool") + print("Other")
25dfc009b380b2a63619651dbcba2c7d7ade929c
deep_parse.py
deep_parse.py
class DeepParseObject(object): """Simple dummy object to hold content.""" pass def deep_parse_dict(content, fields, exc_class=Exception, separator='__'): """Extracting fields specified in ``fields`` from ``content``.""" deep_parse = DeepParseObject() for field in fields: try: lookup_name, store_name = field[0], field[0] if len(field) > 1: lookup_name, store_name = field parts = lookup_name.split(separator) value = content for part in parts: value = value[part] setattr(deep_parse, store_name, value) except Exception as original_exc: exc = exc_class('Error parsing field %r' % field) exc.error_field = field exc.original_exc = original_exc raise exc return deep_parse
class DeepParseObject(object): """Simple dummy object to hold content.""" def __str__(self): return 'DeepParseObject: %s' % self.__dict__ def __repr__(self): return 'DeepParseObject: %r' % self.__dict__ def deep_parse_dict(content, fields, exc_class=Exception, separator='__'): """Extracting fields specified in ``fields`` from ``content``.""" deep_parse = DeepParseObject() for field in fields: try: lookup_name, store_name = field[0], field[0] if len(field) > 1: lookup_name, store_name = field parts = lookup_name.split(separator) value = content for part in parts: value = value[part] setattr(deep_parse, store_name, value) except Exception as original_exc: exc = exc_class('Error parsing field %r' % field) exc.error_field = field exc.original_exc = original_exc raise exc return deep_parse
Add __repr__ and __str__ methods to dummy object.
Add __repr__ and __str__ methods to dummy object.
Python
mit
bradojevic/deep-parse
class DeepParseObject(object): """Simple dummy object to hold content.""" - pass + + def __str__(self): + return 'DeepParseObject: %s' % self.__dict__ + + def __repr__(self): + return 'DeepParseObject: %r' % self.__dict__ def deep_parse_dict(content, fields, exc_class=Exception, separator='__'): """Extracting fields specified in ``fields`` from ``content``.""" deep_parse = DeepParseObject() for field in fields: try: lookup_name, store_name = field[0], field[0] if len(field) > 1: lookup_name, store_name = field parts = lookup_name.split(separator) value = content for part in parts: value = value[part] setattr(deep_parse, store_name, value) except Exception as original_exc: exc = exc_class('Error parsing field %r' % field) exc.error_field = field exc.original_exc = original_exc raise exc return deep_parse
Add __repr__ and __str__ methods to dummy object.
## Code Before: class DeepParseObject(object): """Simple dummy object to hold content.""" pass def deep_parse_dict(content, fields, exc_class=Exception, separator='__'): """Extracting fields specified in ``fields`` from ``content``.""" deep_parse = DeepParseObject() for field in fields: try: lookup_name, store_name = field[0], field[0] if len(field) > 1: lookup_name, store_name = field parts = lookup_name.split(separator) value = content for part in parts: value = value[part] setattr(deep_parse, store_name, value) except Exception as original_exc: exc = exc_class('Error parsing field %r' % field) exc.error_field = field exc.original_exc = original_exc raise exc return deep_parse ## Instruction: Add __repr__ and __str__ methods to dummy object. ## Code After: class DeepParseObject(object): """Simple dummy object to hold content.""" def __str__(self): return 'DeepParseObject: %s' % self.__dict__ def __repr__(self): return 'DeepParseObject: %r' % self.__dict__ def deep_parse_dict(content, fields, exc_class=Exception, separator='__'): """Extracting fields specified in ``fields`` from ``content``.""" deep_parse = DeepParseObject() for field in fields: try: lookup_name, store_name = field[0], field[0] if len(field) > 1: lookup_name, store_name = field parts = lookup_name.split(separator) value = content for part in parts: value = value[part] setattr(deep_parse, store_name, value) except Exception as original_exc: exc = exc_class('Error parsing field %r' % field) exc.error_field = field exc.original_exc = original_exc raise exc return deep_parse
class DeepParseObject(object): """Simple dummy object to hold content.""" - pass + + def __str__(self): + return 'DeepParseObject: %s' % self.__dict__ + + def __repr__(self): + return 'DeepParseObject: %r' % self.__dict__ def deep_parse_dict(content, fields, exc_class=Exception, separator='__'): """Extracting fields specified in ``fields`` from ``content``.""" deep_parse = DeepParseObject() for field in fields: try: lookup_name, store_name = field[0], field[0] if len(field) > 1: lookup_name, store_name = field parts = lookup_name.split(separator) value = content for part in parts: value = value[part] setattr(deep_parse, store_name, value) except Exception as original_exc: exc = exc_class('Error parsing field %r' % field) exc.error_field = field exc.original_exc = original_exc raise exc return deep_parse
c6346fa2c026318b530dbbdc90dbaee8310b6b05
robot/Cumulus/resources/locators_50.py
robot/Cumulus/resources/locators_50.py
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']"
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" # stashed (Noah's version) # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]'
Revert "Revert "changes in locator_50 file (current and old versions)""
Revert "Revert "changes in locator_50 file (current and old versions)"" This reverts commit 7537387aa80109877d6659cc54ec0ee7aa6496bd.
Python
bsd-3-clause
SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) + + # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" + + # stashed (Noah's version) + + # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" + # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" + # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' + +
Revert "Revert "changes in locator_50 file (current and old versions)""
## Code Before: from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" ## Instruction: Revert "Revert "changes in locator_50 file (current and old versions)"" ## Code After: from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" # stashed (Noah's version) # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]'
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) + + # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" + + # stashed (Noah's version) + + # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" + # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" + # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' +
32f38eb01c3a203ae35d70b485fcee7b13f1acde
tests/help_generation_test.py
tests/help_generation_test.py
"""Test that we can generate help for PKB.""" import os import unittest from perfkitbenchmarker import flags # Import pkb to add all flag definitions to flags.FLAGS. from perfkitbenchmarker import pkb # NOQA class HelpTest(unittest.TestCase): def testHelp(self): # Test that help generation finishes without errors flags.FLAGS.GetHelp() class HelpXMLTest(unittest.TestCase): def testHelpXML(self): with open(os.devnull, 'w') as out: flags.FLAGS.WriteHelpInXMLFormat(outfile=out) if __name__ == '__main__': unittest.main()
"""Test that we can generate help for PKB.""" import os import unittest from perfkitbenchmarker import flags # Import pkb to add all flag definitions to flags.FLAGS. from perfkitbenchmarker import pkb # NOQA class HelpTest(unittest.TestCase): def testHelp(self): # Test that help generation finishes without errors if hasattr(flags.FLAGS, 'get_help'): flags.FLAGS.get_help() else: flags.FLAGS.GetHelp() class HelpXMLTest(unittest.TestCase): def testHelpXML(self): with open(os.devnull, 'w') as out: flags.FLAGS.WriteHelpInXMLFormat(outfile=out) if __name__ == '__main__': unittest.main()
Call FLAGS.get_help if it's available.
Call FLAGS.get_help if it's available.
Python
apache-2.0
GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,meteorfox/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,meteorfox/PerfKitBenchmarker
"""Test that we can generate help for PKB.""" import os import unittest from perfkitbenchmarker import flags # Import pkb to add all flag definitions to flags.FLAGS. from perfkitbenchmarker import pkb # NOQA class HelpTest(unittest.TestCase): def testHelp(self): # Test that help generation finishes without errors + if hasattr(flags.FLAGS, 'get_help'): + flags.FLAGS.get_help() + else: - flags.FLAGS.GetHelp() + flags.FLAGS.GetHelp() class HelpXMLTest(unittest.TestCase): def testHelpXML(self): with open(os.devnull, 'w') as out: flags.FLAGS.WriteHelpInXMLFormat(outfile=out) if __name__ == '__main__': unittest.main()
Call FLAGS.get_help if it's available.
## Code Before: """Test that we can generate help for PKB.""" import os import unittest from perfkitbenchmarker import flags # Import pkb to add all flag definitions to flags.FLAGS. from perfkitbenchmarker import pkb # NOQA class HelpTest(unittest.TestCase): def testHelp(self): # Test that help generation finishes without errors flags.FLAGS.GetHelp() class HelpXMLTest(unittest.TestCase): def testHelpXML(self): with open(os.devnull, 'w') as out: flags.FLAGS.WriteHelpInXMLFormat(outfile=out) if __name__ == '__main__': unittest.main() ## Instruction: Call FLAGS.get_help if it's available. ## Code After: """Test that we can generate help for PKB.""" import os import unittest from perfkitbenchmarker import flags # Import pkb to add all flag definitions to flags.FLAGS. from perfkitbenchmarker import pkb # NOQA class HelpTest(unittest.TestCase): def testHelp(self): # Test that help generation finishes without errors if hasattr(flags.FLAGS, 'get_help'): flags.FLAGS.get_help() else: flags.FLAGS.GetHelp() class HelpXMLTest(unittest.TestCase): def testHelpXML(self): with open(os.devnull, 'w') as out: flags.FLAGS.WriteHelpInXMLFormat(outfile=out) if __name__ == '__main__': unittest.main()
"""Test that we can generate help for PKB.""" import os import unittest from perfkitbenchmarker import flags # Import pkb to add all flag definitions to flags.FLAGS. from perfkitbenchmarker import pkb # NOQA class HelpTest(unittest.TestCase): def testHelp(self): # Test that help generation finishes without errors + if hasattr(flags.FLAGS, 'get_help'): + flags.FLAGS.get_help() + else: - flags.FLAGS.GetHelp() + flags.FLAGS.GetHelp() ? ++ class HelpXMLTest(unittest.TestCase): def testHelpXML(self): with open(os.devnull, 'w') as out: flags.FLAGS.WriteHelpInXMLFormat(outfile=out) if __name__ == '__main__': unittest.main()
7b77297f9099019f4424c7115deb933dd51eaf80
setup.py
setup.py
from distutils.core import setup, Extension setup( name = 'Encoder', version = '1.0', description = 'Encode stuff', ext_modules = [ Extension( name = '_encoder', sources = [ 'src/encoder.c', 'src/module.c', ], include_dirs = [ 'include', ], ), ], )
from distutils.core import setup, Extension setup( name = 'Encoder', version = '1.0', description = 'Encode stuff', ext_modules = [ Extension( name = '_encoder', sources = [ 'src/encoder.c', 'src/module.c', ], include_dirs = [ 'include', ], depends = [ 'include/buffer.h', # As this is essentially a source file ], ), ], )
Include buffer.h as a dependency for rebuilds
Include buffer.h as a dependency for rebuilds
Python
apache-2.0
blake-sheridan/py-serializer,blake-sheridan/py-serializer
from distutils.core import setup, Extension setup( name = 'Encoder', version = '1.0', description = 'Encode stuff', ext_modules = [ Extension( name = '_encoder', sources = [ 'src/encoder.c', 'src/module.c', ], include_dirs = [ 'include', ], + depends = [ + 'include/buffer.h', # As this is essentially a source file + ], ), ], )
Include buffer.h as a dependency for rebuilds
## Code Before: from distutils.core import setup, Extension setup( name = 'Encoder', version = '1.0', description = 'Encode stuff', ext_modules = [ Extension( name = '_encoder', sources = [ 'src/encoder.c', 'src/module.c', ], include_dirs = [ 'include', ], ), ], ) ## Instruction: Include buffer.h as a dependency for rebuilds ## Code After: from distutils.core import setup, Extension setup( name = 'Encoder', version = '1.0', description = 'Encode stuff', ext_modules = [ Extension( name = '_encoder', sources = [ 'src/encoder.c', 'src/module.c', ], include_dirs = [ 'include', ], depends = [ 'include/buffer.h', # As this is essentially a source file ], ), ], )
from distutils.core import setup, Extension setup( name = 'Encoder', version = '1.0', description = 'Encode stuff', ext_modules = [ Extension( name = '_encoder', sources = [ 'src/encoder.c', 'src/module.c', ], include_dirs = [ 'include', ], + depends = [ + 'include/buffer.h', # As this is essentially a source file + ], ), ], )
5f9cf67c473ef7d304da067b70b56d77f71ca4fa
web/impact/impact/middleware/method_override_middleware.py
web/impact/impact/middleware/method_override_middleware.py
METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override' class MethodOverrideMiddleware(object): def process_request(self, request): if request.method != 'POST': return if METHOD_OVERRIDE_HEADER not in request.META: return request.method = request.META[METHOD_OVERRIDE_HEADER]
METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' class MethodOverrideMiddleware(object): def process_request(self, request): if request.method != 'POST': return if METHOD_OVERRIDE_HEADER not in request.META: return print(request.META) request.method = request.META[METHOD_OVERRIDE_HEADER] print(request.META)
Revert Changes To Middleware To Prevent Build Hangup
[AC-4959] Revert Changes To Middleware To Prevent Build Hangup
Python
mit
masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api
- METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override' + + METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' class MethodOverrideMiddleware(object): def process_request(self, request): if request.method != 'POST': return if METHOD_OVERRIDE_HEADER not in request.META: return + print(request.META) request.method = request.META[METHOD_OVERRIDE_HEADER] + print(request.META)
Revert Changes To Middleware To Prevent Build Hangup
## Code Before: METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override' class MethodOverrideMiddleware(object): def process_request(self, request): if request.method != 'POST': return if METHOD_OVERRIDE_HEADER not in request.META: return request.method = request.META[METHOD_OVERRIDE_HEADER] ## Instruction: Revert Changes To Middleware To Prevent Build Hangup ## Code After: METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' class MethodOverrideMiddleware(object): def process_request(self, request): if request.method != 'POST': return if METHOD_OVERRIDE_HEADER not in request.META: return print(request.META) request.method = request.META[METHOD_OVERRIDE_HEADER] print(request.META)
- METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override' + + METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' class MethodOverrideMiddleware(object): def process_request(self, request): if request.method != 'POST': return if METHOD_OVERRIDE_HEADER not in request.META: return + print(request.META) request.method = request.META[METHOD_OVERRIDE_HEADER] + print(request.META)
70efbd90d9d5601d368ddb5ea20a3b9910539b78
members/urls.py
members/urls.py
from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'), url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'), url(r'^profile/$', 'members.views.user_projects', name='user-projects'), )
from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'), url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'), url(r'^profile/$', 'members.views.user_projects', name='user-projects'), )
Change url and views for login/logout to django Defaults
Change url and views for login/logout to django Defaults
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
from django.conf.urls import patterns, url - from django.contrib import auth urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'), url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'), url(r'^profile/$', 'members.views.user_projects', name='user-projects'), )
Change url and views for login/logout to django Defaults
## Code Before: from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'), url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'), url(r'^profile/$', 'members.views.user_projects', name='user-projects'), ) ## Instruction: Change url and views for login/logout to django Defaults ## Code After: from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'), url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'), url(r'^profile/$', 'members.views.user_projects', name='user-projects'), )
from django.conf.urls import patterns, url - from django.contrib import auth urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'), url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'), url(r'^profile/$', 'members.views.user_projects', name='user-projects'), )
6ba8e942edaf424c7b20983a5e829736c38b8110
froide/foiidea/tasks.py
froide/foiidea/tasks.py
import sys from celery.task import task from django.conf import settings from django.utils import translation from django.db import transaction from .crawler import crawl_source_by_id from .models import Article @task def fetch_articles(source_id): translation.activate(settings.LANGUAGE_CODE) def run(source_id): try: crawl_source_by_id(int(source_id)) except Exception: transaction.rollback() return sys.exc_info() else: transaction.commit() return None run = transaction.commit_manually(run) exc_info = run(source_id) if exc_info is not None: from sentry.client.models import client client.create_from_exception(exc_info=exc_info, view="froide.foiidea.tasks.fetch_articles") @task def recalculate_order(): Article.objects.recalculate_order()
from celery.task import task from django.conf import settings from django.utils import translation from .crawler import crawl_source_by_id from .models import Article @task def fetch_articles(source_id): translation.activate(settings.LANGUAGE_CODE) crawl_source_by_id(int(source_id)) @task def recalculate_order(): Article.objects.recalculate_order()
Remove complex exception mechanism for celery task
Remove complex exception mechanism for celery task
Python
mit
ryankanno/froide,stefanw/froide,ryankanno/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,CodeforHawaii/froide,stefanw/froide,LilithWittmann/froide,fin/froide,LilithWittmann/froide,catcosmo/froide,catcosmo/froide,stefanw/froide,CodeforHawaii/froide,ryankanno/froide,fin/froide,stefanw/froide,catcosmo/froide,stefanw/froide,okfse/froide,okfse/froide,LilithWittmann/froide,CodeforHawaii/froide,ryankanno/froide,okfse/froide,fin/froide,catcosmo/froide,okfse/froide,okfse/froide,LilithWittmann/froide,catcosmo/froide,CodeforHawaii/froide,fin/froide
- import sys - from celery.task import task from django.conf import settings from django.utils import translation - from django.db import transaction from .crawler import crawl_source_by_id from .models import Article @task def fetch_articles(source_id): translation.activate(settings.LANGUAGE_CODE) - - def run(source_id): - try: - crawl_source_by_id(int(source_id)) + crawl_source_by_id(int(source_id)) - except Exception: - transaction.rollback() - return sys.exc_info() - else: - transaction.commit() - return None - run = transaction.commit_manually(run) - exc_info = run(source_id) - if exc_info is not None: - from sentry.client.models import client - client.create_from_exception(exc_info=exc_info, view="froide.foiidea.tasks.fetch_articles") @task def recalculate_order(): Article.objects.recalculate_order()
Remove complex exception mechanism for celery task
## Code Before: import sys from celery.task import task from django.conf import settings from django.utils import translation from django.db import transaction from .crawler import crawl_source_by_id from .models import Article @task def fetch_articles(source_id): translation.activate(settings.LANGUAGE_CODE) def run(source_id): try: crawl_source_by_id(int(source_id)) except Exception: transaction.rollback() return sys.exc_info() else: transaction.commit() return None run = transaction.commit_manually(run) exc_info = run(source_id) if exc_info is not None: from sentry.client.models import client client.create_from_exception(exc_info=exc_info, view="froide.foiidea.tasks.fetch_articles") @task def recalculate_order(): Article.objects.recalculate_order() ## Instruction: Remove complex exception mechanism for celery task ## Code After: from celery.task import task from django.conf import settings from django.utils import translation from .crawler import crawl_source_by_id from .models import Article @task def fetch_articles(source_id): translation.activate(settings.LANGUAGE_CODE) crawl_source_by_id(int(source_id)) @task def recalculate_order(): Article.objects.recalculate_order()
- import sys - from celery.task import task from django.conf import settings from django.utils import translation - from django.db import transaction from .crawler import crawl_source_by_id from .models import Article @task def fetch_articles(source_id): translation.activate(settings.LANGUAGE_CODE) - - def run(source_id): - try: - crawl_source_by_id(int(source_id)) ? -------- + crawl_source_by_id(int(source_id)) - except Exception: - transaction.rollback() - return sys.exc_info() - else: - transaction.commit() - return None - run = transaction.commit_manually(run) - exc_info = run(source_id) - if exc_info is not None: - from sentry.client.models import client - client.create_from_exception(exc_info=exc_info, view="froide.foiidea.tasks.fetch_articles") @task def recalculate_order(): Article.objects.recalculate_order()
6c54fc230e8c889a2351f20b524382a5c6e29d1c
examples/apps.py
examples/apps.py
import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN.') sys.exit(1) api = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this token has access to for app in api.apps: print(app.name) # Update one specific app api.apps.update('my-awesome-app', {'description': 'My awesome app'}) # Get information for one app app = App.get('my-awesome-app') print('%s: %s' % (app.name, app.description)) # List all services instances for app for service in app.services: print('Service: %s' % service.name)
import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN env variables.') sys.exit(1) # Creating TsuruClient instance tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this user has access to for app in tsuru.apps.list(): print('App: {}'.format(app.name)) # Get information for one app app = tsuru.apps.get('my-awesome-app') print('{app.name}: {app.description}'.format(app=app)) # Update specific app tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
Update examples to match docs
Update examples to match docs Use the interface defined in the docs in the examples scripts.
Python
mit
rcmachado/pysuru
import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: - print('You must set TSURU_TARGET and TSURU_TOKEN.') + print('You must set TSURU_TARGET and TSURU_TOKEN env variables.') sys.exit(1) + # Creating TsuruClient instance - api = TsuruClient(TSURU_TARGET, TSURU_TOKEN) + tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN) - # List all apps that this token has access to + # List all apps that this user has access to + for app in tsuru.apps.list(): + print('App: {}'.format(app.name)) - for app in api.apps: - print(app.name) - - # Update one specific app - api.apps.update('my-awesome-app', {'description': 'My awesome app'}) # Get information for one app - app = App.get('my-awesome-app') + app = tsuru.apps.get('my-awesome-app') - print('%s: %s' % (app.name, app.description)) + print('{app.name}: {app.description}'.format(app=app)) + # Update specific app + tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'}) - # List all services instances for app - for service in app.services: - print('Service: %s' % service.name)
Update examples to match docs
## Code Before: import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN.') sys.exit(1) api = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this token has access to for app in api.apps: print(app.name) # Update one specific app api.apps.update('my-awesome-app', {'description': 'My awesome app'}) # Get information for one app app = App.get('my-awesome-app') print('%s: %s' % (app.name, app.description)) # List all services instances for app for service in app.services: print('Service: %s' % service.name) ## Instruction: Update examples to match docs ## Code After: import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN env variables.') sys.exit(1) # Creating TsuruClient instance tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this user has access to for app in tsuru.apps.list(): print('App: {}'.format(app.name)) # Get information for one app app = tsuru.apps.get('my-awesome-app') print('{app.name}: {app.description}'.format(app=app)) # Update specific app tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: - print('You must set TSURU_TARGET and TSURU_TOKEN.') + print('You must set TSURU_TARGET and TSURU_TOKEN env variables.') ? ++++++++++++++ sys.exit(1) + # Creating TsuruClient instance - api = TsuruClient(TSURU_TARGET, TSURU_TOKEN) ? ^^^ + tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN) ? ^^^^^ - # List all apps that this token has access to ? ^^^ ^ + # List all apps that this user has access to ? ^^ ^ + for app in tsuru.apps.list(): + print('App: {}'.format(app.name)) - for app in api.apps: - print(app.name) - - # Update one specific app - api.apps.update('my-awesome-app', {'description': 'My awesome app'}) # Get information for one app - app = App.get('my-awesome-app') ? ^ + app = tsuru.apps.get('my-awesome-app') ? ^^^^^^^ + - print('%s: %s' % (app.name, app.description)) + print('{app.name}: {app.description}'.format(app=app)) + # Update specific app + tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'}) - # List all services instances for app - for service in app.services: - print('Service: %s' % service.name)
9f091fcc572eb6a65592f828818b34d3e1269083
alg_bellman_ford_shortest_path.py
alg_bellman_ford_shortest_path.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def bellman_ford(w_graph_d, start_vertex): """Bellman-Ford algorithm for weighted / negative graph. """ pass def main(): w_graph_d = { 's': {'a': 2, 'b': 6}, 'a': {'b': 3}, 'b': {'a': -5} } start_vertex = 's' if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def bellman_ford(w_graph_d, start_vertex): """Bellman-Ford algorithm for weighted / negative graph. """ pass def main(): w_graph_d = { 's': {'a': 2, 'b': 6}, 'a': {'b': 3, 'c': 1}, 'b': {'a': -5, 'd': 2}, 'c': {'b': 1, 'e': 4, 'f': 2}, 'd': {'c': 3, 'f': 2}, 'e': {}, 'f': {'e': 1} } start_vertex = 's' if __name__ == '__main__': main()
Revise main()'s weighted negative graph
Revise main()'s weighted negative graph
Python
bsd-2-clause
bowen0701/algorithms_data_structures
from __future__ import absolute_import from __future__ import print_function from __future__ import division def bellman_ford(w_graph_d, start_vertex): """Bellman-Ford algorithm for weighted / negative graph. """ pass def main(): w_graph_d = { 's': {'a': 2, 'b': 6}, - 'a': {'b': 3}, + 'a': {'b': 3, 'c': 1}, + 'b': {'a': -5, 'd': 2}, + 'c': {'b': 1, 'e': 4, 'f': 2}, + 'd': {'c': 3, 'f': 2}, + 'e': {}, - 'b': {'a': -5} + 'f': {'e': 1} } start_vertex = 's' if __name__ == '__main__': main()
Revise main()'s weighted negative graph
## Code Before: from __future__ import absolute_import from __future__ import print_function from __future__ import division def bellman_ford(w_graph_d, start_vertex): """Bellman-Ford algorithm for weighted / negative graph. """ pass def main(): w_graph_d = { 's': {'a': 2, 'b': 6}, 'a': {'b': 3}, 'b': {'a': -5} } start_vertex = 's' if __name__ == '__main__': main() ## Instruction: Revise main()'s weighted negative graph ## Code After: from __future__ import absolute_import from __future__ import print_function from __future__ import division def bellman_ford(w_graph_d, start_vertex): """Bellman-Ford algorithm for weighted / negative graph. """ pass def main(): w_graph_d = { 's': {'a': 2, 'b': 6}, 'a': {'b': 3, 'c': 1}, 'b': {'a': -5, 'd': 2}, 'c': {'b': 1, 'e': 4, 'f': 2}, 'd': {'c': 3, 'f': 2}, 'e': {}, 'f': {'e': 1} } start_vertex = 's' if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def bellman_ford(w_graph_d, start_vertex): """Bellman-Ford algorithm for weighted / negative graph. """ pass def main(): w_graph_d = { 's': {'a': 2, 'b': 6}, - 'a': {'b': 3}, + 'a': {'b': 3, 'c': 1}, ? ++++++++ + 'b': {'a': -5, 'd': 2}, + 'c': {'b': 1, 'e': 4, 'f': 2}, + 'd': {'c': 3, 'f': 2}, + 'e': {}, - 'b': {'a': -5} ? ^ ^ ^^ + 'f': {'e': 1} ? ^ ^ ^ } start_vertex = 's' if __name__ == '__main__': main()
0b13092a7854fe2d967d057221420a57b7a37b16
linter.py
linter.py
"""This module exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
"""Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
Change module docstring to make Travis CI build pass
Change module docstring to make Travis CI build pass
Python
mit
jackbrewer/SublimeLinter-contrib-stylint
- """This module exports the Stylint plugin class.""" + """Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
Change module docstring to make Travis CI build pass
## Code Before: """This module exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~') ## Instruction: Change module docstring to make Travis CI build pass ## Code After: """Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
- """This module exports the Stylint plugin class.""" ? ^^^^^^^^^^^^^ + """Exports the Stylint plugin class.""" ? ^ from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
fd6702fbb43eb4e6c5129ac6026908946f03c1a7
paws/handler.py
paws/handler.py
from .request import Request from .response import response class Handler(object): ''' Simple dispatcher class. ''' def __call__(self, event, context): self.request = request = Request(event, context) func = getattr(self, self.event['httpMethod'], self.invalid) return func(request, *self.event['pathParameters']) def invalid(self, *args): return response(status=405)
from .request import Request from .response import response class Handler(object): ''' Simple dispatcher class. ''' def __init__(self, event, context): self.request = Request(event, context) def __call__(self, event, context): func = getattr(self, self.event['httpMethod'], self.invalid) return func(self.request, *self.event['pathParameters']) def invalid(self, *args): return response(status=405)
Move request construction to init
Move request construction to init
Python
bsd-3-clause
funkybob/paws
from .request import Request from .response import response class Handler(object): ''' Simple dispatcher class. ''' + def __init__(self, event, context): + self.request = Request(event, context) def __call__(self, event, context): - self.request = request = Request(event, context) func = getattr(self, self.event['httpMethod'], self.invalid) - return func(request, *self.event['pathParameters']) + return func(self.request, *self.event['pathParameters']) def invalid(self, *args): return response(status=405)
Move request construction to init
## Code Before: from .request import Request from .response import response class Handler(object): ''' Simple dispatcher class. ''' def __call__(self, event, context): self.request = request = Request(event, context) func = getattr(self, self.event['httpMethod'], self.invalid) return func(request, *self.event['pathParameters']) def invalid(self, *args): return response(status=405) ## Instruction: Move request construction to init ## Code After: from .request import Request from .response import response class Handler(object): ''' Simple dispatcher class. ''' def __init__(self, event, context): self.request = Request(event, context) def __call__(self, event, context): func = getattr(self, self.event['httpMethod'], self.invalid) return func(self.request, *self.event['pathParameters']) def invalid(self, *args): return response(status=405)
from .request import Request from .response import response class Handler(object): ''' Simple dispatcher class. ''' + def __init__(self, event, context): + self.request = Request(event, context) def __call__(self, event, context): - self.request = request = Request(event, context) func = getattr(self, self.event['httpMethod'], self.invalid) - return func(request, *self.event['pathParameters']) + return func(self.request, *self.event['pathParameters']) ? +++++ def invalid(self, *args): return response(status=405)
c01d29b4b2839976fd457a1e950ed5800150b315
setup.py
setup.py
from distutils.core import setup # Load in babel support, if available. try: from babel.messages import frontend as babel cmdclass = {"compile_catalog": babel.compile_catalog, "extract_messages": babel.extract_messages, "init_catalog": babel.init_catalog, "update_catalog": babel.update_catalog,} except ImportError: cmdclass = {} setup(name="django-money", version="0.1", description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.", url="https://github.com/jakewins/django-money", packages=["djmoney", "djmoney.forms", "djmoney.models"], # Commented out, waiting for pull request to be fulfilled: https://github.com/limist/py-moneyed/pull/1 #install_requires=['setuptools', # 'Django >= 1.2', # 'py-moneyed > 0.3'], # package_dir={"": ""}, cmdclass = cmdclass, classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django",])
from distutils.core import setup # Load in babel support, if available. try: from babel.messages import frontend as babel cmdclass = {"compile_catalog": babel.compile_catalog, "extract_messages": babel.extract_messages, "init_catalog": babel.init_catalog, "update_catalog": babel.update_catalog,} except ImportError: cmdclass = {} setup(name="django-money", version="0.1", description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.", url="https://github.com/jakewins/django-money", packages=["djmoney", "djmoney.forms", "djmoney.models"], install_requires=['setuptools', 'Django >= 1.2', 'py-moneyed > 0.4'], cmdclass = cmdclass, classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django",])
Update dependencies so installation is simpler.
Update dependencies so installation is simpler. The pull request, and a new release of py-moneyed has occurred.
Python
bsd-3-clause
recklessromeo/django-money,AlexRiina/django-money,iXioN/django-money,iXioN/django-money,rescale/django-money,recklessromeo/django-money,pjdelport/django-money,tsouvarev/django-money,tsouvarev/django-money
from distutils.core import setup # Load in babel support, if available. try: from babel.messages import frontend as babel cmdclass = {"compile_catalog": babel.compile_catalog, "extract_messages": babel.extract_messages, "init_catalog": babel.init_catalog, "update_catalog": babel.update_catalog,} except ImportError: cmdclass = {} setup(name="django-money", version="0.1", description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.", url="https://github.com/jakewins/django-money", packages=["djmoney", "djmoney.forms", "djmoney.models"], - # Commented out, waiting for pull request to be fulfilled: https://github.com/limist/py-moneyed/pull/1 - #install_requires=['setuptools', + install_requires=['setuptools', - # 'Django >= 1.2', + 'Django >= 1.2', - # 'py-moneyed > 0.3'], + 'py-moneyed > 0.4'], - # package_dir={"": ""}, cmdclass = cmdclass, classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django",]) - -
Update dependencies so installation is simpler.
## Code Before: from distutils.core import setup # Load in babel support, if available. try: from babel.messages import frontend as babel cmdclass = {"compile_catalog": babel.compile_catalog, "extract_messages": babel.extract_messages, "init_catalog": babel.init_catalog, "update_catalog": babel.update_catalog,} except ImportError: cmdclass = {} setup(name="django-money", version="0.1", description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.", url="https://github.com/jakewins/django-money", packages=["djmoney", "djmoney.forms", "djmoney.models"], # Commented out, waiting for pull request to be fulfilled: https://github.com/limist/py-moneyed/pull/1 #install_requires=['setuptools', # 'Django >= 1.2', # 'py-moneyed > 0.3'], # package_dir={"": ""}, cmdclass = cmdclass, classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django",]) ## Instruction: Update dependencies so installation is simpler. ## Code After: from distutils.core import setup # Load in babel support, if available. try: from babel.messages import frontend as babel cmdclass = {"compile_catalog": babel.compile_catalog, "extract_messages": babel.extract_messages, "init_catalog": babel.init_catalog, "update_catalog": babel.update_catalog,} except ImportError: cmdclass = {} setup(name="django-money", version="0.1", description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.", url="https://github.com/jakewins/django-money", packages=["djmoney", "djmoney.forms", "djmoney.models"], install_requires=['setuptools', 'Django >= 1.2', 'py-moneyed > 0.4'], cmdclass = cmdclass, classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django",])
from distutils.core import setup # Load in babel support, if available. try: from babel.messages import frontend as babel cmdclass = {"compile_catalog": babel.compile_catalog, "extract_messages": babel.extract_messages, "init_catalog": babel.init_catalog, "update_catalog": babel.update_catalog,} except ImportError: cmdclass = {} setup(name="django-money", version="0.1", description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.", url="https://github.com/jakewins/django-money", packages=["djmoney", "djmoney.forms", "djmoney.models"], - # Commented out, waiting for pull request to be fulfilled: https://github.com/limist/py-moneyed/pull/1 - #install_requires=['setuptools', ? - + install_requires=['setuptools', - # 'Django >= 1.2', ? - + 'Django >= 1.2', - # 'py-moneyed > 0.3'], ? - ^ + 'py-moneyed > 0.4'], ? ^ - # package_dir={"": ""}, cmdclass = cmdclass, classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django",]) - -
55b7b07986590c4ab519fcda3c973c87ad23596b
flask_admin/model/typefmt.py
flask_admin/model/typefmt.py
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ return Markup('<i class="icon-ok"></i>' if value else '') DEFAULT_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter }
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ return Markup('<i class="icon-ok"></i>' if value else '') def list_formatter(values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(values) DEFAULT_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
Add extra type formatter for `list` type
Add extra type formatter for `list` type
Python
bsd-3-clause
mrjoes/flask-admin,janusnic/flask-admin,Kha/flask-admin,wuxiangfeng/flask-admin,litnimax/flask-admin,HermasT/flask-admin,quokkaproject/flask-admin,Kha/flask-admin,flabe81/flask-admin,porduna/flask-admin,Junnplus/flask-admin,ibushong/test-repo,janusnic/flask-admin,jschneier/flask-admin,closeio/flask-admin,chase-seibert/flask-admin,litnimax/flask-admin,ArtemSerga/flask-admin,flask-admin/flask-admin,NickWoodhams/flask-admin,LennartP/flask-admin,late-warrior/flask-admin,likaiguo/flask-admin,iurisilvio/flask-admin,mikelambert/flask-admin,jamesbeebop/flask-admin,quokkaproject/flask-admin,mrjoes/flask-admin,pawl/flask-admin,jschneier/flask-admin,toddetzel/flask-admin,rochacbruno/flask-admin,ArtemSerga/flask-admin,Junnplus/flask-admin,torotil/flask-admin,ondoheer/flask-admin,plaes/flask-admin,AlmogCohen/flask-admin,plaes/flask-admin,wangjun/flask-admin,dxmo/flask-admin,jmagnusson/flask-admin,marrybird/flask-admin,torotil/flask-admin,wuxiangfeng/flask-admin,CoolCloud/flask-admin,toddetzel/flask-admin,lifei/flask-admin,ondoheer/flask-admin,phantomxc/flask-admin,mikelambert/flask-admin,mrjoes/flask-admin,petrus-jvrensburg/flask-admin,CoolCloud/flask-admin,wangjun/flask-admin,iurisilvio/flask-admin,petrus-jvrensburg/flask-admin,lifei/flask-admin,mikelambert/flask-admin,sfermigier/flask-admin,radioprotector/flask-admin,wuxiangfeng/flask-admin,petrus-jvrensburg/flask-admin,iurisilvio/flask-admin,likaiguo/flask-admin,jschneier/flask-admin,litnimax/flask-admin,flask-admin/flask-admin,petrus-jvrensburg/flask-admin,plaes/flask-admin,ibushong/test-repo,flask-admin/flask-admin,torotil/flask-admin,radioprotector/flask-admin,rochacbruno/flask-admin,wuxiangfeng/flask-admin,HermasT/flask-admin,LennartP/flask-admin,marrybird/flask-admin,dxmo/flask-admin,flask-admin/flask-admin,phantomxc/flask-admin,LennartP/flask-admin,chase-seibert/flask-admin,plaes/flask-admin,marrybird/flask-admin,mikelambert/flask-admin,wangjun/flask-admin,ArtemSerga/flask-admin,AlmogCohen/flask-admin,AlmogCohen/flask-admin,ondoheer/flask-admin,closeio/flask-admin,rochacbruno/flask-admin,flabe81/flask-admin,AlmogCohen/flask-admin,lifei/flask-admin,jmagnusson/flask-admin,mrjoes/flask-admin,pawl/flask-admin,torotil/flask-admin,likaiguo/flask-admin,HermasT/flask-admin,flabe81/flask-admin,porduna/flask-admin,iurisilvio/flask-admin,NickWoodhams/flask-admin,late-warrior/flask-admin,porduna/flask-admin,radioprotector/flask-admin,chase-seibert/flask-admin,CoolCloud/flask-admin,toddetzel/flask-admin,betterlife/flask-admin,betterlife/flask-admin,lifei/flask-admin,porduna/flask-admin,quokkaproject/flask-admin,rochacbruno/flask-admin,jschneier/flask-admin,late-warrior/flask-admin,pawl/flask-admin,toddetzel/flask-admin,phantomxc/flask-admin,late-warrior/flask-admin,wangjun/flask-admin,ondoheer/flask-admin,ibushong/test-repo,jmagnusson/flask-admin,CoolCloud/flask-admin,closeio/flask-admin,ArtemSerga/flask-admin,jamesbeebop/flask-admin,janusnic/flask-admin,marrybird/flask-admin,jamesbeebop/flask-admin,LennartP/flask-admin,phantomxc/flask-admin,Kha/flask-admin,radioprotector/flask-admin,flabe81/flask-admin,betterlife/flask-admin,sfermigier/flask-admin,jamesbeebop/flask-admin,closeio/flask-admin,Kha/flask-admin,Junnplus/flask-admin,Junnplus/flask-admin,ibushong/test-repo,dxmo/flask-admin,NickWoodhams/flask-admin,NickWoodhams/flask-admin,quokkaproject/flask-admin,sfermigier/flask-admin,likaiguo/flask-admin,HermasT/flask-admin,litnimax/flask-admin,jmagnusson/flask-admin,dxmo/flask-admin,betterlife/flask-admin,chase-seibert/flask-admin,janusnic/flask-admin
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ return Markup('<i class="icon-ok"></i>' if value else '') + def list_formatter(values): + """ + Return string with comma separated values + + :param values: + Value to check + """ + return u', '.join(values) + + DEFAULT_FORMATTERS = { type(None): empty_formatter, - bool: bool_formatter + bool: bool_formatter, + list: list_formatter, }
Add extra type formatter for `list` type
## Code Before: from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ return Markup('<i class="icon-ok"></i>' if value else '') DEFAULT_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter } ## Instruction: Add extra type formatter for `list` type ## Code After: from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ return Markup('<i class="icon-ok"></i>' if value else '') def list_formatter(values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(values) DEFAULT_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ return Markup('<i class="icon-ok"></i>' if value else '') + def list_formatter(values): + """ + Return string with comma separated values + + :param values: + Value to check + """ + return u', '.join(values) + + DEFAULT_FORMATTERS = { type(None): empty_formatter, - bool: bool_formatter + bool: bool_formatter, ? + + list: list_formatter, }
1e393fb2bea443e98a591e781fb0827b33524fa0
mezzanine_editor/models.py
mezzanine_editor/models.py
from django.db import models from django.db.models.signals import post_syncdb from django.dispatch import receiver from django.contrib.auth.models import Group from mezzanine.conf import settings from mezzanine.blog.models import BlogPost @receiver(post_syncdb, sender=BlogPost) def create_default_editor_group(sender, **kwargs): editor_name = getattr(settings, "MEZZANINE_EDITOR_GROUPNAME", "Editor") editor, created = Group.objects.get_or_create(name=editor_name)
from django.db import models from django.db.models.signals import post_syncdb from django.dispatch import receiver from django.contrib.auth.models import Group from mezzanine.conf import settings from mezzanine.blog.models import BlogPost @receiver(post_syncdb, sender=BlogPost) def create_default_editor_group(sender, **kwargs): editor_mode = getattr(settings, "MEZZANINE_EDITOR_ENABLED", True) if editor_mode: editor_name = getattr(settings, "MEZZANINE_EDITOR_GROUPNAME", "Editor") editor, created = Group.objects.get_or_create(name=editor_name)
Check for editor_mode before creating editor user.
Check for editor_mode before creating editor user.
Python
bsd-2-clause
renyi/mezzanine-editor
from django.db import models from django.db.models.signals import post_syncdb from django.dispatch import receiver from django.contrib.auth.models import Group from mezzanine.conf import settings from mezzanine.blog.models import BlogPost @receiver(post_syncdb, sender=BlogPost) def create_default_editor_group(sender, **kwargs): - editor_name = getattr(settings, "MEZZANINE_EDITOR_GROUPNAME", "Editor") + editor_mode = getattr(settings, "MEZZANINE_EDITOR_ENABLED", True) - editor, created = Group.objects.get_or_create(name=editor_name) + if editor_mode: + editor_name = getattr(settings, "MEZZANINE_EDITOR_GROUPNAME", "Editor") + editor, created = Group.objects.get_or_create(name=editor_name) +
Check for editor_mode before creating editor user.
## Code Before: from django.db import models from django.db.models.signals import post_syncdb from django.dispatch import receiver from django.contrib.auth.models import Group from mezzanine.conf import settings from mezzanine.blog.models import BlogPost @receiver(post_syncdb, sender=BlogPost) def create_default_editor_group(sender, **kwargs): editor_name = getattr(settings, "MEZZANINE_EDITOR_GROUPNAME", "Editor") editor, created = Group.objects.get_or_create(name=editor_name) ## Instruction: Check for editor_mode before creating editor user. ## Code After: from django.db import models from django.db.models.signals import post_syncdb from django.dispatch import receiver from django.contrib.auth.models import Group from mezzanine.conf import settings from mezzanine.blog.models import BlogPost @receiver(post_syncdb, sender=BlogPost) def create_default_editor_group(sender, **kwargs): editor_mode = getattr(settings, "MEZZANINE_EDITOR_ENABLED", True) if editor_mode: editor_name = getattr(settings, "MEZZANINE_EDITOR_GROUPNAME", "Editor") editor, created = Group.objects.get_or_create(name=editor_name)
from django.db import models from django.db.models.signals import post_syncdb from django.dispatch import receiver from django.contrib.auth.models import Group from mezzanine.conf import settings from mezzanine.blog.models import BlogPost @receiver(post_syncdb, sender=BlogPost) def create_default_editor_group(sender, **kwargs): + editor_mode = getattr(settings, "MEZZANINE_EDITOR_ENABLED", True) + + if editor_mode: - editor_name = getattr(settings, "MEZZANINE_EDITOR_GROUPNAME", "Editor") + editor_name = getattr(settings, "MEZZANINE_EDITOR_GROUPNAME", "Editor") ? ++++ - editor, created = Group.objects.get_or_create(name=editor_name) + editor, created = Group.objects.get_or_create(name=editor_name) ? ++++
e93789084c03b2a566835006d6d5adaee3d4bbe6
silk/globals.py
silk/globals.py
__all__ = [] try: from silk.webdoc import css, html, node __all__.extend(('css', 'html', 'node')) except ImportError: pass try: from silk.webdb import ( AuthenticationError, BoolColumn, Column, DB, DataColumn, DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn, RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect ) __all__.extend(( 'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn', 'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError', 'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn', 'Table', 'UnknownDriver', 'connect' )) except ImportError: pass try: from silk.webreq import ( B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList, PathRouter, Query, Redirect, Response, TextView, URI ) __all__.extend(( 'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header', 'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response', 'TextView', 'URI' )) except ImportError: pass
__all__ = [] try: from silk.webdoc import css, html, node __all__ += ['css', 'html', 'node'] except ImportError: pass try: from silk.webdb import ( AuthenticationError, BoolColumn, Column, DB, DataColumn, DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn, RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect ) __all__ += [ 'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn', 'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError', 'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn', 'Table', 'UnknownDriver', 'connect' ] except ImportError: pass try: from silk.webreq import ( B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList, PathRouter, Query, Redirect, Response, TextView, URI ) __all__ += [ 'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header', 'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response', 'TextView', 'URI' ] except ImportError: pass
Use += to modify __all__, to appease flake8
Use += to modify __all__, to appease flake8
Python
bsd-3-clause
orbnauticus/silk
__all__ = [] try: from silk.webdoc import css, html, node - __all__.extend(('css', 'html', 'node')) + __all__ += ['css', 'html', 'node'] except ImportError: pass try: from silk.webdb import ( AuthenticationError, BoolColumn, Column, DB, DataColumn, DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn, RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect ) - __all__.extend(( + __all__ += [ 'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn', 'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError', 'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn', 'Table', 'UnknownDriver', 'connect' - )) + ] except ImportError: pass try: from silk.webreq import ( B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList, PathRouter, Query, Redirect, Response, TextView, URI ) - __all__.extend(( + __all__ += [ 'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header', 'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response', 'TextView', 'URI' - )) + ] except ImportError: pass
Use += to modify __all__, to appease flake8
## Code Before: __all__ = [] try: from silk.webdoc import css, html, node __all__.extend(('css', 'html', 'node')) except ImportError: pass try: from silk.webdb import ( AuthenticationError, BoolColumn, Column, DB, DataColumn, DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn, RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect ) __all__.extend(( 'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn', 'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError', 'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn', 'Table', 'UnknownDriver', 'connect' )) except ImportError: pass try: from silk.webreq import ( B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList, PathRouter, Query, Redirect, Response, TextView, URI ) __all__.extend(( 'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header', 'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response', 'TextView', 'URI' )) except ImportError: pass ## Instruction: Use += to modify __all__, to appease flake8 ## Code After: __all__ = [] try: from silk.webdoc import css, html, node __all__ += ['css', 'html', 'node'] except ImportError: pass try: from silk.webdb import ( AuthenticationError, BoolColumn, Column, DB, DataColumn, DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn, RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect ) __all__ += [ 'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn', 'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError', 'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn', 'Table', 'UnknownDriver', 'connect' ] except ImportError: pass try: from silk.webreq import ( B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList, PathRouter, Query, Redirect, Response, TextView, URI ) __all__ += [ 'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header', 'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response', 'TextView', 'URI' ] except ImportError: pass
__all__ = [] try: from silk.webdoc import css, html, node - __all__.extend(('css', 'html', 'node')) ? ^^^^^^^^^ ^^ + __all__ += ['css', 'html', 'node'] ? ^^^^^ ^ except ImportError: pass try: from silk.webdb import ( AuthenticationError, BoolColumn, Column, DB, DataColumn, DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn, RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect ) - __all__.extend(( + __all__ += [ 'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn', 'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError', 'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn', 'Table', 'UnknownDriver', 'connect' - )) + ] except ImportError: pass try: from silk.webreq import ( B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList, PathRouter, Query, Redirect, Response, TextView, URI ) - __all__.extend(( + __all__ += [ 'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header', 'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response', 'TextView', 'URI' - )) + ] except ImportError: pass
763e8b3d8cab43fb314a2dd6b5ebb60c2d482a52
deploy_latest_build.py
deploy_latest_build.py
from __future__ import print_function from list_builds import list_builds from get_build import ensure_build_file from deploy_build import deploy_build def main(): build = list_builds('every')[-1] build_file = ensure_build_file(build) deploy_build(build_file) print('Deployed build:', build) if __name__ == '__main__': main()
from __future__ import print_function from list_builds import list_every_build from get_build import ensure_build_file from deploy_build import deploy_build def main(): args = parse_argsets([chromium_src_arg], parser) build = list_every_build(args.chromium_src)[-1] build_file = ensure_build_file(build) deploy_build(build_file) print('Deployed build:', build) if __name__ == '__main__': main()
Fix deploy CLI arg parsing
Fix deploy CLI arg parsing
Python
apache-2.0
alancutter/web-animations-perf-bot
from __future__ import print_function - from list_builds import list_builds + from list_builds import list_every_build from get_build import ensure_build_file from deploy_build import deploy_build def main(): - build = list_builds('every')[-1] + args = parse_argsets([chromium_src_arg], parser) + build = list_every_build(args.chromium_src)[-1] build_file = ensure_build_file(build) deploy_build(build_file) print('Deployed build:', build) if __name__ == '__main__': main()
Fix deploy CLI arg parsing
## Code Before: from __future__ import print_function from list_builds import list_builds from get_build import ensure_build_file from deploy_build import deploy_build def main(): build = list_builds('every')[-1] build_file = ensure_build_file(build) deploy_build(build_file) print('Deployed build:', build) if __name__ == '__main__': main() ## Instruction: Fix deploy CLI arg parsing ## Code After: from __future__ import print_function from list_builds import list_every_build from get_build import ensure_build_file from deploy_build import deploy_build def main(): args = parse_argsets([chromium_src_arg], parser) build = list_every_build(args.chromium_src)[-1] build_file = ensure_build_file(build) deploy_build(build_file) print('Deployed build:', build) if __name__ == '__main__': main()
from __future__ import print_function - from list_builds import list_builds ? - + from list_builds import list_every_build ? ++++++ from get_build import ensure_build_file from deploy_build import deploy_build def main(): - build = list_builds('every')[-1] + args = parse_argsets([chromium_src_arg], parser) + build = list_every_build(args.chromium_src)[-1] build_file = ensure_build_file(build) deploy_build(build_file) print('Deployed build:', build) if __name__ == '__main__': main()
812f1fec796e4c7d86731d5e3e91293fb1b0296b
scripts/europeana-meta.py
scripts/europeana-meta.py
from __future__ import print_function import sys, os from re import sub import zipfile, json # from pyspark import SparkContext # from pyspark.sql import SQLContext # from pyspark.sql import Row # from pyspark.sql.types import StringType def getSeries(fname): with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] series = fname if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) series = m['identifier'][0] return m if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: europeana.py <input> <output>", file=sys.stderr) exit(-1) # sc = SparkContext(appName="Europeana Import") # sqlContext = SQLContext(sc) x = [os.path.join(d[0], f) for d in os.walk(sys.argv[1]) for f in d[2] if f.endswith('zip')] for f in x: print(json.dumps(getSeries(f))) # sc.parallelize(x, 200).flatMap(getSeries).toDF().write.save(sys.argv[2]) # sc.stop()
from __future__ import print_function import sys, os from re import sub import zipfile, json # from pyspark import SparkContext # from pyspark.sql import SQLContext # from pyspark.sql import Row # from pyspark.sql.types import StringType def getSeries(fname): with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] series = 'europeana/' + sub('^.*newspapers-by-country/', '', sub('[\x80-\xff]', '', fname).replace('.zip', '')) if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) return {'series': series, 'title': m['title'][0], 'lang': m['language']} if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: europeana.py <input> <output>", file=sys.stderr) exit(-1) # sc = SparkContext(appName="Europeana Import") # sqlContext = SQLContext(sc) x = [os.path.join(d[0], f) for d in os.walk(sys.argv[1]) for f in d[2] if f.endswith('zip')] for f in x: print(json.dumps(getSeries(f))) # sc.parallelize(x, 200).flatMap(getSeries).toDF().write.save(sys.argv[2]) # sc.stop()
Use file path as Europeana series name.
Use file path as Europeana series name.
Python
apache-2.0
ViralTexts/vt-passim,ViralTexts/vt-passim,ViralTexts/vt-passim
from __future__ import print_function import sys, os from re import sub import zipfile, json # from pyspark import SparkContext # from pyspark.sql import SQLContext # from pyspark.sql import Row # from pyspark.sql.types import StringType def getSeries(fname): with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] - series = fname + series = 'europeana/' + sub('^.*newspapers-by-country/', '', + sub('[\x80-\xff]', '', fname).replace('.zip', '')) if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) + return {'series': series, 'title': m['title'][0], 'lang': m['language']} - series = m['identifier'][0] - return m if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: europeana.py <input> <output>", file=sys.stderr) exit(-1) # sc = SparkContext(appName="Europeana Import") # sqlContext = SQLContext(sc) x = [os.path.join(d[0], f) for d in os.walk(sys.argv[1]) for f in d[2] if f.endswith('zip')] for f in x: print(json.dumps(getSeries(f))) # sc.parallelize(x, 200).flatMap(getSeries).toDF().write.save(sys.argv[2]) # sc.stop()
Use file path as Europeana series name.
## Code Before: from __future__ import print_function import sys, os from re import sub import zipfile, json # from pyspark import SparkContext # from pyspark.sql import SQLContext # from pyspark.sql import Row # from pyspark.sql.types import StringType def getSeries(fname): with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] series = fname if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) series = m['identifier'][0] return m if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: europeana.py <input> <output>", file=sys.stderr) exit(-1) # sc = SparkContext(appName="Europeana Import") # sqlContext = SQLContext(sc) x = [os.path.join(d[0], f) for d in os.walk(sys.argv[1]) for f in d[2] if f.endswith('zip')] for f in x: print(json.dumps(getSeries(f))) # sc.parallelize(x, 200).flatMap(getSeries).toDF().write.save(sys.argv[2]) # sc.stop() ## Instruction: Use file path as Europeana series name. ## Code After: from __future__ import print_function import sys, os from re import sub import zipfile, json # from pyspark import SparkContext # from pyspark.sql import SQLContext # from pyspark.sql import Row # from pyspark.sql.types import StringType def getSeries(fname): with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] series = 'europeana/' + sub('^.*newspapers-by-country/', '', sub('[\x80-\xff]', '', fname).replace('.zip', '')) if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) return {'series': series, 'title': m['title'][0], 'lang': m['language']} if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: europeana.py <input> <output>", file=sys.stderr) exit(-1) # sc = SparkContext(appName="Europeana Import") # sqlContext = SQLContext(sc) x = [os.path.join(d[0], f) for d in os.walk(sys.argv[1]) for f in d[2] if f.endswith('zip')] for f in x: print(json.dumps(getSeries(f))) # sc.parallelize(x, 200).flatMap(getSeries).toDF().write.save(sys.argv[2]) # sc.stop()
from __future__ import print_function import sys, os from re import sub import zipfile, json # from pyspark import SparkContext # from pyspark.sql import SQLContext # from pyspark.sql import Row # from pyspark.sql.types import StringType def getSeries(fname): with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] - series = fname + series = 'europeana/' + sub('^.*newspapers-by-country/', '', + sub('[\x80-\xff]', '', fname).replace('.zip', '')) if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) + return {'series': series, 'title': m['title'][0], 'lang': m['language']} - series = m['identifier'][0] - return m if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: europeana.py <input> <output>", file=sys.stderr) exit(-1) # sc = SparkContext(appName="Europeana Import") # sqlContext = SQLContext(sc) x = [os.path.join(d[0], f) for d in os.walk(sys.argv[1]) for f in d[2] if f.endswith('zip')] for f in x: print(json.dumps(getSeries(f))) # sc.parallelize(x, 200).flatMap(getSeries).toDF().write.save(sys.argv[2]) # sc.stop()
62d7924f6f5097845a21408e975cae1dfff01c1c
android/app/src/main/assets/python/enamlnative/widgets/analog_clock.py
android/app/src/main/assets/python/enamlnative/widgets/analog_clock.py
''' Copyright (c) 2017, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file COPYING.txt, distributed with this software. Created on May 20, 2017 @author: jrm ''' from atom.api import ( Typed, ForwardTyped, Unicode, observe ) from enaml.core.declarative import d_ from .text_view import TextView, ProxyTextView class ProxyAnalogClock(ProxyTextView): """ The abstract definition of a proxy AnalogClock object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: AnalogClock) class AnalogClock(TextView): """ A simple control for displaying an AnalogClock """ #: A reference to the proxy object. proxy = Typed(ProxyAnalogClock)
''' Copyright (c) 2017, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file COPYING.txt, distributed with this software. Created on May 20, 2017 @author: jrm ''' from atom.api import ( Typed, ForwardTyped, Unicode, observe ) from enaml.core.declarative import d_ from .view import View, ProxyView class ProxyAnalogClock(ProxyView): """ The abstract definition of a proxy AnalogClock object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: AnalogClock) class AnalogClock(View): """ A simple control for displaying an AnalogClock """ #: A reference to the proxy object. proxy = Typed(ProxyAnalogClock)
Use correct parent class for clock
Use correct parent class for clock
Python
mit
codelv/enaml-native,codelv/enaml-native,codelv/enaml-native,codelv/enaml-native
''' Copyright (c) 2017, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file COPYING.txt, distributed with this software. Created on May 20, 2017 @author: jrm ''' from atom.api import ( Typed, ForwardTyped, Unicode, observe ) from enaml.core.declarative import d_ - from .text_view import TextView, ProxyTextView + from .view import View, ProxyView - class ProxyAnalogClock(ProxyTextView): + class ProxyAnalogClock(ProxyView): """ The abstract definition of a proxy AnalogClock object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: AnalogClock) - class AnalogClock(TextView): + class AnalogClock(View): """ A simple control for displaying an AnalogClock """ #: A reference to the proxy object. proxy = Typed(ProxyAnalogClock)
Use correct parent class for clock
## Code Before: ''' Copyright (c) 2017, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file COPYING.txt, distributed with this software. Created on May 20, 2017 @author: jrm ''' from atom.api import ( Typed, ForwardTyped, Unicode, observe ) from enaml.core.declarative import d_ from .text_view import TextView, ProxyTextView class ProxyAnalogClock(ProxyTextView): """ The abstract definition of a proxy AnalogClock object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: AnalogClock) class AnalogClock(TextView): """ A simple control for displaying an AnalogClock """ #: A reference to the proxy object. proxy = Typed(ProxyAnalogClock) ## Instruction: Use correct parent class for clock ## Code After: ''' Copyright (c) 2017, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file COPYING.txt, distributed with this software. Created on May 20, 2017 @author: jrm ''' from atom.api import ( Typed, ForwardTyped, Unicode, observe ) from enaml.core.declarative import d_ from .view import View, ProxyView class ProxyAnalogClock(ProxyView): """ The abstract definition of a proxy AnalogClock object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: AnalogClock) class AnalogClock(View): """ A simple control for displaying an AnalogClock """ #: A reference to the proxy object. proxy = Typed(ProxyAnalogClock)
''' Copyright (c) 2017, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file COPYING.txt, distributed with this software. Created on May 20, 2017 @author: jrm ''' from atom.api import ( Typed, ForwardTyped, Unicode, observe ) from enaml.core.declarative import d_ - from .text_view import TextView, ProxyTextView ? ----- ---- ---- + from .view import View, ProxyView - class ProxyAnalogClock(ProxyTextView): ? ---- + class ProxyAnalogClock(ProxyView): """ The abstract definition of a proxy AnalogClock object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: AnalogClock) - class AnalogClock(TextView): ? ---- + class AnalogClock(View): """ A simple control for displaying an AnalogClock """ #: A reference to the proxy object. proxy = Typed(ProxyAnalogClock)
dcd36fab023ac2530cbfa17449e3ce8f61ad6bdc
ssl-cert-parse.py
ssl-cert-parse.py
import datetime import ssl import OpenSSL def GetCert(SiteName, Port): return ssl.get_server_certificate((SiteName, Port)) def ParseCert(CertRaw): Cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, CertRaw) print(str(Cert.get_subject())[18:-2]) print(datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], '%Y%m%d%H%M%SZ')) print(datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], '%Y%m%d%H%M%SZ')) print(str(Cert.get_issuer())[18:-2]) CertRaw = GetCert('some.domain.tld', 443) print(CertRaw) ParseCert(CertRaw)
import datetime import ssl import OpenSSL def GetCert(SiteName, Port): return ssl.get_server_certificate((SiteName, Port)) def ParseCert(CertRaw): Cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, CertRaw) CertSubject = str(Cert.get_subject())[18:-2] CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], '%Y%m%d%H%M%SZ') CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], '%Y%m%d%H%M%SZ') CertIssuer = str(Cert.get_issuer())[18:-2] return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate, 'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer} CertRaw = GetCert('some.domain.tld', 443) print(CertRaw) Out = ParseCert(CertRaw) print(Out) print(Out['CertSubject']) print(Out['CertStartDate'])
Fix ParseCert() function, add variables, add a return statement
Fix ParseCert() function, add variables, add a return statement
Python
apache-2.0
ivuk/ssl-cert-parse
import datetime import ssl import OpenSSL def GetCert(SiteName, Port): return ssl.get_server_certificate((SiteName, Port)) def ParseCert(CertRaw): Cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, CertRaw) + - print(str(Cert.get_subject())[18:-2]) + CertSubject = str(Cert.get_subject())[18:-2] - print(datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], + CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], - '%Y%m%d%H%M%SZ')) + '%Y%m%d%H%M%SZ') - print(datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], + CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], - '%Y%m%d%H%M%SZ')) + '%Y%m%d%H%M%SZ') - print(str(Cert.get_issuer())[18:-2]) + CertIssuer = str(Cert.get_issuer())[18:-2] + + return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate, + 'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer} CertRaw = GetCert('some.domain.tld', 443) + print(CertRaw) - ParseCert(CertRaw) + Out = ParseCert(CertRaw) + print(Out) + print(Out['CertSubject']) + print(Out['CertStartDate']) +
Fix ParseCert() function, add variables, add a return statement
## Code Before: import datetime import ssl import OpenSSL def GetCert(SiteName, Port): return ssl.get_server_certificate((SiteName, Port)) def ParseCert(CertRaw): Cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, CertRaw) print(str(Cert.get_subject())[18:-2]) print(datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], '%Y%m%d%H%M%SZ')) print(datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], '%Y%m%d%H%M%SZ')) print(str(Cert.get_issuer())[18:-2]) CertRaw = GetCert('some.domain.tld', 443) print(CertRaw) ParseCert(CertRaw) ## Instruction: Fix ParseCert() function, add variables, add a return statement ## Code After: import datetime import ssl import OpenSSL def GetCert(SiteName, Port): return ssl.get_server_certificate((SiteName, Port)) def ParseCert(CertRaw): Cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, CertRaw) CertSubject = str(Cert.get_subject())[18:-2] CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], '%Y%m%d%H%M%SZ') CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], '%Y%m%d%H%M%SZ') CertIssuer = str(Cert.get_issuer())[18:-2] return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate, 'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer} CertRaw = GetCert('some.domain.tld', 443) print(CertRaw) Out = ParseCert(CertRaw) print(Out) print(Out['CertSubject']) print(Out['CertStartDate'])
import datetime import ssl import OpenSSL def GetCert(SiteName, Port): return ssl.get_server_certificate((SiteName, Port)) def ParseCert(CertRaw): Cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, CertRaw) + - print(str(Cert.get_subject())[18:-2]) ? ^ -- ^ - + CertSubject = str(Cert.get_subject())[18:-2] ? ^^ ^^^^^^^^^^ - print(datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], ? ^ -- ^ + CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], ? ^^ ^^^^^^^^^^^^ - '%Y%m%d%H%M%SZ')) + '%Y%m%d%H%M%SZ') - print(datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], ? ^ ^ ^ + CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], ? ^^ ^^ +++ ^^^^ - '%Y%m%d%H%M%SZ')) + '%Y%m%d%H%M%SZ') - print(str(Cert.get_issuer())[18:-2]) ? ^ -- ^ - + CertIssuer = str(Cert.get_issuer())[18:-2] ? ^^ ^^^^^^^^^ + + return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate, + 'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer} CertRaw = GetCert('some.domain.tld', 443) + print(CertRaw) + - ParseCert(CertRaw) + Out = ParseCert(CertRaw) ? ++++++ + print(Out) + print(Out['CertSubject']) + print(Out['CertStartDate'])
c7efd5976f511200162610612fcd5b6f9b013a54
dciclient/v1/utils.py
dciclient/v1/utils.py
import click import json import six def flatten(d, prefix=''): ret = [] for k, v in d.items(): p = k if not prefix else prefix + '.' + k if isinstance(v, dict): ret += flatten(v, prefix=p) else: ret.append("%s=%s" % (p, v)) return ret def print_json(result_json): formatted_result = json.dumps(result_json, indent=4) click.echo(formatted_result) def sanitize_kwargs(**kwargs): kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v) try: kwargs['data'] = json.loads(kwargs['data']) except KeyError: pass return kwargs
import click import json import six def flatten(d, prefix=''): ret = [] for k, v in d.items(): p = k if not prefix else prefix + '.' + k if isinstance(v, dict): ret += flatten(v, prefix=p) else: ret.append("%s=%s" % (p, v)) return ret def print_json(result_json): formatted_result = json.dumps(result_json, indent=4) click.echo(formatted_result) def sanitize_kwargs(**kwargs): kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v) try: kwargs['data'] = json.loads(kwargs['data']) except KeyError: pass except TypeError: pass return kwargs
Fix TypeError exception when parsing json
Fix TypeError exception when parsing json This change fixes the TypeError exception that is raised when it should not while parsing json File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer Change-Id: I1b9670adcc505084fecb54a45ce11029dc8a4d93
Python
apache-2.0
redhat-cip/python-dciclient,redhat-cip/python-dciclient
import click import json import six def flatten(d, prefix=''): ret = [] for k, v in d.items(): p = k if not prefix else prefix + '.' + k if isinstance(v, dict): ret += flatten(v, prefix=p) else: ret.append("%s=%s" % (p, v)) return ret def print_json(result_json): formatted_result = json.dumps(result_json, indent=4) click.echo(formatted_result) def sanitize_kwargs(**kwargs): kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v) try: kwargs['data'] = json.loads(kwargs['data']) except KeyError: pass + except TypeError: + pass return kwargs
Fix TypeError exception when parsing json
## Code Before: import click import json import six def flatten(d, prefix=''): ret = [] for k, v in d.items(): p = k if not prefix else prefix + '.' + k if isinstance(v, dict): ret += flatten(v, prefix=p) else: ret.append("%s=%s" % (p, v)) return ret def print_json(result_json): formatted_result = json.dumps(result_json, indent=4) click.echo(formatted_result) def sanitize_kwargs(**kwargs): kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v) try: kwargs['data'] = json.loads(kwargs['data']) except KeyError: pass return kwargs ## Instruction: Fix TypeError exception when parsing json ## Code After: import click import json import six def flatten(d, prefix=''): ret = [] for k, v in d.items(): p = k if not prefix else prefix + '.' + k if isinstance(v, dict): ret += flatten(v, prefix=p) else: ret.append("%s=%s" % (p, v)) return ret def print_json(result_json): formatted_result = json.dumps(result_json, indent=4) click.echo(formatted_result) def sanitize_kwargs(**kwargs): kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v) try: kwargs['data'] = json.loads(kwargs['data']) except KeyError: pass except TypeError: pass return kwargs
import click import json import six def flatten(d, prefix=''): ret = [] for k, v in d.items(): p = k if not prefix else prefix + '.' + k if isinstance(v, dict): ret += flatten(v, prefix=p) else: ret.append("%s=%s" % (p, v)) return ret def print_json(result_json): formatted_result = json.dumps(result_json, indent=4) click.echo(formatted_result) def sanitize_kwargs(**kwargs): kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v) try: kwargs['data'] = json.loads(kwargs['data']) except KeyError: pass + except TypeError: + pass return kwargs
7e5d8eb0d6eabb427d7e9bd02bac3ee7b90d228d
src/config.py
src/config.py
import urllib import urllib.request proxies = [ False, False ]
import urllib import urllib.request from pprint import pprint proxies = [ '', '' ] _tested_proxies = False def test_proxies(): global _tested_proxies if _tested_proxies: return _tested_proxies = {} def _testproxy(proxyid): if proxyid=='': return True if _tested_proxies.get(proxyid) is not None: return _tested_proxies.get(proxyid) print("Pretesting proxy",proxyid) proxy = urllib.request.ProxyHandler( {'http': proxyid , 'https': proxyid } ) opener = urllib.request.build_opener(proxy) #urllib.request.install_opener(opener) try: opened = opener.open('http://example.com') if not opened: _tested_proxies[proxyid] = False return False assert(opened.read().find(b"Example Domain")>-1) except urllib.error.URLError as e: try: opened = opener.open('http://google.com') if not opened: _tested_proxies[proxyid] = False return False except urllib.error.URLError as e: print("Proxy error",proxyid,e) _tested_proxies[proxyid] = False return False _tested_proxies[proxyid] = True return True proxies[:] = [tup for tup in proxies if _testproxy(tup)] _tested_proxies = True
Test proxies before using them.
Test proxies before using them.
Python
mit
koivunen/whoisabusetool
import urllib import urllib.request + from pprint import pprint + proxies = [ + '', + '' + ] - proxies = [ - False, - False - ] + + _tested_proxies = False + def test_proxies(): + global _tested_proxies + + if _tested_proxies: + return + + _tested_proxies = {} + + def _testproxy(proxyid): + if proxyid=='': + return True + + if _tested_proxies.get(proxyid) is not None: + return _tested_proxies.get(proxyid) + + print("Pretesting proxy",proxyid) + proxy = urllib.request.ProxyHandler( {'http': proxyid , 'https': proxyid } ) + opener = urllib.request.build_opener(proxy) + #urllib.request.install_opener(opener) + try: + opened = opener.open('http://example.com') + if not opened: + _tested_proxies[proxyid] = False + return False + assert(opened.read().find(b"Example Domain")>-1) + + except urllib.error.URLError as e: + try: + opened = opener.open('http://google.com') + if not opened: + _tested_proxies[proxyid] = False + return False + + except urllib.error.URLError as e: + print("Proxy error",proxyid,e) + _tested_proxies[proxyid] = False + return False + + _tested_proxies[proxyid] = True + return True + + proxies[:] = [tup for tup in proxies if _testproxy(tup)] + + _tested_proxies = True +
Test proxies before using them.
## Code Before: import urllib import urllib.request proxies = [ False, False ] ## Instruction: Test proxies before using them. ## Code After: import urllib import urllib.request from pprint import pprint proxies = [ '', '' ] _tested_proxies = False def test_proxies(): global _tested_proxies if _tested_proxies: return _tested_proxies = {} def _testproxy(proxyid): if proxyid=='': return True if _tested_proxies.get(proxyid) is not None: return _tested_proxies.get(proxyid) print("Pretesting proxy",proxyid) proxy = urllib.request.ProxyHandler( {'http': proxyid , 'https': proxyid } ) opener = urllib.request.build_opener(proxy) #urllib.request.install_opener(opener) try: opened = opener.open('http://example.com') if not opened: _tested_proxies[proxyid] = False return False assert(opened.read().find(b"Example Domain")>-1) except urllib.error.URLError as e: try: opened = opener.open('http://google.com') if not opened: _tested_proxies[proxyid] = False return False except urllib.error.URLError as e: print("Proxy error",proxyid,e) _tested_proxies[proxyid] = False return False _tested_proxies[proxyid] = True return True proxies[:] = [tup for tup in proxies if _testproxy(tup)] _tested_proxies = True
import urllib import urllib.request + from pprint import pprint + proxies = [ + '', + '' + ] - proxies = [ - False, - False - ] + + _tested_proxies = False + def test_proxies(): + global _tested_proxies + + if _tested_proxies: + return + + _tested_proxies = {} + + def _testproxy(proxyid): + if proxyid=='': + return True + + if _tested_proxies.get(proxyid) is not None: + return _tested_proxies.get(proxyid) + + print("Pretesting proxy",proxyid) + proxy = urllib.request.ProxyHandler( {'http': proxyid , 'https': proxyid } ) + opener = urllib.request.build_opener(proxy) + #urllib.request.install_opener(opener) + try: + opened = opener.open('http://example.com') + if not opened: + _tested_proxies[proxyid] = False + return False + assert(opened.read().find(b"Example Domain")>-1) + + except urllib.error.URLError as e: + try: + opened = opener.open('http://google.com') + if not opened: + _tested_proxies[proxyid] = False + return False + + except urllib.error.URLError as e: + print("Proxy error",proxyid,e) + _tested_proxies[proxyid] = False + return False + + _tested_proxies[proxyid] = True + return True + + proxies[:] = [tup for tup in proxies if _testproxy(tup)] + + _tested_proxies = True +
54cb7685550c1c5238bb2f519306e4b5db5fc9f0
webapp-django/challenges/views.py
webapp-django/challenges/views.py
from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Challenge # from .forms import DocumentForm def download(req): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response def index(request): challenges = Challenge.objects.all() return render(request, 'challenges/index.html', {'challenges': challenges}) ''' path=settings.MEDIA_ROOT file_list =os.listdir(path) return render(request,'challenges/index.html', {'files': file_list}) ''' def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'challenges/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'challenges/upload.html') def upload2(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/jeopardy') else: form = DocumentForm() return render(request, 'challenges/upload2.html', { 'form': form }) def textBased(request): challenges = Challenge.objects.all() return render(request, 'challenges/textBased.html', {'challenges': challenges})
from django.http import HttpResponse from django.shortcuts import render from .models import Challenge def download(req): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response def index(request): challenges = Challenge.objects.all() return render(request, 'challenges/index.html', {'challenges': challenges}) ''' path=settings.MEDIA_ROOT file_list =os.listdir(path) return render(request,'challenges/index.html', {'files': file_list}) ''' ''' def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'challenges/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'challenges/upload.html') def upload2(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/jeopardy') else: form = DocumentForm() return render(request, 'challenges/upload2.html', { 'form': form }) ''' def textBased(request): challenges = Challenge.objects.all() return render(request, 'challenges/textBased.html', {'challenges': challenges})
Comment out some useless code in challenges
Comment out some useless code in challenges
Python
mit
super1337/Super1337-CTF,super1337/Super1337-CTF,super1337/Super1337-CTF
- from django.core.files.storage import FileSystemStorage - from django.shortcuts import render, redirect from django.http import HttpResponse + from django.shortcuts import render + from .models import Challenge - - # from .forms import DocumentForm def download(req): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response def index(request): challenges = Challenge.objects.all() return render(request, 'challenges/index.html', {'challenges': challenges}) ''' path=settings.MEDIA_ROOT file_list =os.listdir(path) return render(request,'challenges/index.html', {'files': file_list}) ''' + ''' def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'challenges/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'challenges/upload.html') def upload2(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/jeopardy') else: form = DocumentForm() return render(request, 'challenges/upload2.html', { 'form': form }) + ''' + def textBased(request): challenges = Challenge.objects.all() return render(request, 'challenges/textBased.html', {'challenges': challenges})
Comment out some useless code in challenges
## Code Before: from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Challenge # from .forms import DocumentForm def download(req): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response def index(request): challenges = Challenge.objects.all() return render(request, 'challenges/index.html', {'challenges': challenges}) ''' path=settings.MEDIA_ROOT file_list =os.listdir(path) return render(request,'challenges/index.html', {'files': file_list}) ''' def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'challenges/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'challenges/upload.html') def upload2(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/jeopardy') else: form = DocumentForm() return render(request, 'challenges/upload2.html', { 'form': form }) def textBased(request): challenges = Challenge.objects.all() return render(request, 'challenges/textBased.html', {'challenges': challenges}) ## Instruction: Comment out some useless code in challenges ## Code After: from django.http import HttpResponse from django.shortcuts import render from .models import Challenge def download(req): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response def index(request): challenges = Challenge.objects.all() return render(request, 'challenges/index.html', {'challenges': challenges}) ''' path=settings.MEDIA_ROOT file_list =os.listdir(path) return render(request,'challenges/index.html', {'files': file_list}) ''' ''' def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'challenges/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'challenges/upload.html') def upload2(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/jeopardy') else: form = DocumentForm() return render(request, 'challenges/upload2.html', { 'form': form }) ''' def textBased(request): challenges = Challenge.objects.all() return render(request, 'challenges/textBased.html', {'challenges': challenges})
- from django.core.files.storage import FileSystemStorage - from django.shortcuts import render, redirect from django.http import HttpResponse + from django.shortcuts import render + from .models import Challenge - - # from .forms import DocumentForm def download(req): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response def index(request): challenges = Challenge.objects.all() return render(request, 'challenges/index.html', {'challenges': challenges}) ''' path=settings.MEDIA_ROOT file_list =os.listdir(path) return render(request,'challenges/index.html', {'files': file_list}) ''' + ''' def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'challenges/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'challenges/upload.html') def upload2(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/jeopardy') else: form = DocumentForm() return render(request, 'challenges/upload2.html', { 'form': form }) + ''' + def textBased(request): challenges = Challenge.objects.all() return render(request, 'challenges/textBased.html', {'challenges': challenges})
7447de560c064d251ec58ca35814f476005335ae
budgetsupervisor/transactions/forms.py
budgetsupervisor/transactions/forms.py
from django import forms from django.conf import settings from django.utils.dateparse import parse_datetime import os from .saltedge import SaltEdge from .models import Transaction, Category from decimal import Decimal class ImportTransactionsForm(forms.Form): def import_transactions(self): app = SaltEdge(os.environ["APP_ID"], os.environ["SECRET"], "transactions/private.pem") url = "https://www.saltedge.com/api/v5/transactions?connection_id={}&account_id={}".format(os.environ["CONNECTION_ID"], os.environ["ACCOUNT_ID"]) response = app.get(url) data = response.json() for imported_transaction in data['data']: imported_id = int(imported_transaction['id']) escaped_category = imported_transaction["category"].replace("_", " ") category = Category.objects.filter(name__iexact=escaped_category) category = category[0] if category else Category.objects.get(name="Uncategorized") t, created = Transaction.objects.update_or_create( external_id=imported_id, defaults={ "date": imported_transaction['made_on'], "amount": imported_transaction['amount'], "payee": "", "category": category, "description": imported_transaction['description'], } )
from django import forms from django.conf import settings from django.utils.dateparse import parse_datetime import os from .saltedge import SaltEdge from .models import Transaction, Category from decimal import Decimal class ImportTransactionsForm(forms.Form): def import_transactions(self): app = SaltEdge(os.environ["APP_ID"], os.environ["SECRET"], "transactions/private.pem") url = "https://www.saltedge.com/api/v5/transactions?connection_id={}&account_id={}".format(os.environ["CONNECTION_ID"], os.environ["ACCOUNT_ID"]) response = app.get(url) data = response.json() uncategorized = Category.objects.get(name="Uncategorized") for imported_transaction in data['data']: imported_id = int(imported_transaction['id']) escaped_category = imported_transaction["category"].replace("_", " ") category = Category.objects.filter(name__iexact=escaped_category) category = category[0] if category else uncategorized t, created = Transaction.objects.update_or_create( external_id=imported_id, defaults={ "date": imported_transaction['made_on'], "amount": imported_transaction['amount'], "payee": "", "category": category, "description": imported_transaction['description'], } )
Reduce number of database queries
Reduce number of database queries
Python
mit
ltowarek/budget-supervisor
from django import forms from django.conf import settings from django.utils.dateparse import parse_datetime import os from .saltedge import SaltEdge from .models import Transaction, Category from decimal import Decimal class ImportTransactionsForm(forms.Form): def import_transactions(self): app = SaltEdge(os.environ["APP_ID"], os.environ["SECRET"], "transactions/private.pem") url = "https://www.saltedge.com/api/v5/transactions?connection_id={}&account_id={}".format(os.environ["CONNECTION_ID"], os.environ["ACCOUNT_ID"]) response = app.get(url) data = response.json() + uncategorized = Category.objects.get(name="Uncategorized") + for imported_transaction in data['data']: imported_id = int(imported_transaction['id']) escaped_category = imported_transaction["category"].replace("_", " ") category = Category.objects.filter(name__iexact=escaped_category) - category = category[0] if category else Category.objects.get(name="Uncategorized") + category = category[0] if category else uncategorized t, created = Transaction.objects.update_or_create( external_id=imported_id, defaults={ "date": imported_transaction['made_on'], "amount": imported_transaction['amount'], "payee": "", "category": category, "description": imported_transaction['description'], } )
Reduce number of database queries
## Code Before: from django import forms from django.conf import settings from django.utils.dateparse import parse_datetime import os from .saltedge import SaltEdge from .models import Transaction, Category from decimal import Decimal class ImportTransactionsForm(forms.Form): def import_transactions(self): app = SaltEdge(os.environ["APP_ID"], os.environ["SECRET"], "transactions/private.pem") url = "https://www.saltedge.com/api/v5/transactions?connection_id={}&account_id={}".format(os.environ["CONNECTION_ID"], os.environ["ACCOUNT_ID"]) response = app.get(url) data = response.json() for imported_transaction in data['data']: imported_id = int(imported_transaction['id']) escaped_category = imported_transaction["category"].replace("_", " ") category = Category.objects.filter(name__iexact=escaped_category) category = category[0] if category else Category.objects.get(name="Uncategorized") t, created = Transaction.objects.update_or_create( external_id=imported_id, defaults={ "date": imported_transaction['made_on'], "amount": imported_transaction['amount'], "payee": "", "category": category, "description": imported_transaction['description'], } ) ## Instruction: Reduce number of database queries ## Code After: from django import forms from django.conf import settings from django.utils.dateparse import parse_datetime import os from .saltedge import SaltEdge from .models import Transaction, Category from decimal import Decimal class ImportTransactionsForm(forms.Form): def import_transactions(self): app = SaltEdge(os.environ["APP_ID"], os.environ["SECRET"], "transactions/private.pem") url = "https://www.saltedge.com/api/v5/transactions?connection_id={}&account_id={}".format(os.environ["CONNECTION_ID"], os.environ["ACCOUNT_ID"]) response = app.get(url) data = response.json() uncategorized = Category.objects.get(name="Uncategorized") for imported_transaction in data['data']: imported_id = int(imported_transaction['id']) escaped_category = imported_transaction["category"].replace("_", " ") category = Category.objects.filter(name__iexact=escaped_category) category = category[0] if category else uncategorized t, created = Transaction.objects.update_or_create( external_id=imported_id, defaults={ "date": imported_transaction['made_on'], "amount": imported_transaction['amount'], "payee": "", "category": category, "description": imported_transaction['description'], } )
from django import forms from django.conf import settings from django.utils.dateparse import parse_datetime import os from .saltedge import SaltEdge from .models import Transaction, Category from decimal import Decimal class ImportTransactionsForm(forms.Form): def import_transactions(self): app = SaltEdge(os.environ["APP_ID"], os.environ["SECRET"], "transactions/private.pem") url = "https://www.saltedge.com/api/v5/transactions?connection_id={}&account_id={}".format(os.environ["CONNECTION_ID"], os.environ["ACCOUNT_ID"]) response = app.get(url) data = response.json() + uncategorized = Category.objects.get(name="Uncategorized") + for imported_transaction in data['data']: imported_id = int(imported_transaction['id']) escaped_category = imported_transaction["category"].replace("_", " ") category = Category.objects.filter(name__iexact=escaped_category) - category = category[0] if category else Category.objects.get(name="Uncategorized") ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- + category = category[0] if category else uncategorized ? ^ t, created = Transaction.objects.update_or_create( external_id=imported_id, defaults={ "date": imported_transaction['made_on'], "amount": imported_transaction['amount'], "payee": "", "category": category, "description": imported_transaction['description'], } )
b0f4158beebdb1edac9305e63a9fb77946d3a59f
run_tests.py
run_tests.py
import os import sys import contextlib import subprocess @contextlib.contextmanager def binding(binding): """Prepare an environment for a specific binding""" sys.stderr.write("""\ # # Running tests with %s.. # """ % binding) os.environ["QT_PREFERRED_BINDING"] = binding try: yield except: pass os.environ.pop("QT_PREFERRED_BINDING") if __name__ == "__main__": argv = [ "nosetests", "--verbose", "--with-process-isolation", "--exe", ] # argv.extend(sys.argv[1:]) # Running each test independently via subprocess # enables tests to filter out from tests.py before # being split into individual processes via the # --with-process-isolation feature of nose. with binding("PyQt4"): subprocess.call(argv) with binding("PySide"): subprocess.call(argv) with binding("PyQt5"): subprocess.call(argv) with binding("PySide2"): subprocess.call(argv)
import os import sys import contextlib import subprocess @contextlib.contextmanager def binding(binding): """Prepare an environment for a specific binding""" sys.stderr.write("""\ # # Running tests with %s.. # """ % binding) os.environ["QT_PREFERRED_BINDING"] = binding try: yield except: pass os.environ.pop("QT_PREFERRED_BINDING") if __name__ == "__main__": argv = [ "nosetests", "--verbose", "--with-process-isolation", "--exe", ] errors = 0 # Running each test independently via subprocess # enables tests to filter out from tests.py before # being split into individual processes via the # --with-process-isolation feature of nose. with binding("PyQt4"): errors += subprocess.call(argv) with binding("PySide"): errors += subprocess.call(argv) with binding("PyQt5"): errors += subprocess.call(argv) with binding("PySide2"): errors += subprocess.call(argv) if errors: raise Exception("%i binding(s) failed." % errors)
Throw exception when primary tests fail
Throw exception when primary tests fail
Python
mit
mottosso/Qt.py,fredrikaverpil/Qt.py,mottosso/Qt.py,fredrikaverpil/Qt.py
import os import sys import contextlib import subprocess @contextlib.contextmanager def binding(binding): """Prepare an environment for a specific binding""" sys.stderr.write("""\ # # Running tests with %s.. # """ % binding) os.environ["QT_PREFERRED_BINDING"] = binding try: yield except: pass os.environ.pop("QT_PREFERRED_BINDING") if __name__ == "__main__": argv = [ "nosetests", "--verbose", "--with-process-isolation", "--exe", ] - # argv.extend(sys.argv[1:]) + errors = 0 # Running each test independently via subprocess # enables tests to filter out from tests.py before # being split into individual processes via the # --with-process-isolation feature of nose. with binding("PyQt4"): - subprocess.call(argv) + errors += subprocess.call(argv) with binding("PySide"): - subprocess.call(argv) + errors += subprocess.call(argv) with binding("PyQt5"): - subprocess.call(argv) + errors += subprocess.call(argv) with binding("PySide2"): - subprocess.call(argv) + errors += subprocess.call(argv) + if errors: + raise Exception("%i binding(s) failed." % errors) +
Throw exception when primary tests fail
## Code Before: import os import sys import contextlib import subprocess @contextlib.contextmanager def binding(binding): """Prepare an environment for a specific binding""" sys.stderr.write("""\ # # Running tests with %s.. # """ % binding) os.environ["QT_PREFERRED_BINDING"] = binding try: yield except: pass os.environ.pop("QT_PREFERRED_BINDING") if __name__ == "__main__": argv = [ "nosetests", "--verbose", "--with-process-isolation", "--exe", ] # argv.extend(sys.argv[1:]) # Running each test independently via subprocess # enables tests to filter out from tests.py before # being split into individual processes via the # --with-process-isolation feature of nose. with binding("PyQt4"): subprocess.call(argv) with binding("PySide"): subprocess.call(argv) with binding("PyQt5"): subprocess.call(argv) with binding("PySide2"): subprocess.call(argv) ## Instruction: Throw exception when primary tests fail ## Code After: import os import sys import contextlib import subprocess @contextlib.contextmanager def binding(binding): """Prepare an environment for a specific binding""" sys.stderr.write("""\ # # Running tests with %s.. # """ % binding) os.environ["QT_PREFERRED_BINDING"] = binding try: yield except: pass os.environ.pop("QT_PREFERRED_BINDING") if __name__ == "__main__": argv = [ "nosetests", "--verbose", "--with-process-isolation", "--exe", ] errors = 0 # Running each test independently via subprocess # enables tests to filter out from tests.py before # being split into individual processes via the # --with-process-isolation feature of nose. with binding("PyQt4"): errors += subprocess.call(argv) with binding("PySide"): errors += subprocess.call(argv) with binding("PyQt5"): errors += subprocess.call(argv) with binding("PySide2"): errors += subprocess.call(argv) if errors: raise Exception("%i binding(s) failed." % errors)
import os import sys import contextlib import subprocess @contextlib.contextmanager def binding(binding): """Prepare an environment for a specific binding""" sys.stderr.write("""\ # # Running tests with %s.. # """ % binding) os.environ["QT_PREFERRED_BINDING"] = binding try: yield except: pass os.environ.pop("QT_PREFERRED_BINDING") if __name__ == "__main__": argv = [ "nosetests", "--verbose", "--with-process-isolation", "--exe", ] - # argv.extend(sys.argv[1:]) + errors = 0 # Running each test independently via subprocess # enables tests to filter out from tests.py before # being split into individual processes via the # --with-process-isolation feature of nose. with binding("PyQt4"): - subprocess.call(argv) + errors += subprocess.call(argv) ? ++++++++++ with binding("PySide"): - subprocess.call(argv) + errors += subprocess.call(argv) ? ++++++++++ with binding("PyQt5"): - subprocess.call(argv) + errors += subprocess.call(argv) ? ++++++++++ with binding("PySide2"): - subprocess.call(argv) + errors += subprocess.call(argv) ? ++++++++++ + + if errors: + raise Exception("%i binding(s) failed." % errors)
3d2f9087e62006f8a5f19476ae23324a4cfa7793
regex.py
regex.py
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
Update of work over prior couple weeks.
Update of work over prior couple weeks.
Python
mit
jnicolls/meTypeset-Test,jnicolls/Joseph
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' - fd = + fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) + pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
Update of work over prior couple weeks.
## Code Before: import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close() ## Instruction: Update of work over prior couple weeks. ## Code After: import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' - fd = + fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) + pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
638dda46a63f1c98f674febe170df55fe36cea5e
tests/test_timestepping.py
tests/test_timestepping.py
import numpy as np from sympy import Eq import pytest from devito.interfaces import TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12)
import numpy as np from sympy import Eq import pytest from devito.interfaces import Backward, Forward, TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) @pytest.fixture def b(shape=(11, 11)): """Backward time data object, unrolled (save=True)""" return TimeData(name='b', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) def test_backward(b, nt=5): b.data[nt, :] = 6. eqn = Eq(b.backward, b - 1.) StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) for i in range(nt + 1): assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12)
Add explicit test for reverse timestepping
TimeData: Add explicit test for reverse timestepping
Python
mit
opesci/devito,opesci/devito
import numpy as np from sympy import Eq import pytest - from devito.interfaces import TimeData + from devito.interfaces import Backward, Forward, TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) + @pytest.fixture + def b(shape=(11, 11)): + """Backward time data object, unrolled (save=True)""" + return TimeData(name='b', shape=shape, time_order=1, + time_dim=6, save=True) + + def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) + + def test_backward(b, nt=5): + b.data[nt, :] = 6. + eqn = Eq(b.backward, b - 1.) + StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) + for i in range(nt + 1): + assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12) +
Add explicit test for reverse timestepping
## Code Before: import numpy as np from sympy import Eq import pytest from devito.interfaces import TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) ## Instruction: Add explicit test for reverse timestepping ## Code After: import numpy as np from sympy import Eq import pytest from devito.interfaces import Backward, Forward, TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) @pytest.fixture def b(shape=(11, 11)): """Backward time data object, unrolled (save=True)""" return TimeData(name='b', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) def test_backward(b, nt=5): b.data[nt, :] = 6. eqn = Eq(b.backward, b - 1.) StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) for i in range(nt + 1): assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12)
import numpy as np from sympy import Eq import pytest - from devito.interfaces import TimeData + from devito.interfaces import Backward, Forward, TimeData ? +++++++++++++++++++ from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) + @pytest.fixture + def b(shape=(11, 11)): + """Backward time data object, unrolled (save=True)""" + return TimeData(name='b', shape=shape, time_order=1, + time_dim=6, save=True) + + def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) + + + def test_backward(b, nt=5): + b.data[nt, :] = 6. + eqn = Eq(b.backward, b - 1.) + StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) + for i in range(nt + 1): + assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12)
359c563e200431e7da13766cf106f14f36b29bd4
shuup_workbench/urls.py
shuup_workbench/urls.py
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")), url(r'^api/', include('shuup.api.urls')), url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static urlpatterns = [ url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")), url(r'^api/', include('shuup.api.urls')), url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Hide Django admin URLs from the workbench
Hide Django admin URLs from the workbench Django admin shouldn't be used by default with Shuup. Enabling this would require some attention towards Django filer in multi shop situations.
Python
agpl-3.0
shoopio/shoop,shoopio/shoop,shoopio/shoop
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static - from django.contrib import admin urlpatterns = [ - url(r'^admin/', include(admin.site.urls)), url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")), url(r'^api/', include('shuup.api.urls')), url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Hide Django admin URLs from the workbench
## Code Before: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")), url(r'^api/', include('shuup.api.urls')), url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ## Instruction: Hide Django admin URLs from the workbench ## Code After: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static urlpatterns = [ url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")), url(r'^api/', include('shuup.api.urls')), url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static - from django.contrib import admin urlpatterns = [ - url(r'^admin/', include(admin.site.urls)), url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")), url(r'^api/', include('shuup.api.urls')), url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
f4e07b93ab81fd0a0dc59ec77fca596a2fcca738
froide/helper/form_utils.py
froide/helper/form_utils.py
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: e.get_json_data() for f, e in self.errors.items()}, 'nonFieldErrors': [e.get_json_data() for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) def get_data(error): if isinstance(error, (dict, str)): return error return error.get_json_data() class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: get_data(e) for f, e in self.errors.items()}, 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
Fix serialization of form errors
Fix serialization of form errors
Python
mit
fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) + def get_data(error): + if isinstance(error, (dict, str)): + return error + return error.get_json_data() + + class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, - 'errors': {f: e.get_json_data() for f, e in self.errors.items()}, + 'errors': {f: get_data(e) for f, e in self.errors.items()}, - 'nonFieldErrors': [e.get_json_data() for e in self.non_field_errors()] + 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
Fix serialization of form errors
## Code Before: import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: e.get_json_data() for f, e in self.errors.items()}, 'nonFieldErrors': [e.get_json_data() for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None } ## Instruction: Fix serialization of form errors ## Code After: import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) def get_data(error): if isinstance(error, (dict, str)): return error return error.get_json_data() class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: get_data(e) for f, e in self.errors.items()}, 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) + def get_data(error): + if isinstance(error, (dict, str)): + return error + return error.get_json_data() + + class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, - 'errors': {f: e.get_json_data() for f, e in self.errors.items()}, ? -- ----- + 'errors': {f: get_data(e) for f, e in self.errors.items()}, ? + - 'nonFieldErrors': [e.get_json_data() for e in self.non_field_errors()] ? -- ----- + 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] ? + } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
cdfbd5bab75de151e2e9f3f36eb18741ddb862c1
sifter.py
sifter.py
import os import requests import re import json NUM_REGEX = r'\#([0-9]+)' API_KEY = os.environ['SIFTER'] def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers=headers) data = json.loads(r.content) for issue in data['issues']: if str(issue['number']) == number: return format_ticket(issue) def format_ticket(issue): url = "https://unisubs.sifterapp.com/issue/%s" % issue['number'] return "%s - %s - %s" % (issue['number'], issue['subject'], url) def parse(text): issues = re.findall(NUM_REGEX, text) return map(find_ticket, issues)
import os import requests import re import json NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b' API_KEY = os.environ['SIFTER'] def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers=headers) data = json.loads(r.content) for issue in data['issues']: if str(issue['number']) == number: return format_ticket(issue) def format_ticket(issue): url = "https://unisubs.sifterapp.com/issue/%s" % issue['number'] return "%s - %s - %s" % (issue['number'], issue['subject'], url) def parse(text): issues = re.findall(NUM_REGEX, text) return map(find_ticket, issues)
Change the Sifter issue number matching
Change the Sifter issue number matching Now it's only 3-5 digits, optionally with the hash, and only as a standalone word.
Python
bsd-2-clause
honza/nigel
import os import requests import re import json - NUM_REGEX = r'\#([0-9]+)' + NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b' API_KEY = os.environ['SIFTER'] def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers=headers) data = json.loads(r.content) for issue in data['issues']: if str(issue['number']) == number: return format_ticket(issue) def format_ticket(issue): url = "https://unisubs.sifterapp.com/issue/%s" % issue['number'] return "%s - %s - %s" % (issue['number'], issue['subject'], url) def parse(text): issues = re.findall(NUM_REGEX, text) return map(find_ticket, issues)
Change the Sifter issue number matching
## Code Before: import os import requests import re import json NUM_REGEX = r'\#([0-9]+)' API_KEY = os.environ['SIFTER'] def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers=headers) data = json.loads(r.content) for issue in data['issues']: if str(issue['number']) == number: return format_ticket(issue) def format_ticket(issue): url = "https://unisubs.sifterapp.com/issue/%s" % issue['number'] return "%s - %s - %s" % (issue['number'], issue['subject'], url) def parse(text): issues = re.findall(NUM_REGEX, text) return map(find_ticket, issues) ## Instruction: Change the Sifter issue number matching ## Code After: import os import requests import re import json NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b' API_KEY = os.environ['SIFTER'] def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers=headers) data = json.loads(r.content) for issue in data['issues']: if str(issue['number']) == number: return format_ticket(issue) def format_ticket(issue): url = "https://unisubs.sifterapp.com/issue/%s" % issue['number'] return "%s - %s - %s" % (issue['number'], issue['subject'], url) def parse(text): issues = re.findall(NUM_REGEX, text) return map(find_ticket, issues)
import os import requests import re import json - NUM_REGEX = r'\#([0-9]+)' + NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b' API_KEY = os.environ['SIFTER'] def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers=headers) data = json.loads(r.content) for issue in data['issues']: if str(issue['number']) == number: return format_ticket(issue) def format_ticket(issue): url = "https://unisubs.sifterapp.com/issue/%s" % issue['number'] return "%s - %s - %s" % (issue['number'], issue['subject'], url) def parse(text): issues = re.findall(NUM_REGEX, text) return map(find_ticket, issues)
38964f0f840a7b60f5ce65ca2857789d92b133b5
django_base64field/tests.py
django_base64field/tests.py
from django.db import models from django.test import TestCase from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): ek = Base64Field() name = models.CharField(max_length=13) class Continent(models.Model): ek = Base64Field() name = models.CharField(max_length=13) planet = models.ForeignKey(Planet, to_field='ek') class TestBase64Field(TestCase): def test_field_is_none_after_creation(self): planet = Planet.objects.create(name='Fucking Earth') self.assertIn(planet.ek, ['', None]) self.assertIsNotNone(planet.pk) def test_field_not_none_after_saved(self): planet = Planet.objects.create(name='Little Planet') base64_key = base64.encode(planet.pk) saved_planet = Planet.objects.get(pk=planet.pk) self.assertEqual(saved_planet.ek, base64_key)
from django.db import models from django.test import TestCase from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): ek = Base64Field() name = models.CharField( default='Fucker', max_length=103 ) class Continent(models.Model): ek = Base64Field() name = models.CharField( default='Suckers!', max_length=13 ) planet = models.ForeignKey(Planet, to_field='ek') class TestBase64Field(TestCase): def test_field_is_none_after_creation(self): planet = Planet.objects.create(name='Fucking Earth') self.assertIn(planet.ek, ['', None]) self.assertIsNotNone(planet.pk) def test_field_not_none_after_saved(self): planet = Planet.objects.create(name='Little Planet') base64_key = base64.encode(planet.pk) saved_planet = Planet.objects.get(pk=planet.pk) self.assertEqual(saved_planet.ek, base64_key)
Make fields on model have defaults value
Make fields on model have defaults value Like who cares for their default value
Python
bsd-3-clause
Alir3z4/django-base64field
from django.db import models from django.test import TestCase from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): ek = Base64Field() - name = models.CharField(max_length=13) + name = models.CharField( + default='Fucker', + max_length=103 + ) class Continent(models.Model): ek = Base64Field() - name = models.CharField(max_length=13) + name = models.CharField( + default='Suckers!', + max_length=13 + ) planet = models.ForeignKey(Planet, to_field='ek') class TestBase64Field(TestCase): def test_field_is_none_after_creation(self): planet = Planet.objects.create(name='Fucking Earth') self.assertIn(planet.ek, ['', None]) self.assertIsNotNone(planet.pk) def test_field_not_none_after_saved(self): planet = Planet.objects.create(name='Little Planet') base64_key = base64.encode(planet.pk) saved_planet = Planet.objects.get(pk=planet.pk) self.assertEqual(saved_planet.ek, base64_key)
Make fields on model have defaults value
## Code Before: from django.db import models from django.test import TestCase from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): ek = Base64Field() name = models.CharField(max_length=13) class Continent(models.Model): ek = Base64Field() name = models.CharField(max_length=13) planet = models.ForeignKey(Planet, to_field='ek') class TestBase64Field(TestCase): def test_field_is_none_after_creation(self): planet = Planet.objects.create(name='Fucking Earth') self.assertIn(planet.ek, ['', None]) self.assertIsNotNone(planet.pk) def test_field_not_none_after_saved(self): planet = Planet.objects.create(name='Little Planet') base64_key = base64.encode(planet.pk) saved_planet = Planet.objects.get(pk=planet.pk) self.assertEqual(saved_planet.ek, base64_key) ## Instruction: Make fields on model have defaults value ## Code After: from django.db import models from django.test import TestCase from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): ek = Base64Field() name = models.CharField( default='Fucker', max_length=103 ) class Continent(models.Model): ek = Base64Field() name = models.CharField( default='Suckers!', max_length=13 ) planet = models.ForeignKey(Planet, to_field='ek') class TestBase64Field(TestCase): def test_field_is_none_after_creation(self): planet = Planet.objects.create(name='Fucking Earth') self.assertIn(planet.ek, ['', None]) self.assertIsNotNone(planet.pk) def test_field_not_none_after_saved(self): planet = Planet.objects.create(name='Little Planet') base64_key = base64.encode(planet.pk) saved_planet = Planet.objects.get(pk=planet.pk) self.assertEqual(saved_planet.ek, base64_key)
from django.db import models from django.test import TestCase from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): ek = Base64Field() - name = models.CharField(max_length=13) ? -------------- + name = models.CharField( + default='Fucker', + max_length=103 + ) class Continent(models.Model): ek = Base64Field() - name = models.CharField(max_length=13) ? -------------- + name = models.CharField( + default='Suckers!', + max_length=13 + ) planet = models.ForeignKey(Planet, to_field='ek') class TestBase64Field(TestCase): def test_field_is_none_after_creation(self): planet = Planet.objects.create(name='Fucking Earth') self.assertIn(planet.ek, ['', None]) self.assertIsNotNone(planet.pk) def test_field_not_none_after_saved(self): planet = Planet.objects.create(name='Little Planet') base64_key = base64.encode(planet.pk) saved_planet = Planet.objects.get(pk=planet.pk) self.assertEqual(saved_planet.ek, base64_key)
63bf9c267ff891f1a2bd1f472a5d77f8df1e0209
tests/iam/test_iam_valid_json.py
tests/iam/test_iam_valid_json.py
"""Test IAM Policy templates are valid JSON.""" import jinja2 from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name items = ['resource1', 'resource2'] if service == 'rds-db': items = { 'resource1': 'user1', 'resource2': 'user2', } rendered = render_policy_template( account_number='', app='coreforrest', env='dev', group='forrest', items=items, pipeline_settings={ 'lambda': { 'vpc_enabled': False, }, }, region='us-east-1', service=service) assert isinstance(rendered, list)
"""Test IAM Policy templates are valid JSON.""" import json import jinja2 import pytest from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name @pytest.mark.parametrize(argnames='template_name', argvalues=iam_templates()) def test_all_iam_templates(template_name): """Verify all IAM templates render as proper JSON.""" *_, service_json = template_name.split('/') service, *_ = service_json.split('.') items = ['resource1', 'resource2'] if service == 'rds-db': items = { 'resource1': 'user1', 'resource2': 'user2', } try: rendered = render_policy_template( account_number='', app='coreforrest', env='dev', group='forrest', items=items, pipeline_settings={ 'lambda': { 'vpc_enabled': False, }, }, region='us-east-1', service=service) except json.decoder.JSONDecodeError: pytest.fail('Bad template: {0}'.format(template_name), pytrace=False) assert isinstance(rendered, list)
Split IAM template tests with paramtrize
test: Split IAM template tests with paramtrize See also: #208
Python
apache-2.0
gogoair/foremast,gogoair/foremast
"""Test IAM Policy templates are valid JSON.""" + import json + import jinja2 + import pytest from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name + @pytest.mark.parametrize(argnames='template_name', argvalues=iam_templates()) + def test_all_iam_templates(template_name): + """Verify all IAM templates render as proper JSON.""" + *_, service_json = template_name.split('/') + service, *_ = service_json.split('.') - items = ['resource1', 'resource2'] + items = ['resource1', 'resource2'] - if service == 'rds-db': + if service == 'rds-db': - items = { + items = { - 'resource1': 'user1', + 'resource1': 'user1', - 'resource2': 'user2', + 'resource2': 'user2', - } + } + try: rendered = render_policy_template( account_number='', app='coreforrest', env='dev', group='forrest', items=items, pipeline_settings={ 'lambda': { 'vpc_enabled': False, }, }, region='us-east-1', service=service) + except json.decoder.JSONDecodeError: + pytest.fail('Bad template: {0}'.format(template_name), pytrace=False) - assert isinstance(rendered, list) + assert isinstance(rendered, list)
Split IAM template tests with paramtrize
## Code Before: """Test IAM Policy templates are valid JSON.""" import jinja2 from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name items = ['resource1', 'resource2'] if service == 'rds-db': items = { 'resource1': 'user1', 'resource2': 'user2', } rendered = render_policy_template( account_number='', app='coreforrest', env='dev', group='forrest', items=items, pipeline_settings={ 'lambda': { 'vpc_enabled': False, }, }, region='us-east-1', service=service) assert isinstance(rendered, list) ## Instruction: Split IAM template tests with paramtrize ## Code After: """Test IAM Policy templates are valid JSON.""" import json import jinja2 import pytest from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name @pytest.mark.parametrize(argnames='template_name', argvalues=iam_templates()) def test_all_iam_templates(template_name): """Verify all IAM templates render as proper JSON.""" *_, service_json = template_name.split('/') service, *_ = service_json.split('.') items = ['resource1', 'resource2'] if service == 'rds-db': items = { 'resource1': 'user1', 'resource2': 'user2', } try: rendered = render_policy_template( account_number='', app='coreforrest', env='dev', group='forrest', items=items, pipeline_settings={ 'lambda': { 'vpc_enabled': False, }, }, region='us-east-1', service=service) except json.decoder.JSONDecodeError: pytest.fail('Bad template: {0}'.format(template_name), pytrace=False) assert isinstance(rendered, list)
"""Test IAM Policy templates are valid JSON.""" + import json + import jinja2 + import pytest from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name + @pytest.mark.parametrize(argnames='template_name', argvalues=iam_templates()) + def test_all_iam_templates(template_name): + """Verify all IAM templates render as proper JSON.""" + *_, service_json = template_name.split('/') + service, *_ = service_json.split('.') - items = ['resource1', 'resource2'] ? ---- + items = ['resource1', 'resource2'] - if service == 'rds-db': ? ---- + if service == 'rds-db': - items = { ? ---- + items = { - 'resource1': 'user1', ? ---- + 'resource1': 'user1', - 'resource2': 'user2', ? ---- + 'resource2': 'user2', - } ? ---- + } + try: rendered = render_policy_template( account_number='', app='coreforrest', env='dev', group='forrest', items=items, pipeline_settings={ 'lambda': { 'vpc_enabled': False, }, }, region='us-east-1', service=service) + except json.decoder.JSONDecodeError: + pytest.fail('Bad template: {0}'.format(template_name), pytrace=False) - assert isinstance(rendered, list) ? ---- + assert isinstance(rendered, list)
48362fa70ab20f66f4f398c68ab252dfd36c6117
crust/fields.py
crust/fields.py
class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value
class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value def dehydrate(self, value): return value
Make provisions for dehydrating a field
Make provisions for dehydrating a field
Python
bsd-2-clause
dstufft/crust
class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value + def dehydrate(self, value): + return value +
Make provisions for dehydrating a field
## Code Before: class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value ## Instruction: Make provisions for dehydrating a field ## Code After: class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value def dehydrate(self, value): return value
class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value + + def dehydrate(self, value): + return value
18bf9dd5e1e054d0c260959a8379f331940e167f
online_status/__init__.py
online_status/__init__.py
VERSION = (0, 1, 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = "%s %s" % (version, VERSION[3]) if VERSION[4] != 0: version = '%s %s' % (version, VERSION[4]) return version
VERSION = (0, 1, 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) return version
Fix 'index out of bound' issue
Fix 'index out of bound' issue
Python
unlicense
hovel/django-online-status,hovel/django-online-status
VERSION = (0, 1, 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) - if VERSION[3:] == ('alpha', 0): - version = '%s pre-alpha' % version - else: - if VERSION[3] != 'final': - version = "%s %s" % (version, VERSION[3]) - if VERSION[4] != 0: - version = '%s %s' % (version, VERSION[4]) return version
Fix 'index out of bound' issue
## Code Before: VERSION = (0, 1, 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = "%s %s" % (version, VERSION[3]) if VERSION[4] != 0: version = '%s %s' % (version, VERSION[4]) return version ## Instruction: Fix 'index out of bound' issue ## Code After: VERSION = (0, 1, 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) return version
VERSION = (0, 1, 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) - if VERSION[3:] == ('alpha', 0): - version = '%s pre-alpha' % version - else: - if VERSION[3] != 'final': - version = "%s %s" % (version, VERSION[3]) - if VERSION[4] != 0: - version = '%s %s' % (version, VERSION[4]) return version
a21d484cc1131b56d793e75fbb6ab1531205dae6
joueur/base_game_object.py
joueur/base_game_object.py
from joueur.delta_mergeable import DeltaMergeable # the base class that every game object within a game inherit from for Python # manipulation that would be redundant via Creer class BaseGameObject(DeltaMergeable): def __init__(self): DeltaMergeable.__init__(self) def __str__(self): return "{} #{}".format(self.game_object_name, self.id) def __repr__(self): return str(self)
from joueur.delta_mergeable import DeltaMergeable # the base class that every game object within a game inherit from for Python # manipulation that would be redundant via Creer class BaseGameObject(DeltaMergeable): def __init__(self): DeltaMergeable.__init__(self) def __str__(self): return "{} #{}".format(self.game_object_name, self.id) def __repr__(self): return str(self) def __hash__(self): # id will always be unique server side anyways, # so it should be safe to hash on return hash(self.id)
Update BaseGameObject to be hashable
Update BaseGameObject to be hashable
Python
mit
JacobFischer/Joueur.py,siggame/Joueur.py,siggame/Joueur.py,JacobFischer/Joueur.py
from joueur.delta_mergeable import DeltaMergeable # the base class that every game object within a game inherit from for Python # manipulation that would be redundant via Creer class BaseGameObject(DeltaMergeable): def __init__(self): DeltaMergeable.__init__(self) def __str__(self): return "{} #{}".format(self.game_object_name, self.id) def __repr__(self): return str(self) + def __hash__(self): + # id will always be unique server side anyways, + # so it should be safe to hash on + return hash(self.id) +
Update BaseGameObject to be hashable
## Code Before: from joueur.delta_mergeable import DeltaMergeable # the base class that every game object within a game inherit from for Python # manipulation that would be redundant via Creer class BaseGameObject(DeltaMergeable): def __init__(self): DeltaMergeable.__init__(self) def __str__(self): return "{} #{}".format(self.game_object_name, self.id) def __repr__(self): return str(self) ## Instruction: Update BaseGameObject to be hashable ## Code After: from joueur.delta_mergeable import DeltaMergeable # the base class that every game object within a game inherit from for Python # manipulation that would be redundant via Creer class BaseGameObject(DeltaMergeable): def __init__(self): DeltaMergeable.__init__(self) def __str__(self): return "{} #{}".format(self.game_object_name, self.id) def __repr__(self): return str(self) def __hash__(self): # id will always be unique server side anyways, # so it should be safe to hash on return hash(self.id)
from joueur.delta_mergeable import DeltaMergeable # the base class that every game object within a game inherit from for Python # manipulation that would be redundant via Creer class BaseGameObject(DeltaMergeable): def __init__(self): DeltaMergeable.__init__(self) def __str__(self): return "{} #{}".format(self.game_object_name, self.id) def __repr__(self): return str(self) + + def __hash__(self): + # id will always be unique server side anyways, + # so it should be safe to hash on + return hash(self.id)
643b47b2b805a045d9344e11e85ae4334ea79056
casia/conf/global_settings.py
casia/conf/global_settings.py
TIME_ZONE = 'UTC' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'casia.conf.urls' WSGI_APPLICATION = 'casia.core.wsgi.application'
TIME_ZONE = 'UTC' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ) ROOT_URLCONF = 'casia.conf.urls' WSGI_APPLICATION = 'casia.core.wsgi.application'
Remove middleware classes which are currently unnecessary
Remove middleware classes which are currently unnecessary
Python
agpl-3.0
mkwm/casia,mkwm/casia
TIME_ZONE = 'UTC' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'casia.conf.urls' WSGI_APPLICATION = 'casia.core.wsgi.application'
Remove middleware classes which are currently unnecessary
## Code Before: TIME_ZONE = 'UTC' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'casia.conf.urls' WSGI_APPLICATION = 'casia.core.wsgi.application' ## Instruction: Remove middleware classes which are currently unnecessary ## Code After: TIME_ZONE = 'UTC' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ) ROOT_URLCONF = 'casia.conf.urls' WSGI_APPLICATION = 'casia.core.wsgi.application'
TIME_ZONE = 'UTC' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'casia.conf.urls' WSGI_APPLICATION = 'casia.core.wsgi.application'
7a68599ca8794d1d1b7d358e6f79791547f7740f
setuptools/tests/test_build.py
setuptools/tests/test_build.py
from setuptools.dist import Distribution from setuptools.command.build import build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', script_args=['build'], packages=[''], package_data={'': ['path/*']}, )) assert isinstance(dist.get_command_obj("build"), build)
from setuptools.dist import Distribution from setuptools.command.build import build from distutils.command.build import build as distutils_build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', script_args=['build'], packages=[''], package_data={'': ['path/*']}, )) build_obj = dist.get_command_obj("build") assert isinstance(build_obj, build) build_obj.sub_commands.append(("custom_build_subcommand", None)) distutils_subcommands = [cmd[0] for cmd in distutils_build.sub_commands] assert "custom_build_subcommand" not in distutils_subcommands
Test that extending setuptools' build sub_commands does not extend distutils
Test that extending setuptools' build sub_commands does not extend distutils
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
from setuptools.dist import Distribution from setuptools.command.build import build + from distutils.command.build import build as distutils_build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', script_args=['build'], packages=[''], package_data={'': ['path/*']}, )) - assert isinstance(dist.get_command_obj("build"), build) + build_obj = dist.get_command_obj("build") + assert isinstance(build_obj, build) + + build_obj.sub_commands.append(("custom_build_subcommand", None)) + + distutils_subcommands = [cmd[0] for cmd in distutils_build.sub_commands] + assert "custom_build_subcommand" not in distutils_subcommands +
Test that extending setuptools' build sub_commands does not extend distutils
## Code Before: from setuptools.dist import Distribution from setuptools.command.build import build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', script_args=['build'], packages=[''], package_data={'': ['path/*']}, )) assert isinstance(dist.get_command_obj("build"), build) ## Instruction: Test that extending setuptools' build sub_commands does not extend distutils ## Code After: from setuptools.dist import Distribution from setuptools.command.build import build from distutils.command.build import build as distutils_build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', script_args=['build'], packages=[''], package_data={'': ['path/*']}, )) build_obj = dist.get_command_obj("build") assert isinstance(build_obj, build) build_obj.sub_commands.append(("custom_build_subcommand", None)) distutils_subcommands = [cmd[0] for cmd in distutils_build.sub_commands] assert "custom_build_subcommand" not in distutils_subcommands
from setuptools.dist import Distribution from setuptools.command.build import build + from distutils.command.build import build as distutils_build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', script_args=['build'], packages=[''], package_data={'': ['path/*']}, )) - assert isinstance(dist.get_command_obj("build"), build) + + build_obj = dist.get_command_obj("build") + assert isinstance(build_obj, build) + + build_obj.sub_commands.append(("custom_build_subcommand", None)) + + distutils_subcommands = [cmd[0] for cmd in distutils_build.sub_commands] + assert "custom_build_subcommand" not in distutils_subcommands
c769b66c546ad3fd9d04c0607506a49e9d3bff4a
fortdepend/preprocessor.py
fortdepend/preprocessor.py
import io import pcpp class FortranPreprocessor(pcpp.Preprocessor): def __init__(self): super().__init__() def parse_to_string_lines(self, text): with io.StringIO() as f: self.parse(text) self.write(f) f.seek(0) result = f.readlines() return result
import io import pcpp class FortranPreprocessor(pcpp.Preprocessor): def __init__(self): super(pcpp.Preprocessor, self).__init__() def parse_to_string_lines(self, text): with io.StringIO() as f: self.parse(text) self.write(f) f.seek(0) result = f.readlines() return result
Fix super() call for py2.7
Fix super() call for py2.7
Python
mit
ZedThree/fort_depend.py,ZedThree/fort_depend.py
import io import pcpp class FortranPreprocessor(pcpp.Preprocessor): def __init__(self): - super().__init__() + super(pcpp.Preprocessor, self).__init__() def parse_to_string_lines(self, text): with io.StringIO() as f: self.parse(text) self.write(f) f.seek(0) result = f.readlines() return result
Fix super() call for py2.7
## Code Before: import io import pcpp class FortranPreprocessor(pcpp.Preprocessor): def __init__(self): super().__init__() def parse_to_string_lines(self, text): with io.StringIO() as f: self.parse(text) self.write(f) f.seek(0) result = f.readlines() return result ## Instruction: Fix super() call for py2.7 ## Code After: import io import pcpp class FortranPreprocessor(pcpp.Preprocessor): def __init__(self): super(pcpp.Preprocessor, self).__init__() def parse_to_string_lines(self, text): with io.StringIO() as f: self.parse(text) self.write(f) f.seek(0) result = f.readlines() return result
import io import pcpp class FortranPreprocessor(pcpp.Preprocessor): def __init__(self): - super().__init__() + super(pcpp.Preprocessor, self).__init__() def parse_to_string_lines(self, text): with io.StringIO() as f: self.parse(text) self.write(f) f.seek(0) result = f.readlines() return result
d7d9fcb260b85a3f785852239acaea6ccda1725a
what_meta/views.py
what_meta/views.py
from django.core import serializers from django.http.response import HttpResponse from what_meta.models import WhatTorrentGroup def search_torrent_groups(request, query): return HttpResponse( serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), content_type='text/plain', )
from django.core import serializers from django.http.response import HttpResponse from what_meta.models import WhatTorrentGroup def search_torrent_groups(request, query): response = HttpResponse( serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), content_type='text/json', ) response['Access-Control-Allow-Origin'] = '*' return response
Support for super simple player.
Support for super simple player.
Python
mit
grandmasterchef/WhatManager2,davols/WhatManager2,MADindustries/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,karamanolev/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,karamanolev/WhatManager2,karamanolev/WhatManager2,karamanolev/WhatManager2,MADindustries/WhatManager2
from django.core import serializers from django.http.response import HttpResponse from what_meta.models import WhatTorrentGroup def search_torrent_groups(request, query): - return HttpResponse( + response = HttpResponse( serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), - content_type='text/plain', + content_type='text/json', ) + response['Access-Control-Allow-Origin'] = '*' + return response
Support for super simple player.
## Code Before: from django.core import serializers from django.http.response import HttpResponse from what_meta.models import WhatTorrentGroup def search_torrent_groups(request, query): return HttpResponse( serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), content_type='text/plain', ) ## Instruction: Support for super simple player. ## Code After: from django.core import serializers from django.http.response import HttpResponse from what_meta.models import WhatTorrentGroup def search_torrent_groups(request, query): response = HttpResponse( serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), content_type='text/json', ) response['Access-Control-Allow-Origin'] = '*' return response
from django.core import serializers from django.http.response import HttpResponse from what_meta.models import WhatTorrentGroup def search_torrent_groups(request, query): - return HttpResponse( ? ^^^ + response = HttpResponse( ? ^^^ ++++ serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), - content_type='text/plain', ? ^^^^ + content_type='text/json', ? ^^^ ) + response['Access-Control-Allow-Origin'] = '*' + return response
b0e614ea7ac59b6b869155b9ac8ea370cb56f83d
cardinal/decorators.py
cardinal/decorators.py
import functools def command(triggers): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
import functools def command(triggers): if isinstance(triggers, basestring): triggers = [triggers] def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
Allow for single trigger in @command decorator
Allow for single trigger in @command decorator
Python
mit
BiohZn/Cardinal,JohnMaguire/Cardinal
import functools def command(triggers): + if isinstance(triggers, basestring): + triggers = [triggers] + def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
Allow for single trigger in @command decorator
## Code Before: import functools def command(triggers): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap ## Instruction: Allow for single trigger in @command decorator ## Code After: import functools def command(triggers): if isinstance(triggers, basestring): triggers = [triggers] def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
import functools def command(triggers): + if isinstance(triggers, basestring): + triggers = [triggers] + def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
630ba21f3b08dcd2685297b057cbee4b6abee6f7
us_ignite/sections/models.py
us_ignite/sections/models.py
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField(upload_to="sponsor") order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField( upload_to="sponsor", help_text='This image is not post processed. ' 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
Add help text describing the image field functionality.
Add help text describing the image field functionality.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) - image = models.ImageField(upload_to="sponsor") + image = models.ImageField( + upload_to="sponsor", help_text='This image is not post processed. ' + 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
Add help text describing the image field functionality.
## Code Before: from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField(upload_to="sponsor") order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name ## Instruction: Add help text describing the image field functionality. ## Code After: from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField( upload_to="sponsor", help_text='This image is not post processed. ' 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) - image = models.ImageField(upload_to="sponsor") ? -------------------- + image = models.ImageField( + upload_to="sponsor", help_text='This image is not post processed. ' + 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
c90dbc5007b5627b264493c2d16af79cff9c2af0
joku/checks.py
joku/checks.py
from discord.ext.commands import CheckFailure def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True
from discord.ext.commands import CheckFailure, check def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True def has_permissions(**perms): def predicate(ctx): if ctx.bot.owner_id == ctx.message.author.id: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure(message="You do not have any of the required permissions: {}".format( ', '.join([perm.upper() for perm in perms]) )) return check(predicate)
Add better custom has_permission check.
Add better custom has_permission check.
Python
mit
MJB47/Jokusoramame,MJB47/Jokusoramame,MJB47/Jokusoramame
- from discord.ext.commands import CheckFailure + from discord.ext.commands import CheckFailure, check def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True + + def has_permissions(**perms): + def predicate(ctx): + if ctx.bot.owner_id == ctx.message.author.id: + return True + msg = ctx.message + ch = msg.channel + permissions = ch.permissions_for(msg.author) + if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): + return True + + # Raise a custom error message + raise CheckFailure(message="You do not have any of the required permissions: {}".format( + ', '.join([perm.upper() for perm in perms]) + )) + + return check(predicate) +
Add better custom has_permission check.
## Code Before: from discord.ext.commands import CheckFailure def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True ## Instruction: Add better custom has_permission check. ## Code After: from discord.ext.commands import CheckFailure, check def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True def has_permissions(**perms): def predicate(ctx): if ctx.bot.owner_id == ctx.message.author.id: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure(message="You do not have any of the required permissions: {}".format( ', '.join([perm.upper() for perm in perms]) )) return check(predicate)
- from discord.ext.commands import CheckFailure + from discord.ext.commands import CheckFailure, check ? +++++++ def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True + + + def has_permissions(**perms): + def predicate(ctx): + if ctx.bot.owner_id == ctx.message.author.id: + return True + msg = ctx.message + ch = msg.channel + permissions = ch.permissions_for(msg.author) + if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): + return True + + # Raise a custom error message + raise CheckFailure(message="You do not have any of the required permissions: {}".format( + ', '.join([perm.upper() for perm in perms]) + )) + + return check(predicate)
4c58426a88ba056841b1d1b44536f2f85de120cc
pythonx/completers/javascript/__init__.py
pythonx/completers/javascript/__init__.py
import json import os.path import re from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True ident = re.compile(r"""(\w+)|(('|").+)""", re.U) trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|('|").*$""" def format_cmd(self): binary = self.get_option('node_binary') or 'node' tern_config = self.find_config_file('.tern-project') cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')] if tern_config: cmd.append(os.path.dirname(tern_config)) return cmd def parse(self, data): try: data = to_unicode(data[0], 'utf-8') return [i for i in json.loads(data) if not self.input_data.endswith(i['word'])] except Exception: return []
import json import os.path import re from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True ident = re.compile(r"""(\w+)|(["'][^"']*)""", re.U) trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|["']\w*$""" def format_cmd(self): binary = self.get_option('node_binary') or 'node' tern_config = self.find_config_file('.tern-project') cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')] if tern_config: cmd.append(os.path.dirname(tern_config)) return cmd def parse(self, data): try: data = to_unicode(data[0], 'utf-8') return [i for i in json.loads(data) if not self.input_data.endswith(i['word'])] except Exception: return []
Fix regex for tern complete_strings plugin
Fix regex for tern complete_strings plugin
Python
mit
maralla/completor.vim,maralla/completor.vim
import json import os.path import re from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True - ident = re.compile(r"""(\w+)|(('|").+)""", re.U) + ident = re.compile(r"""(\w+)|(["'][^"']*)""", re.U) - trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|('|").*$""" + trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|["']\w*$""" def format_cmd(self): binary = self.get_option('node_binary') or 'node' tern_config = self.find_config_file('.tern-project') cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')] if tern_config: cmd.append(os.path.dirname(tern_config)) return cmd def parse(self, data): try: data = to_unicode(data[0], 'utf-8') return [i for i in json.loads(data) if not self.input_data.endswith(i['word'])] except Exception: return []
Fix regex for tern complete_strings plugin
## Code Before: import json import os.path import re from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True ident = re.compile(r"""(\w+)|(('|").+)""", re.U) trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|('|").*$""" def format_cmd(self): binary = self.get_option('node_binary') or 'node' tern_config = self.find_config_file('.tern-project') cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')] if tern_config: cmd.append(os.path.dirname(tern_config)) return cmd def parse(self, data): try: data = to_unicode(data[0], 'utf-8') return [i for i in json.loads(data) if not self.input_data.endswith(i['word'])] except Exception: return [] ## Instruction: Fix regex for tern complete_strings plugin ## Code After: import json import os.path import re from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True ident = re.compile(r"""(\w+)|(["'][^"']*)""", re.U) trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|["']\w*$""" def format_cmd(self): binary = self.get_option('node_binary') or 'node' tern_config = self.find_config_file('.tern-project') cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')] if tern_config: cmd.append(os.path.dirname(tern_config)) return cmd def parse(self, data): try: data = to_unicode(data[0], 'utf-8') return [i for i in json.loads(data) if not self.input_data.endswith(i['word'])] except Exception: return []
import json import os.path import re from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True - ident = re.compile(r"""(\w+)|(('|").+)""", re.U) ? ^ ^ ^^^ + ident = re.compile(r"""(\w+)|(["'][^"']*)""", re.U) ? ^^ ^^^ ^^^ - trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|('|").*$""" ? ^ ^^^^ + trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|["']\w*$""" ? ^^ ^^^ def format_cmd(self): binary = self.get_option('node_binary') or 'node' tern_config = self.find_config_file('.tern-project') cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')] if tern_config: cmd.append(os.path.dirname(tern_config)) return cmd def parse(self, data): try: data = to_unicode(data[0], 'utf-8') return [i for i in json.loads(data) if not self.input_data.endswith(i['word'])] except Exception: return []
4f45e55e5b0e14cf6bf32b42a14cbdf9b3c08258
dbus_notify.py
dbus_notify.py
from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 if is_string(icon): # File path icon_file = icon else: icon_file = "" # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 icon_file = "" if is_string(icon): # File path icon_file = icon elif icon: # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
Make sure we do not try to convert None
Make sure we do not try to convert None
Python
cc0-1.0
hellhovnd/mpd-hiss,ahihi/mpd-hiss
from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 + icon_file = "" if is_string(icon): # File path icon_file = icon + elif icon: - else: - icon_file = "" # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
Make sure we do not try to convert None
## Code Before: from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 if is_string(icon): # File path icon_file = icon else: icon_file = "" # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time) ## Instruction: Make sure we do not try to convert None ## Code After: from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 icon_file = "" if is_string(icon): # File path icon_file = icon elif icon: # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 + icon_file = "" if is_string(icon): # File path icon_file = icon + elif icon: - else: - icon_file = "" # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
1ff53eade7c02a92f5f09c371b766e7b176a90a1
speyer/ingest/gerrit.py
speyer/ingest/gerrit.py
from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event
from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event
Allow connecting to unknown hosts but warn
Allow connecting to unknown hosts but warn
Python
apache-2.0
locke105/streaming-python-testdrive
from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() + client.set_missing_host_key_policy(paramiko.WarningPolicy()) connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event
Allow connecting to unknown hosts but warn
## Code Before: from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event ## Instruction: Allow connecting to unknown hosts but warn ## Code After: from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event
from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() + client.set_missing_host_key_policy(paramiko.WarningPolicy()) connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event
3fb1800548ad421520bf3f2845aad4f51f6f5839
rapidsms_multimodem/tests/__init__.py
rapidsms_multimodem/tests/__init__.py
from test_utils import * # noqa from test_views import * # noqa
from test_outgoing import * # noqa from test_utils import * # noqa from test_views import * # noqa
Add import for older versions of Django
Add import for older versions of Django
Python
bsd-3-clause
caktus/rapidsms-multimodem
+ from test_outgoing import * # noqa from test_utils import * # noqa from test_views import * # noqa
Add import for older versions of Django
## Code Before: from test_utils import * # noqa from test_views import * # noqa ## Instruction: Add import for older versions of Django ## Code After: from test_outgoing import * # noqa from test_utils import * # noqa from test_views import * # noqa
+ from test_outgoing import * # noqa from test_utils import * # noqa from test_views import * # noqa
052de49807dcb9895608e3882b799642b0b08d18
exercises/circular-buffer/circular_buffer.py
exercises/circular-buffer/circular_buffer.py
class BufferFullException(Exception): pass class BufferEmptyException(Exception): pass class CircularBuffer(object): def __init__(self): pass
class BufferFullException(Exception): pass class BufferEmptyException(Exception): pass class CircularBuffer(object): def __init__(self, capacity): pass
Add parameter capacity to circular-buffer example
Add parameter capacity to circular-buffer example Fixes #550
Python
mit
jmluy/xpython,mweb/python,mweb/python,pheanex/xpython,exercism/xpython,jmluy/xpython,exercism/xpython,smalley/python,behrtam/xpython,behrtam/xpython,exercism/python,N-Parsons/exercism-python,exercism/python,N-Parsons/exercism-python,pheanex/xpython,smalley/python
class BufferFullException(Exception): pass class BufferEmptyException(Exception): pass class CircularBuffer(object): - def __init__(self): + def __init__(self, capacity): pass
Add parameter capacity to circular-buffer example
## Code Before: class BufferFullException(Exception): pass class BufferEmptyException(Exception): pass class CircularBuffer(object): def __init__(self): pass ## Instruction: Add parameter capacity to circular-buffer example ## Code After: class BufferFullException(Exception): pass class BufferEmptyException(Exception): pass class CircularBuffer(object): def __init__(self, capacity): pass
class BufferFullException(Exception): pass class BufferEmptyException(Exception): pass class CircularBuffer(object): - def __init__(self): + def __init__(self, capacity): ? ++++++++++ pass