commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
664ad3a2848f7188cd1ea562ddbfd4dc6947915b
tests/test_plugins/bad_server/server.py
tests/test_plugins/bad_server/server.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2015 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server')
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server')
Remove year from file copyright
Remove year from file copyright
Python
apache-2.0
data-exp-lab/girder,Kitware/girder,sutartmelson/girder,sutartmelson/girder,kotfic/girder,RafaelPalomar/girder,Kitware/girder,data-exp-lab/girder,RafaelPalomar/girder,adsorensen/girder,jbeezley/girder,manthey/girder,kotfic/girder,Kitware/girder,RafaelPalomar/girder,adsorensen/girder,Xarthisius/girder,Xarthisius/girder,adsorensen/girder,girder/girder,data-exp-lab/girder,girder/girder,Kitware/girder,manthey/girder,Xarthisius/girder,RafaelPalomar/girder,jbeezley/girder,jbeezley/girder,girder/girder,adsorensen/girder,kotfic/girder,kotfic/girder,sutartmelson/girder,RafaelPalomar/girder,manthey/girder,manthey/girder,adsorensen/girder,Xarthisius/girder,sutartmelson/girder,data-exp-lab/girder,data-exp-lab/girder,jbeezley/girder,girder/girder,kotfic/girder,sutartmelson/girder,Xarthisius/girder
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2015 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server') Remove year from file copyright
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server')
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2015 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server') <commit_msg>Remove year from file copyright<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server')
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2015 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server') Remove year from file copyright#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server')
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2015 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server') <commit_msg>Remove year from file copyright<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### def load(info): raise Exception('Bad server')
7d6e6325e0baf5f4994350a7dd52856db0cb6c8a
src/apps/processing/ala/management/commands/ala_import.py
src/apps/processing/ala/management/commands/ala_import.py
import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from datetime import date, timedelta logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data' def add_arguments(self, parser): parser.add_argument('date', nargs='?', type=parse, default=None) def handle(self, *args, **options): stations = util.get_or_create_stations() day = options['date'] if day is None: day = date.today() - timedelta(2) logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) try: for station in stations: util.load(station, day) util.create_avgs(station, day) except Exception as e: self.stdout.write(self.style.ERROR(e))
import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from dateutil import relativedelta from datetime import date, timedelta logger = logging.getLogger(__name__) def parse_date_range(date_str): if len(date_str) == 4: day_from = parse(date_str).replace(day=1, month=1) day_to = day_from + relativedelta.relativedelta(years=1) elif len(date_str) == 7: day_from = parse(date_str).replace(day=1) day_to = day_from + relativedelta.relativedelta(months=1) else: day_from = parse(date_str) day_to = day_from + timedelta(1) return [day_from, day_to] class Command(BaseCommand): help = 'Import data from ALA stations. Optionally you can pass date, ' \ 'otherwise it will fetch the day before yesterday data.' def add_arguments(self, parser): parser.add_argument('date_range', nargs='?', type=parse_date_range, default=[None, None]) def handle(self, *args, **options): stations = util.get_or_create_stations() day_from, day_to = options['date_range'] if day_from is None: day_from = date.today() - timedelta(2) day_to = day_from + timedelta(1) day = day_from while(day < day_to): logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) for station in stations: util.load(station, day) util.create_avgs(station, day) day += timedelta(1)
Enable ALA import by month or year
Enable ALA import by month or year
Python
bsd-3-clause
gis4dis/poster,gis4dis/poster,gis4dis/poster
import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from datetime import date, timedelta logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data' def add_arguments(self, parser): parser.add_argument('date', nargs='?', type=parse, default=None) def handle(self, *args, **options): stations = util.get_or_create_stations() day = options['date'] if day is None: day = date.today() - timedelta(2) logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) try: for station in stations: util.load(station, day) util.create_avgs(station, day) except Exception as e: self.stdout.write(self.style.ERROR(e)) Enable ALA import by month or year
import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from dateutil import relativedelta from datetime import date, timedelta logger = logging.getLogger(__name__) def parse_date_range(date_str): if len(date_str) == 4: day_from = parse(date_str).replace(day=1, month=1) day_to = day_from + relativedelta.relativedelta(years=1) elif len(date_str) == 7: day_from = parse(date_str).replace(day=1) day_to = day_from + relativedelta.relativedelta(months=1) else: day_from = parse(date_str) day_to = day_from + timedelta(1) return [day_from, day_to] class Command(BaseCommand): help = 'Import data from ALA stations. Optionally you can pass date, ' \ 'otherwise it will fetch the day before yesterday data.' def add_arguments(self, parser): parser.add_argument('date_range', nargs='?', type=parse_date_range, default=[None, None]) def handle(self, *args, **options): stations = util.get_or_create_stations() day_from, day_to = options['date_range'] if day_from is None: day_from = date.today() - timedelta(2) day_to = day_from + timedelta(1) day = day_from while(day < day_to): logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) for station in stations: util.load(station, day) util.create_avgs(station, day) day += timedelta(1)
<commit_before>import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from datetime import date, timedelta logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data' def add_arguments(self, parser): parser.add_argument('date', nargs='?', type=parse, default=None) def handle(self, *args, **options): stations = util.get_or_create_stations() day = options['date'] if day is None: day = date.today() - timedelta(2) logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) try: for station in stations: util.load(station, day) util.create_avgs(station, day) except Exception as e: self.stdout.write(self.style.ERROR(e)) <commit_msg>Enable ALA import by month or year<commit_after>
import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from dateutil import relativedelta from datetime import date, timedelta logger = logging.getLogger(__name__) def parse_date_range(date_str): if len(date_str) == 4: day_from = parse(date_str).replace(day=1, month=1) day_to = day_from + relativedelta.relativedelta(years=1) elif len(date_str) == 7: day_from = parse(date_str).replace(day=1) day_to = day_from + relativedelta.relativedelta(months=1) else: day_from = parse(date_str) day_to = day_from + timedelta(1) return [day_from, day_to] class Command(BaseCommand): help = 'Import data from ALA stations. Optionally you can pass date, ' \ 'otherwise it will fetch the day before yesterday data.' def add_arguments(self, parser): parser.add_argument('date_range', nargs='?', type=parse_date_range, default=[None, None]) def handle(self, *args, **options): stations = util.get_or_create_stations() day_from, day_to = options['date_range'] if day_from is None: day_from = date.today() - timedelta(2) day_to = day_from + timedelta(1) day = day_from while(day < day_to): logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) for station in stations: util.load(station, day) util.create_avgs(station, day) day += timedelta(1)
import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from datetime import date, timedelta logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data' def add_arguments(self, parser): parser.add_argument('date', nargs='?', type=parse, default=None) def handle(self, *args, **options): stations = util.get_or_create_stations() day = options['date'] if day is None: day = date.today() - timedelta(2) logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) try: for station in stations: util.load(station, day) util.create_avgs(station, day) except Exception as e: self.stdout.write(self.style.ERROR(e)) Enable ALA import by month or yearimport logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from dateutil import relativedelta from datetime import date, timedelta logger = logging.getLogger(__name__) def parse_date_range(date_str): if len(date_str) == 4: day_from = parse(date_str).replace(day=1, month=1) day_to = day_from + relativedelta.relativedelta(years=1) elif len(date_str) == 7: day_from = parse(date_str).replace(day=1) day_to = day_from + relativedelta.relativedelta(months=1) else: day_from = parse(date_str) day_to = day_from + timedelta(1) return [day_from, day_to] class Command(BaseCommand): help = 'Import data from ALA stations. Optionally you can pass date, ' \ 'otherwise it will fetch the day before yesterday data.' def add_arguments(self, parser): parser.add_argument('date_range', nargs='?', type=parse_date_range, default=[None, None]) def handle(self, *args, **options): stations = util.get_or_create_stations() day_from, day_to = options['date_range'] if day_from is None: day_from = date.today() - timedelta(2) day_to = day_from + timedelta(1) day = day_from while(day < day_to): logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) for station in stations: util.load(station, day) util.create_avgs(station, day) day += timedelta(1)
<commit_before>import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from datetime import date, timedelta logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data' def add_arguments(self, parser): parser.add_argument('date', nargs='?', type=parse, default=None) def handle(self, *args, **options): stations = util.get_or_create_stations() day = options['date'] if day is None: day = date.today() - timedelta(2) logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) try: for station in stations: util.load(station, day) util.create_avgs(station, day) except Exception as e: self.stdout.write(self.style.ERROR(e)) <commit_msg>Enable ALA import by month or year<commit_after>import logging from django.core.management.base import BaseCommand from apps.processing.ala.util import util from dateutil.parser import parse from dateutil import relativedelta from datetime import date, timedelta logger = logging.getLogger(__name__) def parse_date_range(date_str): if len(date_str) == 4: day_from = parse(date_str).replace(day=1, month=1) day_to = day_from + relativedelta.relativedelta(years=1) elif len(date_str) == 7: day_from = parse(date_str).replace(day=1) day_to = day_from + relativedelta.relativedelta(months=1) else: day_from = parse(date_str) day_to = day_from + timedelta(1) return [day_from, day_to] class Command(BaseCommand): help = 'Import data from ALA stations. Optionally you can pass date, ' \ 'otherwise it will fetch the day before yesterday data.' def add_arguments(self, parser): parser.add_argument('date_range', nargs='?', type=parse_date_range, default=[None, None]) def handle(self, *args, **options): stations = util.get_or_create_stations() day_from, day_to = options['date_range'] if day_from is None: day_from = date.today() - timedelta(2) day_to = day_from + timedelta(1) day = day_from while(day < day_to): logger.info( 'Importing observations of {} ALA stations from {}.'.format( len(stations), day ) ) for station in stations: util.load(station, day) util.create_avgs(station, day) day += timedelta(1)
830a767aa42cfafc22342ff71c23419c86845fe8
src/Classes/SubClass/SubClass.py
src/Classes/SubClass/SubClass.py
class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): try: return dict.__getitem____(self, key) except KeyError: return self.default
class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): if(key in self): return dict.__getitem__(self, key) else: return self.default def get(self, key, *args): if not args: args = (self.default,) return dict.get(self, key, *args) def merge(self, other): for key in other: if key not in self: self[key] = other[key] if __name__ == '__main__': ''' Built-in Dict has a issue. You want solve the problem, when dict doesn't declare variable that you call the variable will throw the "KeyError" ''' print defaultDict print type(defaultDict) d = defaultDict(default = 5) #Init print d print type(d) # Get Type print d.__class__ # Get Class print type(d) is d.__class__ d[1] = 3 print d print d[0] d.merge({1:300, 2:400}) print d print "-----" built_dict = dict() built_dict[1] = 3 print built_dict print built_dict[0]
Add get and merge method. Add Main Function to use class.
[Add] Add get and merge method. Add Main Function to use class.
Python
mit
williamHuang5468/ExpertPython
class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): try: return dict.__getitem____(self, key) except KeyError: return self.default[Add] Add get and merge method. Add Main Function to use class.
class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): if(key in self): return dict.__getitem__(self, key) else: return self.default def get(self, key, *args): if not args: args = (self.default,) return dict.get(self, key, *args) def merge(self, other): for key in other: if key not in self: self[key] = other[key] if __name__ == '__main__': ''' Built-in Dict has a issue. You want solve the problem, when dict doesn't declare variable that you call the variable will throw the "KeyError" ''' print defaultDict print type(defaultDict) d = defaultDict(default = 5) #Init print d print type(d) # Get Type print d.__class__ # Get Class print type(d) is d.__class__ d[1] = 3 print d print d[0] d.merge({1:300, 2:400}) print d print "-----" built_dict = dict() built_dict[1] = 3 print built_dict print built_dict[0]
<commit_before>class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): try: return dict.__getitem____(self, key) except KeyError: return self.default<commit_msg>[Add] Add get and merge method. Add Main Function to use class.<commit_after>
class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): if(key in self): return dict.__getitem__(self, key) else: return self.default def get(self, key, *args): if not args: args = (self.default,) return dict.get(self, key, *args) def merge(self, other): for key in other: if key not in self: self[key] = other[key] if __name__ == '__main__': ''' Built-in Dict has a issue. You want solve the problem, when dict doesn't declare variable that you call the variable will throw the "KeyError" ''' print defaultDict print type(defaultDict) d = defaultDict(default = 5) #Init print d print type(d) # Get Type print d.__class__ # Get Class print type(d) is d.__class__ d[1] = 3 print d print d[0] d.merge({1:300, 2:400}) print d print "-----" built_dict = dict() built_dict[1] = 3 print built_dict print built_dict[0]
class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): try: return dict.__getitem____(self, key) except KeyError: return self.default[Add] Add get and merge method. Add Main Function to use class.class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): if(key in self): return dict.__getitem__(self, key) else: return self.default def get(self, key, *args): if not args: args = (self.default,) return dict.get(self, key, *args) def merge(self, other): for key in other: if key not in self: self[key] = other[key] if __name__ == '__main__': ''' Built-in Dict has a issue. You want solve the problem, when dict doesn't declare variable that you call the variable will throw the "KeyError" ''' print defaultDict print type(defaultDict) d = defaultDict(default = 5) #Init print d print type(d) # Get Type print d.__class__ # Get Class print type(d) is d.__class__ d[1] = 3 print d print d[0] d.merge({1:300, 2:400}) print d print "-----" built_dict = dict() built_dict[1] = 3 print built_dict print built_dict[0]
<commit_before>class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): try: return dict.__getitem____(self, key) except KeyError: return self.default<commit_msg>[Add] Add get and merge method. Add Main Function to use class.<commit_after>class defaultDict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): if(key in self): return dict.__getitem__(self, key) else: return self.default def get(self, key, *args): if not args: args = (self.default,) return dict.get(self, key, *args) def merge(self, other): for key in other: if key not in self: self[key] = other[key] if __name__ == '__main__': ''' Built-in Dict has a issue. You want solve the problem, when dict doesn't declare variable that you call the variable will throw the "KeyError" ''' print defaultDict print type(defaultDict) d = defaultDict(default = 5) #Init print d print type(d) # Get Type print d.__class__ # Get Class print type(d) is d.__class__ d[1] = 3 print d print d[0] d.merge({1:300, 2:400}) print d print "-----" built_dict = dict() built_dict[1] = 3 print built_dict print built_dict[0]
ad2b8bce02c7b7b7ab477fc7fccc1b38fb60e63a
turbustat/statistics/input_base.py
turbustat/statistics/input_base.py
# Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject def input_data(data): ''' Accept a variety of input data forms and return those expected by the various statistics. ''' if isinstance(data, PrimaryHDU): return (data.data, data.header) elif isinstance(data, SpectralCube): return (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): return (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") return data else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.")
# Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject import numpy as np def input_data(data, no_header=False): ''' Accept a variety of input data forms and return those expected by the various statistics. Parameters ---------- data : astropy.io.fits.PrimaryHDU, SpectralCube, spectral_cube.LowerDimensionalObject, np.ndarray or a tuple/list with the data and the header Data to be used with a given statistic or distance metric. no_header must be enabled when passing only an array in. no_header : bool, optional When enabled, returns only the data without the header. Returns ------- ouput_data : tuple or np.ndarray A tuple containing the data and the header. Or an array when no_header is enabled. ''' if isinstance(data, PrimaryHDU): output_data = (data.data, data.header) elif isinstance(data, SpectralCube): output_data = (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): output_data = (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") output_data = data elif isinstance(data, np.ndarray): if not no_header: raise TypeError("no_header must be enabled when giving data" " without a header.") output_data = (data, ) else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") if no_header: return output_data[0] return output_data
Allow for the case when a header isn't needed
Allow for the case when a header isn't needed
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
# Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject def input_data(data): ''' Accept a variety of input data forms and return those expected by the various statistics. ''' if isinstance(data, PrimaryHDU): return (data.data, data.header) elif isinstance(data, SpectralCube): return (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): return (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") return data else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") Allow for the case when a header isn't needed
# Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject import numpy as np def input_data(data, no_header=False): ''' Accept a variety of input data forms and return those expected by the various statistics. Parameters ---------- data : astropy.io.fits.PrimaryHDU, SpectralCube, spectral_cube.LowerDimensionalObject, np.ndarray or a tuple/list with the data and the header Data to be used with a given statistic or distance metric. no_header must be enabled when passing only an array in. no_header : bool, optional When enabled, returns only the data without the header. Returns ------- ouput_data : tuple or np.ndarray A tuple containing the data and the header. Or an array when no_header is enabled. ''' if isinstance(data, PrimaryHDU): output_data = (data.data, data.header) elif isinstance(data, SpectralCube): output_data = (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): output_data = (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") output_data = data elif isinstance(data, np.ndarray): if not no_header: raise TypeError("no_header must be enabled when giving data" " without a header.") output_data = (data, ) else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") if no_header: return output_data[0] return output_data
<commit_before># Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject def input_data(data): ''' Accept a variety of input data forms and return those expected by the various statistics. ''' if isinstance(data, PrimaryHDU): return (data.data, data.header) elif isinstance(data, SpectralCube): return (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): return (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") return data else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") <commit_msg>Allow for the case when a header isn't needed<commit_after>
# Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject import numpy as np def input_data(data, no_header=False): ''' Accept a variety of input data forms and return those expected by the various statistics. Parameters ---------- data : astropy.io.fits.PrimaryHDU, SpectralCube, spectral_cube.LowerDimensionalObject, np.ndarray or a tuple/list with the data and the header Data to be used with a given statistic or distance metric. no_header must be enabled when passing only an array in. no_header : bool, optional When enabled, returns only the data without the header. Returns ------- ouput_data : tuple or np.ndarray A tuple containing the data and the header. Or an array when no_header is enabled. ''' if isinstance(data, PrimaryHDU): output_data = (data.data, data.header) elif isinstance(data, SpectralCube): output_data = (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): output_data = (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") output_data = data elif isinstance(data, np.ndarray): if not no_header: raise TypeError("no_header must be enabled when giving data" " without a header.") output_data = (data, ) else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") if no_header: return output_data[0] return output_data
# Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject def input_data(data): ''' Accept a variety of input data forms and return those expected by the various statistics. ''' if isinstance(data, PrimaryHDU): return (data.data, data.header) elif isinstance(data, SpectralCube): return (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): return (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") return data else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") Allow for the case when a header isn't needed# Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject import numpy as np def input_data(data, no_header=False): ''' Accept a variety of input data forms and return those expected by the various statistics. Parameters ---------- data : astropy.io.fits.PrimaryHDU, SpectralCube, spectral_cube.LowerDimensionalObject, np.ndarray or a tuple/list with the data and the header Data to be used with a given statistic or distance metric. no_header must be enabled when passing only an array in. no_header : bool, optional When enabled, returns only the data without the header. Returns ------- ouput_data : tuple or np.ndarray A tuple containing the data and the header. Or an array when no_header is enabled. ''' if isinstance(data, PrimaryHDU): output_data = (data.data, data.header) elif isinstance(data, SpectralCube): output_data = (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): output_data = (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") output_data = data elif isinstance(data, np.ndarray): if not no_header: raise TypeError("no_header must be enabled when giving data" " without a header.") output_data = (data, ) else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") if no_header: return output_data[0] return output_data
<commit_before># Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject def input_data(data): ''' Accept a variety of input data forms and return those expected by the various statistics. ''' if isinstance(data, PrimaryHDU): return (data.data, data.header) elif isinstance(data, SpectralCube): return (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): return (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") return data else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") <commit_msg>Allow for the case when a header isn't needed<commit_after># Licensed under an MIT open source license - see LICENSE from astropy.io.fits import PrimaryHDU from spectral_cube import SpectralCube from spectral_cube.lower_dimensional_structures import LowerDimensionalObject import numpy as np def input_data(data, no_header=False): ''' Accept a variety of input data forms and return those expected by the various statistics. Parameters ---------- data : astropy.io.fits.PrimaryHDU, SpectralCube, spectral_cube.LowerDimensionalObject, np.ndarray or a tuple/list with the data and the header Data to be used with a given statistic or distance metric. no_header must be enabled when passing only an array in. no_header : bool, optional When enabled, returns only the data without the header. Returns ------- ouput_data : tuple or np.ndarray A tuple containing the data and the header. Or an array when no_header is enabled. ''' if isinstance(data, PrimaryHDU): output_data = (data.data, data.header) elif isinstance(data, SpectralCube): output_data = (data.filled_data[:].value, data.header) elif isinstance(data, LowerDimensionalObject): output_data = (data.value, data.header) elif isinstance(data, tuple) or isinstance(data, list): if len(data) != 2: raise TypeError("Must have two items: data and the header.") output_data = data elif isinstance(data, np.ndarray): if not no_header: raise TypeError("no_header must be enabled when giving data" " without a header.") output_data = (data, ) else: raise TypeError("Input data is not of an accepted form:" " astropy.io.fits.PrimaryHDU, SpectralCube," " spectral_cube.LowerDimensionalObject or a tuple or" " list containing the data and header, in that order.") if no_header: return output_data[0] return output_data
2ef4362be90e2314b69a2ff17ccb5d25ef8905fd
rackspace/database/database_service.py
rackspace/database/database_service.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" if not version: version = "v1" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version)
Set default version for cloud databases.
Set default version for cloud databases.
Python
apache-2.0
rackerlabs/rackspace-sdk-plugin,briancurtin/rackspace-sdk-plugin
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version) Set default version for cloud databases.
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" if not version: version = "v1" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version)
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version) <commit_msg>Set default version for cloud databases.<commit_after>
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" if not version: version = "v1" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version) Set default version for cloud databases.# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" if not version: version = "v1" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version)
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version) <commit_msg>Set default version for cloud databases.<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import service_filter class DatabaseService(service_filter.ServiceFilter): """The database service.""" valid_versions = [service_filter.ValidVersion('v1', path='v1.0')] def __init__(self, version=None): """Create a database service.""" if not version: version = "v1" super(DatabaseService, self).__init__(service_type="rax:database", service_name="cloudDatabases", version=version)
a307bddf490b6ad16739593d4ca51693b9a340fe
regulations/templatetags/in_context.py
regulations/templatetags/in_context.py
from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value return self.nodelist.render(template.Context(new_context)) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:])
from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value new_context = context.new(new_context) return self.nodelist.render(new_context) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:])
Fix custom template tag to work with django 1.8
Fix custom template tag to work with django 1.8
Python
cc0-1.0
18F/regulations-site,jeremiak/regulations-site,18F/regulations-site,18F/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,jeremiak/regulations-site,jeremiak/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,jeremiak/regulations-site
from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value return self.nodelist.render(template.Context(new_context)) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:]) Fix custom template tag to work with django 1.8
from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value new_context = context.new(new_context) return self.nodelist.render(new_context) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:])
<commit_before>from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value return self.nodelist.render(template.Context(new_context)) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:]) <commit_msg>Fix custom template tag to work with django 1.8<commit_after>
from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value new_context = context.new(new_context) return self.nodelist.render(new_context) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:])
from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value return self.nodelist.render(template.Context(new_context)) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:]) Fix custom template tag to work with django 1.8from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value new_context = context.new(new_context) return self.nodelist.render(new_context) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:])
<commit_before>from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value return self.nodelist.render(template.Context(new_context)) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:]) <commit_msg>Fix custom template tag to work with django 1.8<commit_after>from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value new_context = context.new(new_context) return self.nodelist.render(new_context) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:])
4a6f76857a626dd756675a4fe1dd3660cf63d8b7
alg_fibonacci.py
alg_fibonacci.py
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
Move module time to main()
Move module time to main()
Python
bsd-2-clause
bowen0701/algorithms_data_structures
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main() Move module time to main()
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
<commit_before>"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main() <commit_msg>Move module time to main()<commit_after>
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main() Move module time to main()"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
<commit_before>"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main() <commit_msg>Move module time to main()<commit_after>"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import print_function def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
ea5fd30a583016b4dc858848e28168ada74deca3
blaze/py3help.py
blaze/py3help.py
import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib urlparse = urllib.parse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse
import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib.parse as urlparse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse
Check in fix for py3k and urlparse.
Check in fix for py3k and urlparse.
Python
bsd-3-clause
scls19fr/blaze,markflorisson/blaze-core,ChinaQuants/blaze,jdmcbr/blaze,nkhuyu/blaze,cpcloud/blaze,LiaoPan/blaze,FrancescAlted/blaze,cowlicks/blaze,FrancescAlted/blaze,mwiebe/blaze,markflorisson/blaze-core,mwiebe/blaze,ContinuumIO/blaze,FrancescAlted/blaze,aterrel/blaze,AbhiAgarwal/blaze,jdmcbr/blaze,aterrel/blaze,ChinaQuants/blaze,mwiebe/blaze,mrocklin/blaze,jcrist/blaze,AbhiAgarwal/blaze,mwiebe/blaze,nkhuyu/blaze,alexmojaki/blaze,AbhiAgarwal/blaze,markflorisson/blaze-core,cowlicks/blaze,dwillmer/blaze,cpcloud/blaze,mrocklin/blaze,xlhtc007/blaze,maxalbert/blaze,alexmojaki/blaze,aterrel/blaze,caseyclements/blaze,FrancescAlted/blaze,caseyclements/blaze,xlhtc007/blaze,dwillmer/blaze,ContinuumIO/blaze,markflorisson/blaze-core,AbhiAgarwal/blaze,scls19fr/blaze,maxalbert/blaze,jcrist/blaze,LiaoPan/blaze
import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib urlparse = urllib.parse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse Check in fix for py3k and urlparse.
import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib.parse as urlparse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse
<commit_before>import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib urlparse = urllib.parse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse <commit_msg>Check in fix for py3k and urlparse.<commit_after>
import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib.parse as urlparse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse
import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib urlparse = urllib.parse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse Check in fix for py3k and urlparse.import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib.parse as urlparse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse
<commit_before>import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib urlparse = urllib.parse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse <commit_msg>Check in fix for py3k and urlparse.<commit_after>import sys import itertools PY3 = sys.version_info[:2] >= (3,0) if PY3: def dict_iteritems(d): return d.items().__iter__() xrange = range _inttypes = (int,) _strtypes = (str,) unicode = str imap = map basestring = str import urllib.parse as urlparse else: import __builtin__ def dict_iteritems(d): return d.iteritems() xrange = __builtin__.xrange unicode = __builtin__.unicode basestring = __builtin__.basestring _strtypes = (str, unicode) _inttypes = (int, long) imap = itertools.imap import urlparse
05b2848849553172873600ffd6344fc2b1f12d8e
example/__init__.py
example/__init__.py
from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ex' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013']
from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013']
Substitute a more realistic jurisdiction_id
Substitute a more realistic jurisdiction_id
Python
bsd-3-clause
datamade/pupa,mileswwatkins/pupa,rshorey/pupa,opencivicdata/pupa,mileswwatkins/pupa,influence-usa/pupa,datamade/pupa,influence-usa/pupa,rshorey/pupa,opencivicdata/pupa
from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ex' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013'] Substitute a more realistic jurisdiction_id
from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013']
<commit_before>from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ex' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013'] <commit_msg>Substitute a more realistic jurisdiction_id<commit_after>
from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013']
from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ex' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013'] Substitute a more realistic jurisdiction_idfrom pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013']
<commit_before>from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ex' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013'] <commit_msg>Substitute a more realistic jurisdiction_id<commit_after>from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013']
3298fff0ded49c21897a7387a7f3093c351ae04f
scripts/run_psql.py
scripts/run_psql.py
#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import subprocess def main(script, opts, args): subprocess.call(['psql'] + script.config.database.create_psql_args()) run_script(main)
#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import os def main(script, opts, args): os.execlp('psql', 'psql', *script.config.database.create_psql_args()) run_script(main)
Use os.exelp to launch psql
Use os.exelp to launch psql
Python
mit
lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server
#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import subprocess def main(script, opts, args): subprocess.call(['psql'] + script.config.database.create_psql_args()) run_script(main) Use os.exelp to launch psql
#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import os def main(script, opts, args): os.execlp('psql', 'psql', *script.config.database.create_psql_args()) run_script(main)
<commit_before>#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import subprocess def main(script, opts, args): subprocess.call(['psql'] + script.config.database.create_psql_args()) run_script(main) <commit_msg>Use os.exelp to launch psql<commit_after>
#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import os def main(script, opts, args): os.execlp('psql', 'psql', *script.config.database.create_psql_args()) run_script(main)
#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import subprocess def main(script, opts, args): subprocess.call(['psql'] + script.config.database.create_psql_args()) run_script(main) Use os.exelp to launch psql#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import os def main(script, opts, args): os.execlp('psql', 'psql', *script.config.database.create_psql_args()) run_script(main)
<commit_before>#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import subprocess def main(script, opts, args): subprocess.call(['psql'] + script.config.database.create_psql_args()) run_script(main) <commit_msg>Use os.exelp to launch psql<commit_after>#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script import os def main(script, opts, args): os.execlp('psql', 'psql', *script.config.database.create_psql_args()) run_script(main)
e10f2b85775412dd60f11deea6e7a7f8b84edfbe
buysafe/urls.py
buysafe/urls.py
from django.conf.urls import patterns urlpatterns = patterns( 'buysafe.views', (r'^entry/(?P<order_id>\d+)/$', 'entry'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
Add name for entry view URL
Add name for entry view URL
Python
bsd-3-clause
uranusjr/django-buysafe
from django.conf.urls import patterns urlpatterns = patterns( 'buysafe.views', (r'^entry/(?P<order_id>\d+)/$', 'entry'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') ) Add name for entry view URL
from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
<commit_before>from django.conf.urls import patterns urlpatterns = patterns( 'buysafe.views', (r'^entry/(?P<order_id>\d+)/$', 'entry'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') ) <commit_msg>Add name for entry view URL<commit_after>
from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
from django.conf.urls import patterns urlpatterns = patterns( 'buysafe.views', (r'^entry/(?P<order_id>\d+)/$', 'entry'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') ) Add name for entry view URLfrom django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
<commit_before>from django.conf.urls import patterns urlpatterns = patterns( 'buysafe.views', (r'^entry/(?P<order_id>\d+)/$', 'entry'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') ) <commit_msg>Add name for entry view URL<commit_after>from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
202a9b2ad72ffe4ab5981f9a4a886e0a36808eb6
tests/sentry/utils/json/tests.py
tests/sentry/utils/json/tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"'
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' def test_inf(self): res = float('inf') self.assertEquals(json.dumps(res), 'null')
Add test for handling Infinity in json
Add test for handling Infinity in json
Python
bsd-3-clause
mitsuhiko/sentry,ifduyue/sentry,looker/sentry,mvaled/sentry,gencer/sentry,mvaled/sentry,looker/sentry,zenefits/sentry,korealerts1/sentry,zenefits/sentry,Kryz/sentry,kevinlondon/sentry,alexm92/sentry,JamesMura/sentry,mvaled/sentry,kevinlondon/sentry,looker/sentry,beeftornado/sentry,BuildingLink/sentry,ifduyue/sentry,felixbuenemann/sentry,looker/sentry,JamesMura/sentry,ngonzalvez/sentry,zenefits/sentry,gencer/sentry,jean/sentry,fotinakis/sentry,gencer/sentry,daevaorn/sentry,Kryz/sentry,jean/sentry,korealerts1/sentry,BuildingLink/sentry,fotinakis/sentry,imankulov/sentry,daevaorn/sentry,felixbuenemann/sentry,BayanGroup/sentry,beeftornado/sentry,alexm92/sentry,nicholasserra/sentry,kevinlondon/sentry,mitsuhiko/sentry,JackDanger/sentry,felixbuenemann/sentry,mvaled/sentry,ngonzalvez/sentry,Natim/sentry,BuildingLink/sentry,nicholasserra/sentry,JackDanger/sentry,JamesMura/sentry,daevaorn/sentry,JamesMura/sentry,mvaled/sentry,imankulov/sentry,fotinakis/sentry,jean/sentry,BuildingLink/sentry,Natim/sentry,BayanGroup/sentry,BuildingLink/sentry,mvaled/sentry,ifduyue/sentry,imankulov/sentry,JackDanger/sentry,gencer/sentry,daevaorn/sentry,ifduyue/sentry,gencer/sentry,fotinakis/sentry,jean/sentry,BayanGroup/sentry,zenefits/sentry,Kryz/sentry,ngonzalvez/sentry,korealerts1/sentry,zenefits/sentry,Natim/sentry,ifduyue/sentry,jean/sentry,looker/sentry,alexm92/sentry,beeftornado/sentry,nicholasserra/sentry,JamesMura/sentry
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' Add test for handling Infinity in json
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' def test_inf(self): res = float('inf') self.assertEquals(json.dumps(res), 'null')
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' <commit_msg>Add test for handling Infinity in json<commit_after>
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' def test_inf(self): res = float('inf') self.assertEquals(json.dumps(res), 'null')
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' Add test for handling Infinity in json# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' def test_inf(self): res = float('inf') self.assertEquals(json.dumps(res), 'null')
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' <commit_msg>Add test for handling Infinity in json<commit_after># -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' def test_inf(self): res = float('inf') self.assertEquals(json.dumps(res), 'null')
27fec389928c93ba0efe4ca1e4c5b34c3b73fa2c
snippet/__init__.py
snippet/__init__.py
""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """
""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """ __version__ = '2.3.6.1'
Add a version base on djangocms version from where the code was cloned
Add a version base on djangocms version from where the code was cloned
Python
bsd-3-clause
emencia/emencia-cms-snippet,emencia/emencia-cms-snippet,emencia/emencia-cms-snippet
""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """Add a version base on djangocms version from where the code was cloned
""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """ __version__ = '2.3.6.1'
<commit_before>""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """<commit_msg>Add a version base on djangocms version from where the code was cloned<commit_after>
""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """ __version__ = '2.3.6.1'
""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """Add a version base on djangocms version from where the code was cloned""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """ __version__ = '2.3.6.1'
<commit_before>""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """<commit_msg>Add a version base on djangocms version from where the code was cloned<commit_after>""" "cms.plugins.snippet" (from djangocms) clone to extend it with some facilities """ __version__ = '2.3.6.1'
de22e547c57be633cb32d51e93a6efe9c9e90293
src/helper_threading.py
src/helper_threading.py
import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: log('WARN: prctl module is not installed. You will not be able to see thread names') def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set()
import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set()
Remove buggy log message if prctl is missing
Remove buggy log message if prctl is missing - it's not that important that you need to be informed of it, and importing logging may cause cyclic dependencies/other problems
Python
mit
hb9kns/PyBitmessage,hb9kns/PyBitmessage,hb9kns/PyBitmessage,hb9kns/PyBitmessage
import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: log('WARN: prctl module is not installed. You will not be able to see thread names') def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set() Remove buggy log message if prctl is missing - it's not that important that you need to be informed of it, and importing logging may cause cyclic dependencies/other problems
import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set()
<commit_before>import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: log('WARN: prctl module is not installed. You will not be able to see thread names') def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set() <commit_msg>Remove buggy log message if prctl is missing - it's not that important that you need to be informed of it, and importing logging may cause cyclic dependencies/other problems<commit_after>
import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set()
import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: log('WARN: prctl module is not installed. You will not be able to see thread names') def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set() Remove buggy log message if prctl is missing - it's not that important that you need to be informed of it, and importing logging may cause cyclic dependencies/other problemsimport threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set()
<commit_before>import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: log('WARN: prctl module is not installed. You will not be able to see thread names') def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set() <commit_msg>Remove buggy log message if prctl is missing - it's not that important that you need to be informed of it, and importing logging may cause cyclic dependencies/other problems<commit_after>import threading try: import prctl def set_thread_name(name): prctl.set_name(name) def _thread_name_hack(self): set_thread_name(self.name) threading.Thread.__bootstrap_original__(self) threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap threading.Thread._Thread__bootstrap = _thread_name_hack except ImportError: def set_thread_name(name): pass class StoppableThread(object): def initStop(self): self.stop = threading.Event() self._stopped = False def stopThread(self): self._stopped = True self.stop.set()
a25920e3549933e4c6c158cc9490f3eaa883ec66
Lib/test/test_heapq.py
Lib/test/test_heapq.py
"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): parentpos = ((pos+1) >> 1) - 1 if parentpos >= 0: verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main()
"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): if pos: # pos 0 has no parent parentpos = (pos-1) >> 1 verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main()
Use the same child->parent "formula" used by heapq.py.
check_invariant(): Use the same child->parent "formula" used by heapq.py.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): parentpos = ((pos+1) >> 1) - 1 if parentpos >= 0: verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main() check_invariant(): Use the same child->parent "formula" used by heapq.py.
"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): if pos: # pos 0 has no parent parentpos = (pos-1) >> 1 verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main()
<commit_before>"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): parentpos = ((pos+1) >> 1) - 1 if parentpos >= 0: verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main() <commit_msg>check_invariant(): Use the same child->parent "formula" used by heapq.py.<commit_after>
"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): if pos: # pos 0 has no parent parentpos = (pos-1) >> 1 verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main()
"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): parentpos = ((pos+1) >> 1) - 1 if parentpos >= 0: verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main() check_invariant(): Use the same child->parent "formula" used by heapq.py."""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): if pos: # pos 0 has no parent parentpos = (pos-1) >> 1 verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main()
<commit_before>"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): parentpos = ((pos+1) >> 1) - 1 if parentpos >= 0: verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main() <commit_msg>check_invariant(): Use the same child->parent "formula" used by heapq.py.<commit_after>"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): if pos: # pos 0 has no parent parentpos = (pos-1) >> 1 verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main()
b12b4f47d3cd701506380c914e45b9958490392c
functional_tests.py
functional_tests.py
from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title
from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): # Edith has heard about a cool new onlien to-do app. She goes # to check out its homepage self.browser.get('http://localhost:8000') # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # She is invited to enter a to-do item straight away # Edith has heard about a cool new online to-do app. She goes # to check out its homepage # She notices the page title and header mention to-do lists # She is invited to enter a to-do item straight away # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) # When she hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an itme in a to-do list # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very methodical) # The page updates again, and now shows both updates on her list # Edith wonders whether the site will remember her list. Then she sees # that the site has generated a unique URL for her -- there is some # explanatory text to that effect. # She visits that URL - her to-do list is still there. # Satisfied, she goes back to sleep if __name__ == '__main__': unittest.main(warnings='ignore')
Add FT specs and use unittest.
Add FT specs and use unittest.
Python
mit
ejpreciado/superlists,ejpreciado/superlists,ejpreciado/superlists
from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title Add FT specs and use unittest.
from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): # Edith has heard about a cool new onlien to-do app. She goes # to check out its homepage self.browser.get('http://localhost:8000') # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # She is invited to enter a to-do item straight away # Edith has heard about a cool new online to-do app. She goes # to check out its homepage # She notices the page title and header mention to-do lists # She is invited to enter a to-do item straight away # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) # When she hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an itme in a to-do list # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very methodical) # The page updates again, and now shows both updates on her list # Edith wonders whether the site will remember her list. Then she sees # that the site has generated a unique URL for her -- there is some # explanatory text to that effect. # She visits that URL - her to-do list is still there. # Satisfied, she goes back to sleep if __name__ == '__main__': unittest.main(warnings='ignore')
<commit_before>from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title <commit_msg>Add FT specs and use unittest.<commit_after>
from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): # Edith has heard about a cool new onlien to-do app. She goes # to check out its homepage self.browser.get('http://localhost:8000') # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # She is invited to enter a to-do item straight away # Edith has heard about a cool new online to-do app. She goes # to check out its homepage # She notices the page title and header mention to-do lists # She is invited to enter a to-do item straight away # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) # When she hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an itme in a to-do list # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very methodical) # The page updates again, and now shows both updates on her list # Edith wonders whether the site will remember her list. Then she sees # that the site has generated a unique URL for her -- there is some # explanatory text to that effect. # She visits that URL - her to-do list is still there. # Satisfied, she goes back to sleep if __name__ == '__main__': unittest.main(warnings='ignore')
from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title Add FT specs and use unittest.from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): # Edith has heard about a cool new onlien to-do app. She goes # to check out its homepage self.browser.get('http://localhost:8000') # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # She is invited to enter a to-do item straight away # Edith has heard about a cool new online to-do app. She goes # to check out its homepage # She notices the page title and header mention to-do lists # She is invited to enter a to-do item straight away # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) # When she hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an itme in a to-do list # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very methodical) # The page updates again, and now shows both updates on her list # Edith wonders whether the site will remember her list. Then she sees # that the site has generated a unique URL for her -- there is some # explanatory text to that effect. # She visits that URL - her to-do list is still there. # Satisfied, she goes back to sleep if __name__ == '__main__': unittest.main(warnings='ignore')
<commit_before>from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title <commit_msg>Add FT specs and use unittest.<commit_after>from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): # Edith has heard about a cool new onlien to-do app. She goes # to check out its homepage self.browser.get('http://localhost:8000') # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # She is invited to enter a to-do item straight away # Edith has heard about a cool new online to-do app. She goes # to check out its homepage # She notices the page title and header mention to-do lists # She is invited to enter a to-do item straight away # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) # When she hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an itme in a to-do list # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very methodical) # The page updates again, and now shows both updates on her list # Edith wonders whether the site will remember her list. Then she sees # that the site has generated a unique URL for her -- there is some # explanatory text to that effect. # She visits that URL - her to-do list is still there. # Satisfied, she goes back to sleep if __name__ == '__main__': unittest.main(warnings='ignore')
d98e33d28105c8180b591e3097af83e42599bfc5
django_local_apps/management/commands/docker_exec.py
django_local_apps/management/commands/docker_exec.py
import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ parser.add_argument('--container_id', nargs=1) parser.add_argument('--work_dir', nargs='?', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"][0]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"])) Command = DockerExecutor
import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ # for using with chronograph, do not use nargs param, because chronograph seems do not support passing # array, but using nargs will generate a list for the parameters parser.add_argument('-c', '--container_id') parser.add_argument('-w', '--work_dir', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["container_id"]) print(self.options["work_dir"]) print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=(self.options["work_dir"]))) Command = DockerExecutor
Remove the usage of nargs to avoid different behaviors between chronograph and command line.
Remove the usage of nargs to avoid different behaviors between chronograph and command line.
Python
bsd-3-clause
weijia/django-local-apps,weijia/django-local-apps
import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ parser.add_argument('--container_id', nargs=1) parser.add_argument('--work_dir', nargs='?', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"][0]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"])) Command = DockerExecutor Remove the usage of nargs to avoid different behaviors between chronograph and command line.
import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ # for using with chronograph, do not use nargs param, because chronograph seems do not support passing # array, but using nargs will generate a list for the parameters parser.add_argument('-c', '--container_id') parser.add_argument('-w', '--work_dir', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["container_id"]) print(self.options["work_dir"]) print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=(self.options["work_dir"]))) Command = DockerExecutor
<commit_before>import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ parser.add_argument('--container_id', nargs=1) parser.add_argument('--work_dir', nargs='?', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"][0]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"])) Command = DockerExecutor <commit_msg>Remove the usage of nargs to avoid different behaviors between chronograph and command line.<commit_after>
import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ # for using with chronograph, do not use nargs param, because chronograph seems do not support passing # array, but using nargs will generate a list for the parameters parser.add_argument('-c', '--container_id') parser.add_argument('-w', '--work_dir', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["container_id"]) print(self.options["work_dir"]) print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=(self.options["work_dir"]))) Command = DockerExecutor
import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ parser.add_argument('--container_id', nargs=1) parser.add_argument('--work_dir', nargs='?', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"][0]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"])) Command = DockerExecutor Remove the usage of nargs to avoid different behaviors between chronograph and command line.import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ # for using with chronograph, do not use nargs param, because chronograph seems do not support passing # array, but using nargs will generate a list for the parameters parser.add_argument('-c', '--container_id') parser.add_argument('-w', '--work_dir', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["container_id"]) print(self.options["work_dir"]) print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=(self.options["work_dir"]))) Command = DockerExecutor
<commit_before>import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ parser.add_argument('--container_id', nargs=1) parser.add_argument('--work_dir', nargs='?', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"][0]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"])) Command = DockerExecutor <commit_msg>Remove the usage of nargs to avoid different behaviors between chronograph and command line.<commit_after>import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ # for using with chronograph, do not use nargs param, because chronograph seems do not support passing # array, but using nargs will generate a list for the parameters parser.add_argument('-c', '--container_id') parser.add_argument('-w', '--work_dir', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["container_id"]) print(self.options["work_dir"]) print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=(self.options["work_dir"]))) Command = DockerExecutor
36e7af17c8d7c4bdb9cfd20387c470697e1bac96
po/build-babel.py
po/build-babel.py
import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={str(input)}", f"--output-file={str(output_file)}", f"--locale={str(locale)}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files()
import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={input}", f"--output-file={output_file}", f"--locale={locale}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files()
Simplify f-string to remove cast
Simplify f-string to remove cast
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={str(input)}", f"--output-file={str(output_file)}", f"--locale={str(locale)}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files() Simplify f-string to remove cast
import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={input}", f"--output-file={output_file}", f"--locale={locale}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files()
<commit_before>import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={str(input)}", f"--output-file={str(output_file)}", f"--locale={str(locale)}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files() <commit_msg>Simplify f-string to remove cast<commit_after>
import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={input}", f"--output-file={output_file}", f"--locale={locale}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files()
import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={str(input)}", f"--output-file={str(output_file)}", f"--locale={str(locale)}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files() Simplify f-string to remove castimport subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={input}", f"--output-file={output_file}", f"--locale={locale}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files()
<commit_before>import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={str(input)}", f"--output-file={str(output_file)}", f"--locale={str(locale)}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files() <commit_msg>Simplify f-string to remove cast<commit_after>import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={input}", f"--output-file={output_file}", f"--locale={locale}", "--domain=gaphor", ] ) def update_po_files(): pot_path = po_path / "gaphor.pot" for path in (path for path in po_path.iterdir() if path.suffix == ".po"): run_babel("update", pot_path, path, path.stem) def compile_mo_files(): for path in (path for path in po_path.iterdir() if path.suffix == ".po"): mo_path = po_path.parent / "locale" / path.stem / "LC_MESSAGES" / "gaphor.mo" mo_path.parent.mkdir(parents=True, exist_ok=True) run_babel("compile", path, mo_path, path.stem) if __name__ == "__main__": update_po_files() compile_mo_files()
7cee7edabad08b01ceda0ed8f2798ebf47c87e95
src/pycontw2016/urls.py
src/pycontw2016/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 from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. urlpatterns += [ url(r'^(?P<path>.+)/$', flat_page, name='page'), ]
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. if settings.URL_PREFIX: urlpatterns += [ url(r'^{prefix}(?P<path>.+)/$'.format(prefix=settings.URL_PREFIX), flat_page, name='page'), ] else: urlpatterns += [url(r'^(?P<path>.+)/$', flat_page, name='page')]
Fix catch-all URLs with prefix
Fix catch-all URLs with prefix
Python
mit
uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. urlpatterns += [ url(r'^(?P<path>.+)/$', flat_page, name='page'), ] Fix catch-all URLs with prefix
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. if settings.URL_PREFIX: urlpatterns += [ url(r'^{prefix}(?P<path>.+)/$'.format(prefix=settings.URL_PREFIX), flat_page, name='page'), ] else: urlpatterns += [url(r'^(?P<path>.+)/$', flat_page, name='page')]
<commit_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 from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. urlpatterns += [ url(r'^(?P<path>.+)/$', flat_page, name='page'), ] <commit_msg>Fix catch-all URLs with prefix<commit_after>
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. if settings.URL_PREFIX: urlpatterns += [ url(r'^{prefix}(?P<path>.+)/$'.format(prefix=settings.URL_PREFIX), flat_page, name='page'), ] else: urlpatterns += [url(r'^(?P<path>.+)/$', flat_page, name='page')]
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. urlpatterns += [ url(r'^(?P<path>.+)/$', flat_page, name='page'), ] Fix catch-all URLs with prefixfrom django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. if settings.URL_PREFIX: urlpatterns += [ url(r'^{prefix}(?P<path>.+)/$'.format(prefix=settings.URL_PREFIX), flat_page, name='page'), ] else: urlpatterns += [url(r'^(?P<path>.+)/$', flat_page, name='page')]
<commit_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 from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. urlpatterns += [ url(r'^(?P<path>.+)/$', flat_page, name='page'), ] <commit_msg>Fix catch-all URLs with prefix<commit_after>from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from core.views import flat_page from users.views import user_dashboard urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'), url(r'^dashboard/$', user_dashboard, name='user_dashboard'), url(r'^accounts/', include('users.urls')), url(r'^proposals/', include('proposals.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.URL_PREFIX: urlpatterns = [ url(r'^{prefix}'.format(prefix=settings.URL_PREFIX), include(urlpatterns)), ] # User-uploaded files like profile pics need to be served in development urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Catch-all URL pattern must be put last. if settings.URL_PREFIX: urlpatterns += [ url(r'^{prefix}(?P<path>.+)/$'.format(prefix=settings.URL_PREFIX), flat_page, name='page'), ] else: urlpatterns += [url(r'^(?P<path>.+)/$', flat_page, name='page')]
e2cbd73218e6f5cf5b86718f6adebd92e9fee2a3
geotrek/trekking/tests/test_filters.py
geotrek/trekking/tests/test_filters.py
from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path
# Make sure land filters are set up when testing from geotrek.land.filters import * # NOQA from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path
Make sure land filters are set up when testing
Make sure land filters are set up when testing
Python
bsd-2-clause
GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,mabhub/Geotrek,Anaethelion/Geotrek
from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path Make sure land filters are set up when testing
# Make sure land filters are set up when testing from geotrek.land.filters import * # NOQA from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path
<commit_before>from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path <commit_msg>Make sure land filters are set up when testing<commit_after>
# Make sure land filters are set up when testing from geotrek.land.filters import * # NOQA from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path
from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path Make sure land filters are set up when testing# Make sure land filters are set up when testing from geotrek.land.filters import * # NOQA from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path
<commit_before>from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path <commit_msg>Make sure land filters are set up when testing<commit_after># Make sure land filters are set up when testing from geotrek.land.filters import * # NOQA from geotrek.land.tests.test_filters import LandFiltersTest from geotrek.trekking.filters import TrekFilterSet from geotrek.trekking.factories import TrekFactory class TrekFilterLandTest(LandFiltersTest): filterclass = TrekFilterSet def test_land_filters_are_well_setup(self): filterset = TrekFilterSet() self.assertIn('work', filterset.filters) def create_pair_of_distinct_path(self): useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path() self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path) return useless_path, seek_path
c1b0cfe9fdfbacf71ffbba45b4a8f7efe3fe36a7
docker/dev_wrong_port_warning.py
docker/dev_wrong_port_warning.py
#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import BaseHTTPServer import sys class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( 'Your development environment is trying to connect to the KoBoCAT ' 'container on port 8000 instead of 8001. Please change this. See ' 'https://github.com/kobotoolbox/kobo-docker/issues/301 ' 'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = BaseHTTPServer.HTTPServer(server_address, Handler) httpd.serve_forever()
#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import sys from http.server import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( b'Your development environment is trying to connect to the KoBoCAT ' b'container on port 8000 instead of 8001. Please change this. See ' b'https://github.com/kobotoolbox/kobo-docker/issues/301 ' b'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = HTTPServer(server_address, Handler) httpd.serve_forever()
Update wront port script to Python3
Update wront port script to Python3
Python
bsd-2-clause
kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat
#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import BaseHTTPServer import sys class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( 'Your development environment is trying to connect to the KoBoCAT ' 'container on port 8000 instead of 8001. Please change this. See ' 'https://github.com/kobotoolbox/kobo-docker/issues/301 ' 'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = BaseHTTPServer.HTTPServer(server_address, Handler) httpd.serve_forever() Update wront port script to Python3
#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import sys from http.server import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( b'Your development environment is trying to connect to the KoBoCAT ' b'container on port 8000 instead of 8001. Please change this. See ' b'https://github.com/kobotoolbox/kobo-docker/issues/301 ' b'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = HTTPServer(server_address, Handler) httpd.serve_forever()
<commit_before>#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import BaseHTTPServer import sys class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( 'Your development environment is trying to connect to the KoBoCAT ' 'container on port 8000 instead of 8001. Please change this. See ' 'https://github.com/kobotoolbox/kobo-docker/issues/301 ' 'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = BaseHTTPServer.HTTPServer(server_address, Handler) httpd.serve_forever() <commit_msg>Update wront port script to Python3<commit_after>
#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import sys from http.server import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( b'Your development environment is trying to connect to the KoBoCAT ' b'container on port 8000 instead of 8001. Please change this. See ' b'https://github.com/kobotoolbox/kobo-docker/issues/301 ' b'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = HTTPServer(server_address, Handler) httpd.serve_forever()
#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import BaseHTTPServer import sys class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( 'Your development environment is trying to connect to the KoBoCAT ' 'container on port 8000 instead of 8001. Please change this. See ' 'https://github.com/kobotoolbox/kobo-docker/issues/301 ' 'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = BaseHTTPServer.HTTPServer(server_address, Handler) httpd.serve_forever() Update wront port script to Python3#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import sys from http.server import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( b'Your development environment is trying to connect to the KoBoCAT ' b'container on port 8000 instead of 8001. Please change this. See ' b'https://github.com/kobotoolbox/kobo-docker/issues/301 ' b'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = HTTPServer(server_address, Handler) httpd.serve_forever()
<commit_before>#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import BaseHTTPServer import sys class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( 'Your development environment is trying to connect to the KoBoCAT ' 'container on port 8000 instead of 8001. Please change this. See ' 'https://github.com/kobotoolbox/kobo-docker/issues/301 ' 'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = BaseHTTPServer.HTTPServer(server_address, Handler) httpd.serve_forever() <commit_msg>Update wront port script to Python3<commit_after>#!/usr/bin/env python """ Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This provides a helpful message to anyone still trying to use port 8000 """ import sys from http.server import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(503) self.end_headers() self.wfile.write( b'Your development environment is trying to connect to the KoBoCAT ' b'container on port 8000 instead of 8001. Please change this. See ' b'https://github.com/kobotoolbox/kobo-docker/issues/301 ' b'for more details.' ) server_address = ('', int(sys.argv[1])) httpd = HTTPServer(server_address, Handler) httpd.serve_forever()
fee10efeae410a0bc51842877ef8ffb5fe8b97af
src/file_dialogs.py
src/file_dialogs.py
#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: raise Exception("not implemented") else: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath()
#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: import gtk dlg = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) flt = gtk.FileFilter() flt.set_name("JSON files") flt.add_pattern("*.json"); dlg.add_filter(flt) flt = gtk.FileFilter() flt.set_name("All files") flt.add_pattern("*.*"); dlg.add_filter(flt) resp = dlg.run() if resp == gtk.RESPONSE_CANCEL: dlg.destroy() return None f = dlg.get_filename() dlg.destroy() return f elif message_loop.is_wx: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() else: raise Exception("Not implemented.")
Add gtk implementation of open_file
Add gtk implementation of open_file
Python
apache-2.0
natduca/trace_event_viewer,natduca/trace_event_viewer,natduca/trace_event_viewer
#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: raise Exception("not implemented") else: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() Add gtk implementation of open_file
#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: import gtk dlg = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) flt = gtk.FileFilter() flt.set_name("JSON files") flt.add_pattern("*.json"); dlg.add_filter(flt) flt = gtk.FileFilter() flt.set_name("All files") flt.add_pattern("*.*"); dlg.add_filter(flt) resp = dlg.run() if resp == gtk.RESPONSE_CANCEL: dlg.destroy() return None f = dlg.get_filename() dlg.destroy() return f elif message_loop.is_wx: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() else: raise Exception("Not implemented.")
<commit_before>#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: raise Exception("not implemented") else: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() <commit_msg>Add gtk implementation of open_file<commit_after>
#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: import gtk dlg = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) flt = gtk.FileFilter() flt.set_name("JSON files") flt.add_pattern("*.json"); dlg.add_filter(flt) flt = gtk.FileFilter() flt.set_name("All files") flt.add_pattern("*.*"); dlg.add_filter(flt) resp = dlg.run() if resp == gtk.RESPONSE_CANCEL: dlg.destroy() return None f = dlg.get_filename() dlg.destroy() return f elif message_loop.is_wx: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() else: raise Exception("Not implemented.")
#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: raise Exception("not implemented") else: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() Add gtk implementation of open_file#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: import gtk dlg = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) flt = gtk.FileFilter() flt.set_name("JSON files") flt.add_pattern("*.json"); dlg.add_filter(flt) flt = gtk.FileFilter() flt.set_name("All files") flt.add_pattern("*.*"); dlg.add_filter(flt) resp = dlg.run() if resp == gtk.RESPONSE_CANCEL: dlg.destroy() return None f = dlg.get_filename() dlg.destroy() return f elif message_loop.is_wx: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() else: raise Exception("Not implemented.")
<commit_before>#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: raise Exception("not implemented") else: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() <commit_msg>Add gtk implementation of open_file<commit_after>#!/usr/bin/env python # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import message_loop def open_file(): message_loop.init_main_loop() if message_loop.is_gtk: import gtk dlg = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) flt = gtk.FileFilter() flt.set_name("JSON files") flt.add_pattern("*.json"); dlg.add_filter(flt) flt = gtk.FileFilter() flt.set_name("All files") flt.add_pattern("*.*"); dlg.add_filter(flt) resp = dlg.run() if resp == gtk.RESPONSE_CANCEL: dlg.destroy() return None f = dlg.get_filename() dlg.destroy() return f elif message_loop.is_wx: import wx wc = "JSON files (*.json)|*.json|All files (*.*)|*.*" fd = wx.FileDialog(None, "Open trace file...", style=wx.FD_OPEN, wildcard=wc) res = fd.ShowModal() if res != wx.ID_OK: return None return fd.GetPath() else: raise Exception("Not implemented.")
6104b111b4ceaec894018b77cbea4a0de31400d4
chainer/trainer/extensions/_snapshot.py
chainer/trainer/extensions/_snapshot.py
from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext
from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(name='snapshot', trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext
Add name to the snapshot extension
Add name to the snapshot extension
Python
mit
hvy/chainer,jnishi/chainer,ktnyt/chainer,chainer/chainer,cupy/cupy,hvy/chainer,ktnyt/chainer,cupy/cupy,wkentaro/chainer,ysekky/chainer,kikusu/chainer,pfnet/chainer,jnishi/chainer,okuta/chainer,keisuke-umezawa/chainer,ktnyt/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,cupy/cupy,rezoo/chainer,chainer/chainer,hvy/chainer,delta2323/chainer,chainer/chainer,aonotas/chainer,wkentaro/chainer,keisuke-umezawa/chainer,tkerola/chainer,niboshi/chainer,niboshi/chainer,kashif/chainer,chainer/chainer,jnishi/chainer,keisuke-umezawa/chainer,kikusu/chainer,cupy/cupy,keisuke-umezawa/chainer,anaruse/chainer,okuta/chainer,wkentaro/chainer,jnishi/chainer,wkentaro/chainer,ronekko/chainer,ktnyt/chainer,kiyukuta/chainer,hvy/chainer,okuta/chainer
from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext Add name to the snapshot extension
from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(name='snapshot', trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext
<commit_before>from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext <commit_msg>Add name to the snapshot extension<commit_after>
from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(name='snapshot', trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext
from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext Add name to the snapshot extensionfrom chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(name='snapshot', trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext
<commit_before>from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext <commit_msg>Add name to the snapshot extension<commit_after>from chainer.serializers import npz from chainer.trainer import extension def snapshot(savefun=npz.save_npz, filename='snapshot_iter_{.updater.iteration}'): """Return a trainer extension to take snapshots of the trainer. This extension serializes the trainer object and saves it to the output directory. It is used to support resuming the training loop from the saved state. This extension is called once for each epoch by default. .. note:: This extension first writes the serialized object to a temporary file and then rename it to the target file name. Thus, if the program stops right before the renaming, the temporary file might be left in the output directory. Args: savefun: Function to save the trainer. It takes two arguments: the output file path and the trainer object. filename (str): Name of the file into which the trainer is serialized. It can be a format string, where the trainer object is passed to the :meth:`str.format` method. """ @extension.make_extension(name='snapshot', trigger=(1, 'epoch')) def ext(trainer): fname = filename.format(trainer) fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out) try: savefun(tmppath, trainer) finally: os.close(fd) os.rename(tmppath, os.path.join(trainer.out, fname)) return ext
ab6b61d8d0b91ebc2d0b1b8cbd526cfbb6a45a42
chipy_org/libs/social_auth_pipelines.py
chipy_org/libs/social_auth_pipelines.py
from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github'] or kwargs.get('user'): # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
Check for a user from previously in the pipeline before checking for duplicate user.
Check for a user from previously in the pipeline before checking for duplicate user.
Python
mit
chicagopython/chipy.org,tanyaschlusser/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,brianray/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org,brianray/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,brianray/chipy.org,agfor/chipy.org
from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) Check for a user from previously in the pipeline before checking for duplicate user.
from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github'] or kwargs.get('user'): # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
<commit_before>from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) <commit_msg>Check for a user from previously in the pipeline before checking for duplicate user.<commit_after>
from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github'] or kwargs.get('user'): # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) Check for a user from previously in the pipeline before checking for duplicate user.from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github'] or kwargs.get('user'): # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
<commit_before>from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) <commit_msg>Check for a user from previously in the pipeline before checking for duplicate user.<commit_after>from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github'] or kwargs.get('user'): # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
62a04170e41d599d653e94afe0844576e175c314
settings_example.py
settings_example.py
import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() # Values come from `EMAIL_SUBJECT_RE`. CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() # Values come from `EMAIL_SUBJECT_RE`. TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
Add comments on variable settings
Add comments on variable settings
Python
mit
AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files
import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password') Add comments on variable settings
import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() # Values come from `EMAIL_SUBJECT_RE`. CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() # Values come from `EMAIL_SUBJECT_RE`. TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
<commit_before>import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password') <commit_msg>Add comments on variable settings<commit_after>
import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() # Values come from `EMAIL_SUBJECT_RE`. CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() # Values come from `EMAIL_SUBJECT_RE`. TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password') Add comments on variable settingsimport os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() # Values come from `EMAIL_SUBJECT_RE`. CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() # Values come from `EMAIL_SUBJECT_RE`. TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
<commit_before>import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password') <commit_msg>Add comments on variable settings<commit_after>import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() # Values come from `EMAIL_SUBJECT_RE`. CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() # Values come from `EMAIL_SUBJECT_RE`. TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
0cf45657c01349b6304470e0ee7349e9f62874f5
lbrynet/__init__.py
lbrynet/__init__.py
import logging __version__ = "0.19.0rc3" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler())
import logging __version__ = "0.19.0rc4" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler())
Bump version 0.19.0rc3 --> 0.19.0rc4
Bump version 0.19.0rc3 --> 0.19.0rc4 Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>
Python
mit
lbryio/lbry,lbryio/lbry,lbryio/lbry
import logging __version__ = "0.19.0rc3" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler()) Bump version 0.19.0rc3 --> 0.19.0rc4 Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>
import logging __version__ = "0.19.0rc4" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_before>import logging __version__ = "0.19.0rc3" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler()) <commit_msg>Bump version 0.19.0rc3 --> 0.19.0rc4 Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io><commit_after>
import logging __version__ = "0.19.0rc4" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler())
import logging __version__ = "0.19.0rc3" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler()) Bump version 0.19.0rc3 --> 0.19.0rc4 Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>import logging __version__ = "0.19.0rc4" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_before>import logging __version__ = "0.19.0rc3" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler()) <commit_msg>Bump version 0.19.0rc3 --> 0.19.0rc4 Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io><commit_after>import logging __version__ = "0.19.0rc4" version = tuple(__version__.split('.')) logging.getLogger(__name__).addHandler(logging.NullHandler())
d03b385b5d23c321ee1d4bd2020be1452e8c1cab
pika/__init__.py
pika/__init__.py
# ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p1' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection # Python 2.4 support: add struct.unpack_from if it's missing. try: import struct getattr(struct, "unpack_from") except AttributeError: def _unpack_from(fmt, buf, offset=0): slice = buffer(buf, offset, struct.calcsize(fmt)) return struct.unpack(fmt, slice) struct.unpack_from = _unpack_from
# ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p2' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection
Remove Python 2.4 support monkey patch and bump rev
Remove Python 2.4 support monkey patch and bump rev
Python
bsd-3-clause
reddec/pika,skftn/pika,Tarsbot/pika,shinji-s/pika,jstnlef/pika,zixiliuyue/pika,fkarb/pika-python3,renshawbay/pika-python3,vrtsystems/pika,Zephor5/pika,pika/pika,vitaly-krugl/pika,knowsis/pika,hugoxia/pika,benjamin9999/pika
# ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p1' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection # Python 2.4 support: add struct.unpack_from if it's missing. try: import struct getattr(struct, "unpack_from") except AttributeError: def _unpack_from(fmt, buf, offset=0): slice = buffer(buf, offset, struct.calcsize(fmt)) return struct.unpack(fmt, slice) struct.unpack_from = _unpack_from Remove Python 2.4 support monkey patch and bump rev
# ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p2' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection
<commit_before># ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p1' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection # Python 2.4 support: add struct.unpack_from if it's missing. try: import struct getattr(struct, "unpack_from") except AttributeError: def _unpack_from(fmt, buf, offset=0): slice = buffer(buf, offset, struct.calcsize(fmt)) return struct.unpack(fmt, slice) struct.unpack_from = _unpack_from <commit_msg>Remove Python 2.4 support monkey patch and bump rev<commit_after>
# ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p2' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection
# ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p1' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection # Python 2.4 support: add struct.unpack_from if it's missing. try: import struct getattr(struct, "unpack_from") except AttributeError: def _unpack_from(fmt, buf, offset=0): slice = buffer(buf, offset, struct.calcsize(fmt)) return struct.unpack(fmt, slice) struct.unpack_from = _unpack_from Remove Python 2.4 support monkey patch and bump rev# ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p2' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection
<commit_before># ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p1' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection # Python 2.4 support: add struct.unpack_from if it's missing. try: import struct getattr(struct, "unpack_from") except AttributeError: def _unpack_from(fmt, buf, offset=0): slice = buffer(buf, offset, struct.calcsize(fmt)) return struct.unpack(fmt, slice) struct.unpack_from = _unpack_from <commit_msg>Remove Python 2.4 support monkey patch and bump rev<commit_after># ***** BEGIN LICENSE BLOCK ***** # # For copyright and licensing please refer to COPYING. # # ***** END LICENSE BLOCK ***** __version__ = '0.9.13p2' from pika.connection import ConnectionParameters from pika.connection import URLParameters from pika.credentials import PlainCredentials from pika.spec import BasicProperties from pika.adapters.base_connection import BaseConnection from pika.adapters.asyncore_connection import AsyncoreConnection from pika.adapters.blocking_connection import BlockingConnection from pika.adapters.select_connection import SelectConnection
1382fd8afecdeca9bb1b6961a636b6502c16ad6e
log-preprocessor.py
log-preprocessor.py
__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for e in row: #TODO still need to remove \n from list elements e = re.sub(r'\n','',e) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()
__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for i, s in enumerate(row): row[i] = re.sub(r'\n+', '', s) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()
Enumerate much more elegant to loop through list elements and regex each.
Enumerate much more elegant to loop through list elements and regex each.
Python
apache-2.0
smehan/App-data-reqs,smehan/App-data-reqs
__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for e in row: #TODO still need to remove \n from list elements e = re.sub(r'\n','',e) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()Enumerate much more elegant to loop through list elements and regex each.
__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for i, s in enumerate(row): row[i] = re.sub(r'\n+', '', s) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()
<commit_before>__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for e in row: #TODO still need to remove \n from list elements e = re.sub(r'\n','',e) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()<commit_msg>Enumerate much more elegant to loop through list elements and regex each.<commit_after>
__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for i, s in enumerate(row): row[i] = re.sub(r'\n+', '', s) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()
__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for e in row: #TODO still need to remove \n from list elements e = re.sub(r'\n','',e) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()Enumerate much more elegant to loop through list elements and regex each.__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for i, s in enumerate(row): row[i] = re.sub(r'\n+', '', s) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()
<commit_before>__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for e in row: #TODO still need to remove \n from list elements e = re.sub(r'\n','',e) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()<commit_msg>Enumerate much more elegant to loop through list elements and regex each.<commit_after>__author__ = 'shawnmehan' import csv, os, re # # first lets open the file, which is tab delimited because of , in description field and others with open('./data/AppDataRequest2010-2015.tsv', 'rb') as csvfile: testfile = open("./data/test.tsv", "wb") #TODO get proper line endings, not ^M records = csv.reader(csvfile, delimiter='\t') testwriter = csv.writer(testfile, delimiter='\t') count = 0 for row in records: for i, s in enumerate(row): row[i] = re.sub(r'\n+', '', s) testwriter.writerow(row) count += 1 # for row in records: # target = ','.join(row) # print(target) # if re.match(".*(?<!EOR)$", target): # testwriter.writerow(row) # elif re.match(".*EOR$", target): # # print(row) # # count += 1 # testwriter.writerow(row) # else: # testwriter.writerow(target) print count testfile.close()
d6c5b9a19921ce2c1e3f2e30d6ce0468a5305e80
myflaskapp/tests/test_flask_testing.py
myflaskapp/tests/test_flask_testing.py
from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200)
from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests import datetime as dt import pytest from myflaskapp.user.models import Role, User from myflaskapp.item.models import Item from .factories import UserFactory import requests from bs4 import BeautifulSoup import datetime as dt class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) def test_home_page_can_save_a_POST_request(self): test_list_data = "TERRY BATES MFR" client = requests.session() url = self.get_server_url() + '/lists/' print(url) get_result = client.get(url) soup = BeautifulSoup(get_result.text, 'html.parser') # Find the input tag input = soup.input csrf_token_value = input['value'] print(input['value']) # Create dictionary to store POST params list_data = {'todo-item':test_list_data, 'todo-csrf_token':csrf_token_value} post_result = client.post(url, data=list_data, headers=dict(Referer=url)) # Assert that our test data is in result assert test_list_data in post_result.text # Assert we have one item in DB #assert len(Item.query.all()) == 1
Test with Flask-Testing to test POST request
Test with Flask-Testing to test POST request
Python
mit
terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python
from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) Test with Flask-Testing to test POST request
from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests import datetime as dt import pytest from myflaskapp.user.models import Role, User from myflaskapp.item.models import Item from .factories import UserFactory import requests from bs4 import BeautifulSoup import datetime as dt class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) def test_home_page_can_save_a_POST_request(self): test_list_data = "TERRY BATES MFR" client = requests.session() url = self.get_server_url() + '/lists/' print(url) get_result = client.get(url) soup = BeautifulSoup(get_result.text, 'html.parser') # Find the input tag input = soup.input csrf_token_value = input['value'] print(input['value']) # Create dictionary to store POST params list_data = {'todo-item':test_list_data, 'todo-csrf_token':csrf_token_value} post_result = client.post(url, data=list_data, headers=dict(Referer=url)) # Assert that our test data is in result assert test_list_data in post_result.text # Assert we have one item in DB #assert len(Item.query.all()) == 1
<commit_before>from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) <commit_msg>Test with Flask-Testing to test POST request<commit_after>
from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests import datetime as dt import pytest from myflaskapp.user.models import Role, User from myflaskapp.item.models import Item from .factories import UserFactory import requests from bs4 import BeautifulSoup import datetime as dt class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) def test_home_page_can_save_a_POST_request(self): test_list_data = "TERRY BATES MFR" client = requests.session() url = self.get_server_url() + '/lists/' print(url) get_result = client.get(url) soup = BeautifulSoup(get_result.text, 'html.parser') # Find the input tag input = soup.input csrf_token_value = input['value'] print(input['value']) # Create dictionary to store POST params list_data = {'todo-item':test_list_data, 'todo-csrf_token':csrf_token_value} post_result = client.post(url, data=list_data, headers=dict(Referer=url)) # Assert that our test data is in result assert test_list_data in post_result.text # Assert we have one item in DB #assert len(Item.query.all()) == 1
from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) Test with Flask-Testing to test POST requestfrom flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests import datetime as dt import pytest from myflaskapp.user.models import Role, User from myflaskapp.item.models import Item from .factories import UserFactory import requests from bs4 import BeautifulSoup import datetime as dt class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) def test_home_page_can_save_a_POST_request(self): test_list_data = "TERRY BATES MFR" client = requests.session() url = self.get_server_url() + '/lists/' print(url) get_result = client.get(url) soup = BeautifulSoup(get_result.text, 'html.parser') # Find the input tag input = soup.input csrf_token_value = input['value'] print(input['value']) # Create dictionary to store POST params list_data = {'todo-item':test_list_data, 'todo-csrf_token':csrf_token_value} post_result = client.post(url, data=list_data, headers=dict(Referer=url)) # Assert that our test data is in result assert test_list_data in post_result.text # Assert we have one item in DB #assert len(Item.query.all()) == 1
<commit_before>from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) <commit_msg>Test with Flask-Testing to test POST request<commit_after>from flask import Flask from flask_testing import LiveServerTestCase from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig import requests import datetime as dt import pytest from myflaskapp.user.models import Role, User from myflaskapp.item.models import Item from .factories import UserFactory import requests from bs4 import BeautifulSoup import datetime as dt class MyTest(LiveServerTestCase): def create_app(self): app = create_app(DevConfig) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 55531 return app def test_server_is_up_and_running(self): #server_url = self.get_server_url() #print("SERVER URL:{}".format(server_url)) response = requests.get(self.get_server_url()) self.assertEqual(response.status_code, 200) def test_home_page_can_save_a_POST_request(self): test_list_data = "TERRY BATES MFR" client = requests.session() url = self.get_server_url() + '/lists/' print(url) get_result = client.get(url) soup = BeautifulSoup(get_result.text, 'html.parser') # Find the input tag input = soup.input csrf_token_value = input['value'] print(input['value']) # Create dictionary to store POST params list_data = {'todo-item':test_list_data, 'todo-csrf_token':csrf_token_value} post_result = client.post(url, data=list_data, headers=dict(Referer=url)) # Assert that our test data is in result assert test_list_data in post_result.text # Assert we have one item in DB #assert len(Item.query.all()) == 1
cea891a2de493ce211ccf13f4bf0c487f945985d
test_audio_files.py
test_audio_files.py
import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track.track_from_filename('audio/'+file.filename, force_upload=True)
import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track = track.track_from_filename('audio/'+file.filename, force_upload=True) print(track.id)
Print out the new track id.
Print out the new track id.
Python
artistic-2.0
Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension
import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track.track_from_filename('audio/'+file.filename, force_upload=True) Print out the new track id.
import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track = track.track_from_filename('audio/'+file.filename, force_upload=True) print(track.id)
<commit_before>import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track.track_from_filename('audio/'+file.filename, force_upload=True) <commit_msg>Print out the new track id.<commit_after>
import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track = track.track_from_filename('audio/'+file.filename, force_upload=True) print(track.id)
import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track.track_from_filename('audio/'+file.filename, force_upload=True) Print out the new track id.import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track = track.track_from_filename('audio/'+file.filename, force_upload=True) print(track.id)
<commit_before>import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track.track_from_filename('audio/'+file.filename, force_upload=True) <commit_msg>Print out the new track id.<commit_after>import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track = track.track_from_filename('audio/'+file.filename, force_upload=True) print(track.id)
550b48c0d1b464a782d875e30da140c742cd4b3e
tests/test_bayes.py
tests/test_bayes.py
from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertGreaterEqual(result['numTotal'], result['numSpam'])
from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertTrue(result['numTotal'] >= result['numSpam'])
Replace assertGreaterEqual with assertTrue(a >= b)
Replace assertGreaterEqual with assertTrue(a >= b)
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertGreaterEqual(result['numTotal'], result['numSpam']) Replace assertGreaterEqual with assertTrue(a >= b)
from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertTrue(result['numTotal'] >= result['numSpam'])
<commit_before>from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertGreaterEqual(result['numTotal'], result['numSpam']) <commit_msg>Replace assertGreaterEqual with assertTrue(a >= b)<commit_after>
from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertTrue(result['numTotal'] >= result['numSpam'])
from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertGreaterEqual(result['numTotal'], result['numSpam']) Replace assertGreaterEqual with assertTrue(a >= b)from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertTrue(result['numTotal'] >= result['numSpam'])
<commit_before>from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertGreaterEqual(result['numTotal'], result['numSpam']) <commit_msg>Replace assertGreaterEqual with assertTrue(a >= b)<commit_after>from unittest import TestCase from itertools import repeat, imap, izip, cycle from spicedham.bayes import Bayes from spicedham import Spicedham class TestBayes(TestCase): def test_classify(self): sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) alphabet = map(chr, range(97, 123)) for letter in alphabet: p = b.classify(letter) self.assertEqual(p, 0.5) def _training(self, bayes): alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) messagePairs = izip(alphabet, reversed_alphabet) for message, is_spam in izip(messagePairs, cycle((True, False))): bayes.train(message, is_spam) def test_train(self): alphabet = map(chr, range(97, 123)) sh = Spicedham() b = Bayes(sh.config, sh.backend) b.backend.reset() self._training(b) for letter in alphabet: result = sh.backend.get_key(b.__class__.__name__, letter) self.assertEqual(result, {'numTotal': 2, 'numSpam': 1}) self.assertTrue(result['numTotal'] >= result['numSpam'])
2fdf35f8a9bf7a6249bc92236952655314a47080
swapify/__init__.py
swapify/__init__.py
# -*- encoding: utf-8 -*- __version__ = VERSION = '0.0.0'
# -*- encoding: utf-8 -*- __author__ = 'Sebastian Vetter' __version__ = VERSION = '0.0.0' __license__ = 'MIT'
Add author and lincense variables
Add author and lincense variables
Python
mit
elbaschid/swapify
# -*- encoding: utf-8 -*- __version__ = VERSION = '0.0.0'Add author and lincense variables
# -*- encoding: utf-8 -*- __author__ = 'Sebastian Vetter' __version__ = VERSION = '0.0.0' __license__ = 'MIT'
<commit_before># -*- encoding: utf-8 -*- __version__ = VERSION = '0.0.0'<commit_msg>Add author and lincense variables<commit_after>
# -*- encoding: utf-8 -*- __author__ = 'Sebastian Vetter' __version__ = VERSION = '0.0.0' __license__ = 'MIT'
# -*- encoding: utf-8 -*- __version__ = VERSION = '0.0.0'Add author and lincense variables# -*- encoding: utf-8 -*- __author__ = 'Sebastian Vetter' __version__ = VERSION = '0.0.0' __license__ = 'MIT'
<commit_before># -*- encoding: utf-8 -*- __version__ = VERSION = '0.0.0'<commit_msg>Add author and lincense variables<commit_after># -*- encoding: utf-8 -*- __author__ = 'Sebastian Vetter' __version__ = VERSION = '0.0.0' __license__ = 'MIT'
40897be402bd05ed5fb53e116f03d2d954720245
astrobin_apps_platesolving/utils.py
astrobin_apps_platesolving/utils.py
# Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): url = image.thumbnail(alias) if "://" in url: url = url.split('://')[1] else: url = settings.BASE_URL + url url = 'http://' + urllib2.quote(url.encode('utf-8')) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img)
# Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): def encoded(path): return urllib2.quote(path.encode('utf-8')) url = image.thumbnail(alias) if "://" in url: # We are getting the full path and must only encode the part after the protocol # (we assume that the hostname is ASCII) protocol, path = url.split("://") url = protocol + encoded(path) else: url = settings.BASE_URL + encoded(url) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img)
Fix plate-solving on local development mode
Fix plate-solving on local development mode
Python
agpl-3.0
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
# Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): url = image.thumbnail(alias) if "://" in url: url = url.split('://')[1] else: url = settings.BASE_URL + url url = 'http://' + urllib2.quote(url.encode('utf-8')) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img) Fix plate-solving on local development mode
# Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): def encoded(path): return urllib2.quote(path.encode('utf-8')) url = image.thumbnail(alias) if "://" in url: # We are getting the full path and must only encode the part after the protocol # (we assume that the hostname is ASCII) protocol, path = url.split("://") url = protocol + encoded(path) else: url = settings.BASE_URL + encoded(url) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img)
<commit_before># Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): url = image.thumbnail(alias) if "://" in url: url = url.split('://')[1] else: url = settings.BASE_URL + url url = 'http://' + urllib2.quote(url.encode('utf-8')) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img) <commit_msg>Fix plate-solving on local development mode<commit_after>
# Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): def encoded(path): return urllib2.quote(path.encode('utf-8')) url = image.thumbnail(alias) if "://" in url: # We are getting the full path and must only encode the part after the protocol # (we assume that the hostname is ASCII) protocol, path = url.split("://") url = protocol + encoded(path) else: url = settings.BASE_URL + encoded(url) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img)
# Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): url = image.thumbnail(alias) if "://" in url: url = url.split('://')[1] else: url = settings.BASE_URL + url url = 'http://' + urllib2.quote(url.encode('utf-8')) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img) Fix plate-solving on local development mode# Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): def encoded(path): return urllib2.quote(path.encode('utf-8')) url = image.thumbnail(alias) if "://" in url: # We are getting the full path and must only encode the part after the protocol # (we assume that the hostname is ASCII) protocol, path = url.split("://") url = protocol + encoded(path) else: url = settings.BASE_URL + encoded(url) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img)
<commit_before># Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): url = image.thumbnail(alias) if "://" in url: url = url.split('://')[1] else: url = settings.BASE_URL + url url = 'http://' + urllib2.quote(url.encode('utf-8')) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img) <commit_msg>Fix plate-solving on local development mode<commit_after># Python import urllib2 # Django from django.conf import settings from django.core.files import File from django.core.files.temp import NamedTemporaryFile def getFromStorage(image, alias): def encoded(path): return urllib2.quote(path.encode('utf-8')) url = image.thumbnail(alias) if "://" in url: # We are getting the full path and must only encode the part after the protocol # (we assume that the hostname is ASCII) protocol, path = url.split("://") url = protocol + encoded(path) else: url = settings.BASE_URL + encoded(url) headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) img = NamedTemporaryFile(delete = True) img.write(urllib2.urlopen(req).read()) img.flush() img.seek(0) return File(img)
11b35c79ff8d2108d572929334e4e3f30c70eea5
modules/__init__.py
modules/__init__.py
import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() botconfig.DEBUG_MODE = args.debug if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = args.verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db()
import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() debug_mode = args.debug verbose = args.verbose sabotage = args.sabotage # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if setting == "DEBUG_MODE": debug_mode = value if setting == "VERBOSE_MODE": verbose = value if setting == "DEFAULT_MODULE": sabotage = value if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) botconfig.DEBUG_MODE = debug_mode if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db()
Allow debug and verbose modes to be set directly from config.
Allow debug and verbose modes to be set directly from config.
Python
bsd-2-clause
Agent-Isai/lykos,billion57/lykos,Diitto/lykos,Cr0wb4r/lykos
import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() botconfig.DEBUG_MODE = args.debug if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = args.verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db() Allow debug and verbose modes to be set directly from config.
import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() debug_mode = args.debug verbose = args.verbose sabotage = args.sabotage # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if setting == "DEBUG_MODE": debug_mode = value if setting == "VERBOSE_MODE": verbose = value if setting == "DEFAULT_MODULE": sabotage = value if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) botconfig.DEBUG_MODE = debug_mode if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db()
<commit_before>import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() botconfig.DEBUG_MODE = args.debug if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = args.verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db() <commit_msg>Allow debug and verbose modes to be set directly from config.<commit_after>
import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() debug_mode = args.debug verbose = args.verbose sabotage = args.sabotage # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if setting == "DEBUG_MODE": debug_mode = value if setting == "VERBOSE_MODE": verbose = value if setting == "DEFAULT_MODULE": sabotage = value if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) botconfig.DEBUG_MODE = debug_mode if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db()
import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() botconfig.DEBUG_MODE = args.debug if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = args.verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db() Allow debug and verbose modes to be set directly from config.import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() debug_mode = args.debug verbose = args.verbose sabotage = args.sabotage # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if setting == "DEBUG_MODE": debug_mode = value if setting == "VERBOSE_MODE": verbose = value if setting == "DEFAULT_MODULE": sabotage = value if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) botconfig.DEBUG_MODE = debug_mode if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db()
<commit_before>import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() botconfig.DEBUG_MODE = args.debug if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = args.verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db() <commit_msg>Allow debug and verbose modes to be set directly from config.<commit_after>import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() debug_mode = args.debug verbose = args.verbose sabotage = args.sabotage # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if setting == "DEBUG_MODE": debug_mode = value if setting == "VERBOSE_MODE": verbose = value if setting == "DEFAULT_MODULE": sabotage = value if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) botconfig.DEBUG_MODE = debug_mode if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db()
8fe8717b4e2afe6329d2dd25210371df3eab2b4f
test/test_stdlib.py
test/test_stdlib.py
# -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543.stdlib from .backend_tests import SimpleNegotiation class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND
# -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543 import pep543.stdlib import pytest from .backend_tests import SimpleNegotiation CONTEXTS = ( pep543.stdlib.STDLIB_BACKEND.client_context, pep543.stdlib.STDLIB_BACKEND.server_context ) def assert_wrap_fails(context, exception): """ A convenient helper that calls wrap_buffers with the appropriate number of arugments and asserts that it raises the appropriate error. """ if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): with pytest.raises(exception): context.wrap_buffers(server_hostname=None) else: with pytest.raises(exception): context.wrap_buffers() class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND class TestStdlibErrorHandling(object): """ Validate that the stdlib backend can do sensible error handling in specific situations that it cannot handle. """ @pytest.mark.parametrize( 'lowest,highest', ( (object(), None), (None, object()), (object(), object()) ) ) @pytest.mark.parametrize('context', CONTEXTS) def test_bad_values_for_versions_client(self, lowest, highest, context): """ Using TLSConfiguration objects with a bad value for their minimum version raises a TLSError with Client contexts. """ config = pep543.TLSConfiguration( validate_certificates=False, lowest_supported_version=lowest, highest_supported_version=highest ) ctx = context(config) assert_wrap_fails(ctx, pep543.TLSError)
Test that we reject bad TLS versions
Test that we reject bad TLS versions
Python
mit
python-hyper/pep543
# -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543.stdlib from .backend_tests import SimpleNegotiation class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND Test that we reject bad TLS versions
# -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543 import pep543.stdlib import pytest from .backend_tests import SimpleNegotiation CONTEXTS = ( pep543.stdlib.STDLIB_BACKEND.client_context, pep543.stdlib.STDLIB_BACKEND.server_context ) def assert_wrap_fails(context, exception): """ A convenient helper that calls wrap_buffers with the appropriate number of arugments and asserts that it raises the appropriate error. """ if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): with pytest.raises(exception): context.wrap_buffers(server_hostname=None) else: with pytest.raises(exception): context.wrap_buffers() class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND class TestStdlibErrorHandling(object): """ Validate that the stdlib backend can do sensible error handling in specific situations that it cannot handle. """ @pytest.mark.parametrize( 'lowest,highest', ( (object(), None), (None, object()), (object(), object()) ) ) @pytest.mark.parametrize('context', CONTEXTS) def test_bad_values_for_versions_client(self, lowest, highest, context): """ Using TLSConfiguration objects with a bad value for their minimum version raises a TLSError with Client contexts. """ config = pep543.TLSConfiguration( validate_certificates=False, lowest_supported_version=lowest, highest_supported_version=highest ) ctx = context(config) assert_wrap_fails(ctx, pep543.TLSError)
<commit_before># -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543.stdlib from .backend_tests import SimpleNegotiation class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND <commit_msg>Test that we reject bad TLS versions<commit_after>
# -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543 import pep543.stdlib import pytest from .backend_tests import SimpleNegotiation CONTEXTS = ( pep543.stdlib.STDLIB_BACKEND.client_context, pep543.stdlib.STDLIB_BACKEND.server_context ) def assert_wrap_fails(context, exception): """ A convenient helper that calls wrap_buffers with the appropriate number of arugments and asserts that it raises the appropriate error. """ if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): with pytest.raises(exception): context.wrap_buffers(server_hostname=None) else: with pytest.raises(exception): context.wrap_buffers() class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND class TestStdlibErrorHandling(object): """ Validate that the stdlib backend can do sensible error handling in specific situations that it cannot handle. """ @pytest.mark.parametrize( 'lowest,highest', ( (object(), None), (None, object()), (object(), object()) ) ) @pytest.mark.parametrize('context', CONTEXTS) def test_bad_values_for_versions_client(self, lowest, highest, context): """ Using TLSConfiguration objects with a bad value for their minimum version raises a TLSError with Client contexts. """ config = pep543.TLSConfiguration( validate_certificates=False, lowest_supported_version=lowest, highest_supported_version=highest ) ctx = context(config) assert_wrap_fails(ctx, pep543.TLSError)
# -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543.stdlib from .backend_tests import SimpleNegotiation class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND Test that we reject bad TLS versions# -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543 import pep543.stdlib import pytest from .backend_tests import SimpleNegotiation CONTEXTS = ( pep543.stdlib.STDLIB_BACKEND.client_context, pep543.stdlib.STDLIB_BACKEND.server_context ) def assert_wrap_fails(context, exception): """ A convenient helper that calls wrap_buffers with the appropriate number of arugments and asserts that it raises the appropriate error. """ if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): with pytest.raises(exception): context.wrap_buffers(server_hostname=None) else: with pytest.raises(exception): context.wrap_buffers() class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND class TestStdlibErrorHandling(object): """ Validate that the stdlib backend can do sensible error handling in specific situations that it cannot handle. """ @pytest.mark.parametrize( 'lowest,highest', ( (object(), None), (None, object()), (object(), object()) ) ) @pytest.mark.parametrize('context', CONTEXTS) def test_bad_values_for_versions_client(self, lowest, highest, context): """ Using TLSConfiguration objects with a bad value for their minimum version raises a TLSError with Client contexts. """ config = pep543.TLSConfiguration( validate_certificates=False, lowest_supported_version=lowest, highest_supported_version=highest ) ctx = context(config) assert_wrap_fails(ctx, pep543.TLSError)
<commit_before># -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543.stdlib from .backend_tests import SimpleNegotiation class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND <commit_msg>Test that we reject bad TLS versions<commit_after># -*- coding: utf-8 -*- """ Tests for the standard library PEP 543 shim. """ import pep543 import pep543.stdlib import pytest from .backend_tests import SimpleNegotiation CONTEXTS = ( pep543.stdlib.STDLIB_BACKEND.client_context, pep543.stdlib.STDLIB_BACKEND.server_context ) def assert_wrap_fails(context, exception): """ A convenient helper that calls wrap_buffers with the appropriate number of arugments and asserts that it raises the appropriate error. """ if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): with pytest.raises(exception): context.wrap_buffers(server_hostname=None) else: with pytest.raises(exception): context.wrap_buffers() class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND class TestStdlibErrorHandling(object): """ Validate that the stdlib backend can do sensible error handling in specific situations that it cannot handle. """ @pytest.mark.parametrize( 'lowest,highest', ( (object(), None), (None, object()), (object(), object()) ) ) @pytest.mark.parametrize('context', CONTEXTS) def test_bad_values_for_versions_client(self, lowest, highest, context): """ Using TLSConfiguration objects with a bad value for their minimum version raises a TLSError with Client contexts. """ config = pep543.TLSConfiguration( validate_certificates=False, lowest_supported_version=lowest, highest_supported_version=highest ) ctx = context(config) assert_wrap_fails(ctx, pep543.TLSError)
04608636f6e4fc004458560499338af4b871cddb
asyncio_irc/message.py
asyncio_irc/message.py
from .utils import to_bytes class Message: """A message recieved from the IRC network.""" def __init__(self, raw_message): self.raw = raw_message self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.raw.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message
from .utils import to_bytes class Message(bytes): """A message recieved from the IRC network.""" def __init__(self, raw_message_bytes_ignored): super().__init__() self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message
Make Message a subclass of bytes
Make Message a subclass of bytes
Python
bsd-2-clause
meshy/framewirc
from .utils import to_bytes class Message: """A message recieved from the IRC network.""" def __init__(self, raw_message): self.raw = raw_message self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.raw.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message Make Message a subclass of bytes
from .utils import to_bytes class Message(bytes): """A message recieved from the IRC network.""" def __init__(self, raw_message_bytes_ignored): super().__init__() self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message
<commit_before>from .utils import to_bytes class Message: """A message recieved from the IRC network.""" def __init__(self, raw_message): self.raw = raw_message self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.raw.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message <commit_msg>Make Message a subclass of bytes<commit_after>
from .utils import to_bytes class Message(bytes): """A message recieved from the IRC network.""" def __init__(self, raw_message_bytes_ignored): super().__init__() self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message
from .utils import to_bytes class Message: """A message recieved from the IRC network.""" def __init__(self, raw_message): self.raw = raw_message self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.raw.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message Make Message a subclass of bytesfrom .utils import to_bytes class Message(bytes): """A message recieved from the IRC network.""" def __init__(self, raw_message_bytes_ignored): super().__init__() self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message
<commit_before>from .utils import to_bytes class Message: """A message recieved from the IRC network.""" def __init__(self, raw_message): self.raw = raw_message self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.raw.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message <commit_msg>Make Message a subclass of bytes<commit_after>from .utils import to_bytes class Message(bytes): """A message recieved from the IRC network.""" def __init__(self, raw_message_bytes_ignored): super().__init__() self.prefix, self.command, self.params, self.suffix = self._elements() def _elements(self): """ Split the raw message into it's component parts. Adapted from http://stackoverflow.com/a/930706/400691 """ message = self.strip() prefix = b'' # Odd slicing required for bytes to avoid getting int instead of char # http://stackoverflow.com/q/28249597/400691 if message[0:1] == b':': prefix, message = message[1:].split(b' ', 1) suffix = b'' if b' :' in message: message, suffix = message.split(b' :', 1) command, *params = message.split() params = list(filter(None, params)) return prefix, command, params, suffix def message_bytes(command, prefix=b'', params=None, suffix=b''): command = to_bytes(command) prefix = to_bytes(prefix) params = list(map(to_bytes, params or [])) suffix = to_bytes(suffix) message = command if prefix: message = b':' + prefix + b' ' + message if params: params = b' '.join(params) message = message + b' ' + params if suffix: message = message + b' :' + suffix return message
729a5c2e1276f9789733fc46fb7f48d0ac7e3178
src/slackmoji.py
src/slackmoji.py
# pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs from subprocess import check_output # Third Party import requests def list_emojis(domain, token): script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)] response = check_output(script, shell=True) print "\nGot list of emojis from %s Slack domain!" % domain return response def download_emojis(emojis, folder): count = 0 makedirs(folder) emojis = json.loads(emojis)["emoji"] print "\nDownloading emojis from list..." for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count
# pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs # Third Party import requests def list_emojis(domain, token): url = r'https://%s.slack.com/api/emoji.list' % domain data = [('token', token)] response = requests.post(url, data=data) print "\nGot list of emojis from %s Slack domain!" % domain emojis = json.loads(response.text)["emoji"] return emojis def download_emojis(emojis, folder): count = 0 makedirs(folder) print "\nDownloading emojis to %s folder..." % folder for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count
Use requests to fetch emoji list
Use requests to fetch emoji list
Python
mit
le1ia/slackmoji
# pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs from subprocess import check_output # Third Party import requests def list_emojis(domain, token): script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)] response = check_output(script, shell=True) print "\nGot list of emojis from %s Slack domain!" % domain return response def download_emojis(emojis, folder): count = 0 makedirs(folder) emojis = json.loads(emojis)["emoji"] print "\nDownloading emojis from list..." for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count Use requests to fetch emoji list
# pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs # Third Party import requests def list_emojis(domain, token): url = r'https://%s.slack.com/api/emoji.list' % domain data = [('token', token)] response = requests.post(url, data=data) print "\nGot list of emojis from %s Slack domain!" % domain emojis = json.loads(response.text)["emoji"] return emojis def download_emojis(emojis, folder): count = 0 makedirs(folder) print "\nDownloading emojis to %s folder..." % folder for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count
<commit_before># pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs from subprocess import check_output # Third Party import requests def list_emojis(domain, token): script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)] response = check_output(script, shell=True) print "\nGot list of emojis from %s Slack domain!" % domain return response def download_emojis(emojis, folder): count = 0 makedirs(folder) emojis = json.loads(emojis)["emoji"] print "\nDownloading emojis from list..." for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count <commit_msg>Use requests to fetch emoji list<commit_after>
# pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs # Third Party import requests def list_emojis(domain, token): url = r'https://%s.slack.com/api/emoji.list' % domain data = [('token', token)] response = requests.post(url, data=data) print "\nGot list of emojis from %s Slack domain!" % domain emojis = json.loads(response.text)["emoji"] return emojis def download_emojis(emojis, folder): count = 0 makedirs(folder) print "\nDownloading emojis to %s folder..." % folder for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count
# pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs from subprocess import check_output # Third Party import requests def list_emojis(domain, token): script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)] response = check_output(script, shell=True) print "\nGot list of emojis from %s Slack domain!" % domain return response def download_emojis(emojis, folder): count = 0 makedirs(folder) emojis = json.loads(emojis)["emoji"] print "\nDownloading emojis from list..." for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count Use requests to fetch emoji list# pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs # Third Party import requests def list_emojis(domain, token): url = r'https://%s.slack.com/api/emoji.list' % domain data = [('token', token)] response = requests.post(url, data=data) print "\nGot list of emojis from %s Slack domain!" % domain emojis = json.loads(response.text)["emoji"] return emojis def download_emojis(emojis, folder): count = 0 makedirs(folder) print "\nDownloading emojis to %s folder..." % folder for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count
<commit_before># pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs from subprocess import check_output # Third Party import requests def list_emojis(domain, token): script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)] response = check_output(script, shell=True) print "\nGot list of emojis from %s Slack domain!" % domain return response def download_emojis(emojis, folder): count = 0 makedirs(folder) emojis = json.loads(emojis)["emoji"] print "\nDownloading emojis from list..." for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count <commit_msg>Use requests to fetch emoji list<commit_after># pylint: disable = C0103, C0111 # Standard Library import json import mimetypes from os import makedirs # Third Party import requests def list_emojis(domain, token): url = r'https://%s.slack.com/api/emoji.list' % domain data = [('token', token)] response = requests.post(url, data=data) print "\nGot list of emojis from %s Slack domain!" % domain emojis = json.loads(response.text)["emoji"] return emojis def download_emojis(emojis, folder): count = 0 makedirs(folder) print "\nDownloading emojis to %s folder..." % folder for name, url in emojis.iteritems(): if 'alias' in url: continue else: res = requests.get(url) cont = res.headers['content-type'] ext = mimetypes.guess_extension(cont) if ext == '.jpe': ext = '.jpg' output = folder + '/' + name + ext with open(output, 'wb') as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) count = count + 1 print "\nFinished downloading %s emojis!" % count
48b7880fec255c7a021361211e56980be2bd4c6b
project/creditor/management/commands/addrecurring.py
project/creditor/management/commands/addrecurring.py
# -*- coding: utf-8 -*- from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def handle(self, *args, **options): for t in RecurringTransaction.objects.all(): ret = t.conditional_add_transaction() if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
# -*- coding: utf-8 -*- import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def add_arguments(self, parser): parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') def handle(self, *args, **options): since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) if options['verbosity'] > 2: print("Processing since %s" % since_parsed.isoformat()) for t in RecurringTransaction.objects.all(): if options['verbosity'] > 2: print("Processing: %s" % t) for month in months(since_parsed, timezone.now()): if options['verbosity'] > 2: print(" month %s" % month.isoformat()) ret = t.conditional_add_transaction(month) if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
Add "since" parameter to this command
Add "since" parameter to this command Fixes #25
Python
mit
HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum
# -*- coding: utf-8 -*- from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def handle(self, *args, **options): for t in RecurringTransaction.objects.all(): ret = t.conditional_add_transaction() if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret) Add "since" parameter to this command Fixes #25
# -*- coding: utf-8 -*- import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def add_arguments(self, parser): parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') def handle(self, *args, **options): since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) if options['verbosity'] > 2: print("Processing since %s" % since_parsed.isoformat()) for t in RecurringTransaction.objects.all(): if options['verbosity'] > 2: print("Processing: %s" % t) for month in months(since_parsed, timezone.now()): if options['verbosity'] > 2: print(" month %s" % month.isoformat()) ret = t.conditional_add_transaction(month) if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
<commit_before># -*- coding: utf-8 -*- from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def handle(self, *args, **options): for t in RecurringTransaction.objects.all(): ret = t.conditional_add_transaction() if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret) <commit_msg>Add "since" parameter to this command Fixes #25<commit_after>
# -*- coding: utf-8 -*- import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def add_arguments(self, parser): parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') def handle(self, *args, **options): since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) if options['verbosity'] > 2: print("Processing since %s" % since_parsed.isoformat()) for t in RecurringTransaction.objects.all(): if options['verbosity'] > 2: print("Processing: %s" % t) for month in months(since_parsed, timezone.now()): if options['verbosity'] > 2: print(" month %s" % month.isoformat()) ret = t.conditional_add_transaction(month) if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
# -*- coding: utf-8 -*- from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def handle(self, *args, **options): for t in RecurringTransaction.objects.all(): ret = t.conditional_add_transaction() if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret) Add "since" parameter to this command Fixes #25# -*- coding: utf-8 -*- import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def add_arguments(self, parser): parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') def handle(self, *args, **options): since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) if options['verbosity'] > 2: print("Processing since %s" % since_parsed.isoformat()) for t in RecurringTransaction.objects.all(): if options['verbosity'] > 2: print("Processing: %s" % t) for month in months(since_parsed, timezone.now()): if options['verbosity'] > 2: print(" month %s" % month.isoformat()) ret = t.conditional_add_transaction(month) if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
<commit_before># -*- coding: utf-8 -*- from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def handle(self, *args, **options): for t in RecurringTransaction.objects.all(): ret = t.conditional_add_transaction() if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret) <commit_msg>Add "since" parameter to this command Fixes #25<commit_after># -*- coding: utf-8 -*- import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def add_arguments(self, parser): parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') def handle(self, *args, **options): since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) if options['verbosity'] > 2: print("Processing since %s" % since_parsed.isoformat()) for t in RecurringTransaction.objects.all(): if options['verbosity'] > 2: print("Processing: %s" % t) for month in months(since_parsed, timezone.now()): if options['verbosity'] > 2: print(" month %s" % month.isoformat()) ret = t.conditional_add_transaction(month) if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
09bdc51dacfe72597105c468baf356f0b1e81012
tests/testLabels.py
tests/testLabels.py
import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" sys.exit() #labels.create("barf", True) for l in labels: print l
import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" return #labels.create("barf", True) for l in labels: print l
Test modified a second time, to keep Travis happy.
Test modified a second time, to keep Travis happy.
Python
mit
FulcrumIT/skytap,mapledyne/skytap
import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" sys.exit() #labels.create("barf", True) for l in labels: print l Test modified a second time, to keep Travis happy.
import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" return #labels.create("barf", True) for l in labels: print l
<commit_before>import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" sys.exit() #labels.create("barf", True) for l in labels: print l <commit_msg>Test modified a second time, to keep Travis happy.<commit_after>
import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" return #labels.create("barf", True) for l in labels: print l
import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" sys.exit() #labels.create("barf", True) for l in labels: print l Test modified a second time, to keep Travis happy.import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" return #labels.create("barf", True) for l in labels: print l
<commit_before>import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" sys.exit() #labels.create("barf", True) for l in labels: print l <commit_msg>Test modified a second time, to keep Travis happy.<commit_after>import json import sys sys.path.append('..') from skytap.Labels import Labels # noqa labels = Labels() def test_labels(): """Peform tests relating to labels.""" return #labels.create("barf", True) for l in labels: print l
0f6128c3694b08899220a3e2b8d73c27cda7eeee
saleor/product/migrations/0117_auto_20200423_0737.py
saleor/product/migrations/0117_auto_20200423_0737.py
# Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0116_auto_20200225_0237'), ] operations = [ migrations.AlterField( model_name='producttranslation', name='name', field=models.CharField(max_length=250), ), ]
# Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("product", "0116_auto_20200225_0237"), ] operations = [ migrations.AlterField( model_name="producttranslation", name="name", field=models.CharField(max_length=250), ), ]
Format new migration file with black
Format new migration file with black
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
# Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0116_auto_20200225_0237'), ] operations = [ migrations.AlterField( model_name='producttranslation', name='name', field=models.CharField(max_length=250), ), ] Format new migration file with black
# Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("product", "0116_auto_20200225_0237"), ] operations = [ migrations.AlterField( model_name="producttranslation", name="name", field=models.CharField(max_length=250), ), ]
<commit_before># Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0116_auto_20200225_0237'), ] operations = [ migrations.AlterField( model_name='producttranslation', name='name', field=models.CharField(max_length=250), ), ] <commit_msg>Format new migration file with black<commit_after>
# Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("product", "0116_auto_20200225_0237"), ] operations = [ migrations.AlterField( model_name="producttranslation", name="name", field=models.CharField(max_length=250), ), ]
# Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0116_auto_20200225_0237'), ] operations = [ migrations.AlterField( model_name='producttranslation', name='name', field=models.CharField(max_length=250), ), ] Format new migration file with black# Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("product", "0116_auto_20200225_0237"), ] operations = [ migrations.AlterField( model_name="producttranslation", name="name", field=models.CharField(max_length=250), ), ]
<commit_before># Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0116_auto_20200225_0237'), ] operations = [ migrations.AlterField( model_name='producttranslation', name='name', field=models.CharField(max_length=250), ), ] <commit_msg>Format new migration file with black<commit_after># Generated by Django 3.0.5 on 2020-04-23 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("product", "0116_auto_20200225_0237"), ] operations = [ migrations.AlterField( model_name="producttranslation", name="name", field=models.CharField(max_length=250), ), ]
42c667ab7e1ed9cdfc711a4d5eb815492d8b1e05
tests/test_image.py
tests/test_image.py
# -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150)) assert os.path.isfile(dstfile)
# -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150), None) assert os.path.isfile(dstfile)
Fix a test with generate_thumbnail
Fix a test with generate_thumbnail
Python
mit
franek/sigal,jdn06/sigal,cbosdo/sigal,jasuarez/sigal,muggenhor/sigal,jdn06/sigal,kontza/sigal,franek/sigal,t-animal/sigal,t-animal/sigal,kontza/sigal,kontza/sigal,muggenhor/sigal,elaOnMars/sigal,cbosdo/sigal,jasuarez/sigal,jdn06/sigal,Ferada/sigal,saimn/sigal,saimn/sigal,cbosdo/sigal,saimn/sigal,xouillet/sigal,elaOnMars/sigal,Ferada/sigal,jasuarez/sigal,t-animal/sigal,xouillet/sigal,xouillet/sigal,Ferada/sigal
# -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150)) assert os.path.isfile(dstfile) Fix a test with generate_thumbnail
# -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150), None) assert os.path.isfile(dstfile)
<commit_before># -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150)) assert os.path.isfile(dstfile) <commit_msg>Fix a test with generate_thumbnail<commit_after>
# -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150), None) assert os.path.isfile(dstfile)
# -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150)) assert os.path.isfile(dstfile) Fix a test with generate_thumbnail# -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150), None) assert os.path.isfile(dstfile)
<commit_before># -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150)) assert os.path.isfile(dstfile) <commit_msg>Fix a test with generate_thumbnail<commit_after># -*- coding:utf-8 -*- import os from sigal.image import generate_image, generate_thumbnail CURRENT_DIR = os.path.dirname(__file__) TEST_IMAGE = 'exo20101028-b-full.jpg' def test_image(tmpdir): "Test the Image class." srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE) dstfile = str(tmpdir.join(TEST_IMAGE)) generate_thumbnail(srcfile, dstfile, (200, 150), None) assert os.path.isfile(dstfile)
ccfe12391050d598ec32861ed146b66f4e907943
noodles/entities.py
noodles/entities.py
""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] TODO: - work out a standard form to normalize company names to - import company names into the massive regex """ import re norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): return ['ABC Inc', 'Joost Ltd.'] class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] """ COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' import re import csv norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) names = [normalize(row[0]) for row in rows] return names class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
Use big company list for regex entity extraction
Use big company list for regex entity extraction
Python
mit
uf6/noodles,uf6/noodles
""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] TODO: - work out a standard form to normalize company names to - import company names into the massive regex """ import re norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): return ['ABC Inc', 'Joost Ltd.'] class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text)) Use big company list for regex entity extraction
""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] """ COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' import re import csv norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) names = [normalize(row[0]) for row in rows] return names class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
<commit_before>""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] TODO: - work out a standard form to normalize company names to - import company names into the massive regex """ import re norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): return ['ABC Inc', 'Joost Ltd.'] class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text)) <commit_msg>Use big company list for regex entity extraction<commit_after>
""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] """ COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' import re import csv norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) names = [normalize(row[0]) for row in rows] return names class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] TODO: - work out a standard form to normalize company names to - import company names into the massive regex """ import re norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): return ['ABC Inc', 'Joost Ltd.'] class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text)) Use big company list for regex entity extraction""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] """ COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' import re import csv norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) names = [normalize(row[0]) for row in rows] return names class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
<commit_before>""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] TODO: - work out a standard form to normalize company names to - import company names into the massive regex """ import re norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): return ['ABC Inc', 'Joost Ltd.'] class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text)) <commit_msg>Use big company list for regex entity extraction<commit_after>""" Find all company names in a piece of text extractor = EntityExtractor() entities = extractor.entities_from_text(text) > ['acme incorporated', 'fubar limited', ...] """ COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' import re import csv norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) names = [normalize(row[0]) for row in rows] return names class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
93e2ff0dd32a72efa90222988d4289c70bb55b98
c2corg_api/models/common/fields_book.py
c2corg_api/models/common/fields_book.py
DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS }
DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'locales.summary', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS }
Add summary to book listing
Add summary to book listing
Python
agpl-3.0
c2corg/v6_api,c2corg/v6_api,c2corg/v6_api
DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS } Add summary to book listing
DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'locales.summary', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS }
<commit_before>DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS } <commit_msg>Add summary to book listing<commit_after>
DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'locales.summary', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS }
DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS } Add summary to book listingDEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'locales.summary', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS }
<commit_before>DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS } <commit_msg>Add summary to book listing<commit_after>DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'locales.summary', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS }
4008824b7b7bf8338b057bc0b594774cb055c794
blinkylib/patterns/blinkypattern.py
blinkylib/patterns/blinkypattern.py
class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.05 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass
class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.01 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass
Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixed
Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixed
Python
mit
jonspeicher/blinkyfun
class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.05 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixed
class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.01 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass
<commit_before>class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.05 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass <commit_msg>Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixed<commit_after>
class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.01 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass
class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.05 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixedclass BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.01 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass
<commit_before>class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.05 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass <commit_msg>Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixed<commit_after>class BlinkyPattern(object): def __init__(self, blinkytape): self._blinkytape = blinkytape self._animated = False self._timebase_sec = 0.01 @property def animated(self): return self._animated @property def timebase_sec(self): return self._timebase_sec def setup(self): pass def animate(self): pass def teardown(self): pass
38845ecae177635b98a2e074355227f0c9f9834d
cartoframes/viz/widgets/__init__.py
cartoframes/viz/widgets/__init__.py
""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ]
""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget from ..widget import Widget from ..widget_list import WidgetList def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'Widget', 'WidgetList', 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ]
Add Widget and WidgetList to namespace
Add Widget and WidgetList to namespace
Python
bsd-3-clause
CartoDB/cartoframes,CartoDB/cartoframes
""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ] Add Widget and WidgetList to namespace
""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget from ..widget import Widget from ..widget_list import WidgetList def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'Widget', 'WidgetList', 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ]
<commit_before>""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ] <commit_msg>Add Widget and WidgetList to namespace<commit_after>
""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget from ..widget import Widget from ..widget_list import WidgetList def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'Widget', 'WidgetList', 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ]
""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ] Add Widget and WidgetList to namespace""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget from ..widget import Widget from ..widget_list import WidgetList def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'Widget', 'WidgetList', 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ]
<commit_before>""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ] <commit_msg>Add Widget and WidgetList to namespace<commit_after>""" Widget functions to generate widgets faster. """ from __future__ import absolute_import from .animation_widget import animation_widget from .category_widget import category_widget from .default_widget import default_widget from .formula_widget import formula_widget from .histogram_widget import histogram_widget from .time_series_widget import time_series_widget from ..widget import Widget from ..widget_list import WidgetList def _inspect(widget): import inspect lines = inspect.getsource(widget) print(lines) __all__ = [ 'Widget', 'WidgetList', 'animation_widget', 'category_widget', 'default_widget', 'formula_widget', 'histogram_widget', 'time_series_widget', ]
3640a5b1976ea6c5b21617cda11324d73071fb9f
trimwhitespace.py
trimwhitespace.py
"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'r') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: overwritefile(filepath, stripped) def overwritefile(filepath, contents): handle = open(filepath, 'w') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.')
"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'rb') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: print('FAIL: %s' % filepath) overwritefile(filepath, stripped) else: print('OK: %s' % filepath) def overwritefile(filepath, contents): handle = open(filepath, 'wb') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.')
Fix for whitespace.py so that Windows will save Unix EOLs.
Fix for whitespace.py so that Windows will save Unix EOLs.
Python
apache-2.0
GoogleCloudPlatform/datastore-ndb-python,GoogleCloudPlatform/datastore-ndb-python
"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'r') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: overwritefile(filepath, stripped) def overwritefile(filepath, contents): handle = open(filepath, 'w') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.') Fix for whitespace.py so that Windows will save Unix EOLs.
"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'rb') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: print('FAIL: %s' % filepath) overwritefile(filepath, stripped) else: print('OK: %s' % filepath) def overwritefile(filepath, contents): handle = open(filepath, 'wb') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.')
<commit_before>"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'r') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: overwritefile(filepath, stripped) def overwritefile(filepath, contents): handle = open(filepath, 'w') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.') <commit_msg>Fix for whitespace.py so that Windows will save Unix EOLs.<commit_after>
"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'rb') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: print('FAIL: %s' % filepath) overwritefile(filepath, stripped) else: print('OK: %s' % filepath) def overwritefile(filepath, contents): handle = open(filepath, 'wb') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.')
"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'r') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: overwritefile(filepath, stripped) def overwritefile(filepath, contents): handle = open(filepath, 'w') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.') Fix for whitespace.py so that Windows will save Unix EOLs."""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'rb') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: print('FAIL: %s' % filepath) overwritefile(filepath, stripped) else: print('OK: %s' % filepath) def overwritefile(filepath, contents): handle = open(filepath, 'wb') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.')
<commit_before>"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'r') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: overwritefile(filepath, stripped) def overwritefile(filepath, contents): handle = open(filepath, 'w') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.') <commit_msg>Fix for whitespace.py so that Windows will save Unix EOLs.<commit_after>"""Remove trailing whitespace from files in current path and sub directories.""" import os, glob def scanpath(path): for filepath in glob.glob(os.path.join(path, '*')): if os.path.isdir(filepath): scanpath(filepath) else: trimwhitespace(filepath) def trimwhitespace(filepath): handle = open(filepath, 'rb') stripped = '' flag = False for line in handle.readlines(): stripped_line = line.rstrip() + '\n' if line != stripped_line: flag = True stripped += stripped_line handle.close() if flag: print('FAIL: %s' % filepath) overwritefile(filepath, stripped) else: print('OK: %s' % filepath) def overwritefile(filepath, contents): handle = open(filepath, 'wb') handle.write(contents) handle.close() if __name__ == '__main__': scanpath('.')
d31d2a73127a79566651e644d105cbe2063a6e2a
webapp/publish.py
webapp/publish.py
from cloudly.pubsub import Pusher from cloudly.tweets import Tweets from cloudly.twitterstream import Streamer from webapp import config class Publisher(Pusher): def publish(self, tweets, event): """Keep only relevant fields from the given tweets.""" stripped = [] for tweet in tweets: stripped.append({ 'coordinates': tweet['coordinates'], }) super(Publisher, self).publish(stripped, event) def processor(tweet): return True def start(): # This trick of importing the current module is for RQ workers to # correctly unpickle the `processor` function. from webapp import publish pubsub = publish.Publisher.open(config.pubsub_channel) streamer = Streamer(publish.processor, pubsub=pubsub, is_queuing=True, cache_length=100) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start()
from cloudly.pubsub import Pusher from cloudly.tweets import Tweets, StreamManager, keep from webapp import config pubsub = Pusher.open(config.pubsub_channel) def processor(tweets): pubsub.publish(keep(['coordinates'], tweets), "tweets") return len(tweets) def start(): streamer = StreamManager('locate', processor, is_queuing=False) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start()
Fix for the new cloudly APi.
Fix for the new cloudly APi.
Python
mit
hdemers/webapp-template,hdemers/webapp-template,hdemers/webapp-template
from cloudly.pubsub import Pusher from cloudly.tweets import Tweets from cloudly.twitterstream import Streamer from webapp import config class Publisher(Pusher): def publish(self, tweets, event): """Keep only relevant fields from the given tweets.""" stripped = [] for tweet in tweets: stripped.append({ 'coordinates': tweet['coordinates'], }) super(Publisher, self).publish(stripped, event) def processor(tweet): return True def start(): # This trick of importing the current module is for RQ workers to # correctly unpickle the `processor` function. from webapp import publish pubsub = publish.Publisher.open(config.pubsub_channel) streamer = Streamer(publish.processor, pubsub=pubsub, is_queuing=True, cache_length=100) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start() Fix for the new cloudly APi.
from cloudly.pubsub import Pusher from cloudly.tweets import Tweets, StreamManager, keep from webapp import config pubsub = Pusher.open(config.pubsub_channel) def processor(tweets): pubsub.publish(keep(['coordinates'], tweets), "tweets") return len(tweets) def start(): streamer = StreamManager('locate', processor, is_queuing=False) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start()
<commit_before>from cloudly.pubsub import Pusher from cloudly.tweets import Tweets from cloudly.twitterstream import Streamer from webapp import config class Publisher(Pusher): def publish(self, tweets, event): """Keep only relevant fields from the given tweets.""" stripped = [] for tweet in tweets: stripped.append({ 'coordinates': tweet['coordinates'], }) super(Publisher, self).publish(stripped, event) def processor(tweet): return True def start(): # This trick of importing the current module is for RQ workers to # correctly unpickle the `processor` function. from webapp import publish pubsub = publish.Publisher.open(config.pubsub_channel) streamer = Streamer(publish.processor, pubsub=pubsub, is_queuing=True, cache_length=100) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start() <commit_msg>Fix for the new cloudly APi.<commit_after>
from cloudly.pubsub import Pusher from cloudly.tweets import Tweets, StreamManager, keep from webapp import config pubsub = Pusher.open(config.pubsub_channel) def processor(tweets): pubsub.publish(keep(['coordinates'], tweets), "tweets") return len(tweets) def start(): streamer = StreamManager('locate', processor, is_queuing=False) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start()
from cloudly.pubsub import Pusher from cloudly.tweets import Tweets from cloudly.twitterstream import Streamer from webapp import config class Publisher(Pusher): def publish(self, tweets, event): """Keep only relevant fields from the given tweets.""" stripped = [] for tweet in tweets: stripped.append({ 'coordinates': tweet['coordinates'], }) super(Publisher, self).publish(stripped, event) def processor(tweet): return True def start(): # This trick of importing the current module is for RQ workers to # correctly unpickle the `processor` function. from webapp import publish pubsub = publish.Publisher.open(config.pubsub_channel) streamer = Streamer(publish.processor, pubsub=pubsub, is_queuing=True, cache_length=100) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start() Fix for the new cloudly APi.from cloudly.pubsub import Pusher from cloudly.tweets import Tweets, StreamManager, keep from webapp import config pubsub = Pusher.open(config.pubsub_channel) def processor(tweets): pubsub.publish(keep(['coordinates'], tweets), "tweets") return len(tweets) def start(): streamer = StreamManager('locate', processor, is_queuing=False) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start()
<commit_before>from cloudly.pubsub import Pusher from cloudly.tweets import Tweets from cloudly.twitterstream import Streamer from webapp import config class Publisher(Pusher): def publish(self, tweets, event): """Keep only relevant fields from the given tweets.""" stripped = [] for tweet in tweets: stripped.append({ 'coordinates': tweet['coordinates'], }) super(Publisher, self).publish(stripped, event) def processor(tweet): return True def start(): # This trick of importing the current module is for RQ workers to # correctly unpickle the `processor` function. from webapp import publish pubsub = publish.Publisher.open(config.pubsub_channel) streamer = Streamer(publish.processor, pubsub=pubsub, is_queuing=True, cache_length=100) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start() <commit_msg>Fix for the new cloudly APi.<commit_after>from cloudly.pubsub import Pusher from cloudly.tweets import Tweets, StreamManager, keep from webapp import config pubsub = Pusher.open(config.pubsub_channel) def processor(tweets): pubsub.publish(keep(['coordinates'], tweets), "tweets") return len(tweets) def start(): streamer = StreamManager('locate', processor, is_queuing=False) tweets = Tweets() streamer.run(tweets.with_coordinates()) if __name__ == "__main__": start()
4a7b548511fa0651aa0bc526302d13947941dacc
parse_push/views.py
parse_push/views.py
from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_409_CONFLICT)
from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_200_OK)
Return status code 200 when Device instance already exists
Return status code 200 when Device instance already exists
Python
bsd-3-clause
willandskill/django-parse-push
from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_409_CONFLICT) Return status code 200 when Device instance already exists
from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_200_OK)
<commit_before>from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_409_CONFLICT) <commit_msg>Return status code 200 when Device instance already exists<commit_after>
from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_200_OK)
from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_409_CONFLICT) Return status code 200 when Device instance already existsfrom django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_200_OK)
<commit_before>from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_409_CONFLICT) <commit_msg>Return status code 200 when Device instance already exists<commit_after>from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_200_OK)
c1f5b9e3bfa96762fdbe9f4ca54b3851b38294da
test/__init__.py
test/__init__.py
import glob, os.path, sys # Add path to hiredis.so load path path = glob.glob("build/lib*/hiredis/*.so")[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite
import glob, os.path, sys version = sys.version.split(" ")[0] majorminor = version[0:3] # Add path to hiredis.so load path path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite
Add versioned path for dynamic library lookup
Add versioned path for dynamic library lookup
Python
bsd-3-clause
badboy/hiredis-py-win,charsyam/hiredis-py,badboy/hiredis-py-win,redis/hiredis-py,charsyam/hiredis-py,badboy/hiredis-py-win,redis/hiredis-py
import glob, os.path, sys # Add path to hiredis.so load path path = glob.glob("build/lib*/hiredis/*.so")[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite Add versioned path for dynamic library lookup
import glob, os.path, sys version = sys.version.split(" ")[0] majorminor = version[0:3] # Add path to hiredis.so load path path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite
<commit_before>import glob, os.path, sys # Add path to hiredis.so load path path = glob.glob("build/lib*/hiredis/*.so")[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite <commit_msg>Add versioned path for dynamic library lookup<commit_after>
import glob, os.path, sys version = sys.version.split(" ")[0] majorminor = version[0:3] # Add path to hiredis.so load path path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite
import glob, os.path, sys # Add path to hiredis.so load path path = glob.glob("build/lib*/hiredis/*.so")[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite Add versioned path for dynamic library lookupimport glob, os.path, sys version = sys.version.split(" ")[0] majorminor = version[0:3] # Add path to hiredis.so load path path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite
<commit_before>import glob, os.path, sys # Add path to hiredis.so load path path = glob.glob("build/lib*/hiredis/*.so")[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite <commit_msg>Add versioned path for dynamic library lookup<commit_after>import glob, os.path, sys version = sys.version.split(" ")[0] majorminor = version[0:3] # Add path to hiredis.so load path path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0] sys.path.insert(0, os.path.dirname(path)) from unittest import * from . import reader def tests(): suite = TestSuite() suite.addTest(makeSuite(reader.ReaderTest)) return suite
3e30737c98a4a9e890d362ba4cbbb2315163bc29
cfgov/v1/__init__.py
cfgov/v1/__init__.py
from __future__ import absolute_import # Python 2 only from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env
from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env
Remove unused Python 2 support
Remove unused Python 2 support
Python
cc0-1.0
kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh
from __future__ import absolute_import # Python 2 only from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env Remove unused Python 2 support
from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env
<commit_before>from __future__ import absolute_import # Python 2 only from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env <commit_msg>Remove unused Python 2 support<commit_after>
from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env
from __future__ import absolute_import # Python 2 only from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env Remove unused Python 2 supportfrom django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env
<commit_before>from __future__ import absolute_import # Python 2 only from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env <commit_msg>Remove unused Python 2 support<commit_after>from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from wagtail.wagtailcore.templatetags import wagtailcore_tags from wagtail.wagtailadmin.templatetags import wagtailuserbar from jinja2 import Environment from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): options.setdefault('extensions', []).append(CompressorExtension) env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'reverse': reverse, 'wagtailuserbar': wagtailuserbar.wagtailuserbar }) env.filters.update({ 'slugify': slugify, 'richtext': wagtailcore_tags.richtext }) return env
f20c0b650da2354f3008c7a0933eb32a1409fbf0
openacademy/model/openacademy_session.py
openacademy/model/openacademy_session.py
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor") course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor", domain=['|', ("instructor","=",True), ("category_id.name", "ilike", "Teacher") ]) course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
Add domain or and ilike
[REF] openacademy: Add domain or and ilike
Python
apache-2.0
KarenKawaii/openacademy-project
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor") course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees") [REF] openacademy: Add domain or and ilike
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor", domain=['|', ("instructor","=",True), ("category_id.name", "ilike", "Teacher") ]) course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
<commit_before># -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor") course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees") <commit_msg>[REF] openacademy: Add domain or and ilike<commit_after>
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor", domain=['|', ("instructor","=",True), ("category_id.name", "ilike", "Teacher") ]) course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor") course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees") [REF] openacademy: Add domain or and ilike# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor", domain=['|', ("instructor","=",True), ("category_id.name", "ilike", "Teacher") ]) course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
<commit_before># -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor") course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees") <commit_msg>[REF] openacademy: Add domain or and ilike<commit_after># -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor", domain=['|', ("instructor","=",True), ("category_id.name", "ilike", "Teacher") ]) course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
410207e4c0a091e7b4eca9cedd08f381095f50a9
pypeerassets/card_parsers.py
pypeerassets/card_parsers.py
'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 0: none_parser, 1: custom_parser, 2: once_parser, 4: multi_parser, 8: mono_parser, 16: unflushable_parser }
'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 'NONE': none_parser, 'CUSTOM': none_parser, 'ONCE': once_parser, 'MULTI': multi_parser, 'MONO': mono_parser, 'UNFLUSHABLE': unflushable_parser }
Revert "change from string to int"
Revert "change from string to int" This reverts commit a89f8f251ee95609ec4c1ea412b0aa7ec4603252.
Python
bsd-3-clause
PeerAssets/pypeerassets
'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 0: none_parser, 1: custom_parser, 2: once_parser, 4: multi_parser, 8: mono_parser, 16: unflushable_parser } Revert "change from string to int" This reverts commit a89f8f251ee95609ec4c1ea412b0aa7ec4603252.
'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 'NONE': none_parser, 'CUSTOM': none_parser, 'ONCE': once_parser, 'MULTI': multi_parser, 'MONO': mono_parser, 'UNFLUSHABLE': unflushable_parser }
<commit_before>'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 0: none_parser, 1: custom_parser, 2: once_parser, 4: multi_parser, 8: mono_parser, 16: unflushable_parser } <commit_msg>Revert "change from string to int" This reverts commit a89f8f251ee95609ec4c1ea412b0aa7ec4603252.<commit_after>
'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 'NONE': none_parser, 'CUSTOM': none_parser, 'ONCE': once_parser, 'MULTI': multi_parser, 'MONO': mono_parser, 'UNFLUSHABLE': unflushable_parser }
'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 0: none_parser, 1: custom_parser, 2: once_parser, 4: multi_parser, 8: mono_parser, 16: unflushable_parser } Revert "change from string to int" This reverts commit a89f8f251ee95609ec4c1ea412b0aa7ec4603252.'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 'NONE': none_parser, 'CUSTOM': none_parser, 'ONCE': once_parser, 'MULTI': multi_parser, 'MONO': mono_parser, 'UNFLUSHABLE': unflushable_parser }
<commit_before>'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 0: none_parser, 1: custom_parser, 2: once_parser, 4: multi_parser, 8: mono_parser, 16: unflushable_parser } <commit_msg>Revert "change from string to int" This reverts commit a89f8f251ee95609ec4c1ea412b0aa7ec4603252.<commit_after>'''parse cards according to deck issue mode''' from .pautils import exponent_to_amount def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards) def once_parser(cards): '''parser for ONCE [2] issue mode''' return [next(i for i in cards if i.type == "CardIssue")] def multi_parser(cards): '''parser for MULTI [4] issue mode''' return cards def mono_parser(cards): '''parser for MONO [8] issue mode''' return [i for i in cards if i.type == "CardIssue" and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1] def unflushable_parser(cards): '''parser for UNFLUSHABLE [16] issue mode''' return [i for i in cards if i.type == "CardIssue"] parsers = { 'NONE': none_parser, 'CUSTOM': none_parser, 'ONCE': once_parser, 'MULTI': multi_parser, 'MONO': mono_parser, 'UNFLUSHABLE': unflushable_parser }
8ca30840b5477239625c93f4799f266f0a971e3d
raco/datalog/datalog_test.py
raco/datalog/datalog_test.py
import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( "", dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected)
import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( query, dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected)
Add query to json output in json generation test
Add query to json output in json generation test
Python
bsd-3-clause
uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco
import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( "", dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected) Add query to json output in json generation test
import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( query, dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected)
<commit_before>import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( "", dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected) <commit_msg>Add query to json output in json generation test<commit_after>
import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( query, dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected)
import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( "", dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected) Add query to json output in json generation testimport unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( query, dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected)
<commit_before>import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( "", dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected) <commit_msg>Add query to json output in json generation test<commit_after>import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( query, dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected)
b8f33283014854bfa2d92896e2061bf17de00836
pygypsy/__init__.py
pygypsy/__init__.py
"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg')
"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions import pygypsy.basal_area_increment __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') __all__ = ['basal_area_increment']
Revert "Try not importing basal_area_increment to init"
Revert "Try not importing basal_area_increment to init" This reverts commit 30f9d5367085285a3100d7ec5d6a9e07734c5ccd.
Python
mit
tesera/pygypsy,tesera/pygypsy
"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') Revert "Try not importing basal_area_increment to init" This reverts commit 30f9d5367085285a3100d7ec5d6a9e07734c5ccd.
"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions import pygypsy.basal_area_increment __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') __all__ = ['basal_area_increment']
<commit_before>"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') <commit_msg>Revert "Try not importing basal_area_increment to init" This reverts commit 30f9d5367085285a3100d7ec5d6a9e07734c5ccd.<commit_after>
"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions import pygypsy.basal_area_increment __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') __all__ = ['basal_area_increment']
"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') Revert "Try not importing basal_area_increment to init" This reverts commit 30f9d5367085285a3100d7ec5d6a9e07734c5ccd."""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions import pygypsy.basal_area_increment __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') __all__ = ['basal_area_increment']
<commit_before>"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') <commit_msg>Revert "Try not importing basal_area_increment to init" This reverts commit 30f9d5367085285a3100d7ec5d6a9e07734c5ccd.<commit_after>"""pygypsy Based on Hueng et all (2009) Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system (GYPSY) for natural and post-harvest stands in Alberta. Forestry Division, Alberta Sustainable Resource Development, 25. Important Acronyms: aw = white aspen sb = black spruce sw = white spruce pl = logdepole pine bhage = Breast Height Age tage = Total age si_<xx> = estimated site index for species <xx> y2bh = years until breast height age can be measured """ import os import matplotlib from ._version import get_versions import pygypsy.basal_area_increment __version__ = get_versions()['version'] del get_versions # Force matplotlib to not use any Xwindows backend so that headless docker works matplotlib.use('Agg') __all__ = ['basal_area_increment']
72ce164a461987f7b9d35ac9a2b3a36386b7f8c9
ui/Interactor.py
ui/Interactor.py
""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = []
""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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
""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = [] Add possibility of passing priority for adding an observer
""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = []
<commit_before>""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = [] <commit_msg>Add possibility of passing priority for adding an observer<commit_after>
""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = []
""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = [] Add possibility of passing priority for adding an observer""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = []
<commit_before>""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = [] <commit_msg>Add possibility of passing priority for adding an observer<commit_after>""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ 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 = []
e85fcd553756eab32cedca214c9b8b86ff48f8b8
app/forms/vacancy.py
app/forms/vacancy.py
from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload'), validators=[InputRequired( message=_('Workload is required.'))]) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit'))
from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload')) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit'))
Make workload optional when editing vacancies
Make workload optional when editing vacancies
Python
mit
viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct
from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload'), validators=[InputRequired( message=_('Workload is required.'))]) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit')) Make workload optional when editing vacancies
from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload')) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit'))
<commit_before>from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload'), validators=[InputRequired( message=_('Workload is required.'))]) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit')) <commit_msg>Make workload optional when editing vacancies<commit_after>
from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload')) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit'))
from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload'), validators=[InputRequired( message=_('Workload is required.'))]) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit')) Make workload optional when editing vacanciesfrom flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload')) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit'))
<commit_before>from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload'), validators=[InputRequired( message=_('Workload is required.'))]) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit')) <commit_msg>Make workload optional when editing vacancies<commit_after>from flask_wtf import Form from flask_babel import lazy_gettext as _ # noqa from wtforms import StringField, SubmitField, TextAreaField, \ DateField, SelectField from wtforms.validators import InputRequired class VacancyForm(Form): title = StringField(_('Title'), validators=[InputRequired( message=_('A title is required.'))]) description = TextAreaField(_('Description'), validators=[InputRequired( message=_('A description is required.'))]) start_date = DateField(_('Start date'), validators=[InputRequired( message=_('Start date is required.'))]) end_date = DateField(_('End date'), validators=[InputRequired( message=_('End date is required.'))]) contract_of_service = SelectField(_('Contract'), choices=[('voltijd', _('Voltijd')), ('deeltijd', _('Deeltijd')), ('bijbaan', _('Bijbaan')), ('stage', _('Stage'))]) workload = StringField(_('Workload')) company_id = SelectField(_('Company'), coerce=int) submit = SubmitField(_('Submit'))
2627c2c5ea6fdbff9d9979765deee8740a11c7c9
backend/globaleaks/handlers/__init__.py
backend/globaleaks/handlers/__init__.py
# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'css', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip']
# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip']
Fix module packaging thanks to landscape.io hint
Fix module packaging thanks to landscape.io hint
Python
agpl-3.0
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'css', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip'] Fix module packaging thanks to landscape.io hint
# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip']
<commit_before># -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'css', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip'] <commit_msg>Fix module packaging thanks to landscape.io hint<commit_after>
# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip']
# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'css', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip'] Fix module packaging thanks to landscape.io hint# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip']
<commit_before># -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'css', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip'] <commit_msg>Fix module packaging thanks to landscape.io hint<commit_after># -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip']
6728bf1fecef3ac1aea9489e7c74333ad0a3b552
datalogger/__main__.py
datalogger/__main__.py
import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full()
import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() #w.CurrentWorkspace.path = "//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/" # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") #w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full()
Comment out audo-discovery of addons
Comment out audo-discovery of addons
Python
bsd-3-clause
torebutlin/cued_datalogger
import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full() Comment out audo-discovery of addons
import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() #w.CurrentWorkspace.path = "//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/" # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") #w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full()
<commit_before>import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full() <commit_msg>Comment out audo-discovery of addons<commit_after>
import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() #w.CurrentWorkspace.path = "//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/" # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") #w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full()
import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full() Comment out audo-discovery of addonsimport sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() #w.CurrentWorkspace.path = "//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/" # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") #w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full()
<commit_before>import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full() <commit_msg>Comment out audo-discovery of addons<commit_after>import sys from PyQt5.QtWidgets import QApplication from datalogger.bin.workspace import Workspace from datalogger.analysis_window_testing import AnalysisWindow def full(): app = 0 app = QApplication(sys.argv) # Create the window w = AnalysisWindow() w.CurrentWorkspace = Workspace() #w.CurrentWorkspace.path = "//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/" # Load the workspace #CurrentWorkspace.load("//cued-fs/users/general/tab53/ts-home/Documents/urop/Logger 2017/cued_datalogger/tests/test_workspace.wsp") #w.addon_widget.discover_addons(w.CurrentWorkspace.path + "addons/") # Run the program w.show() sys.exit(app.exec_()) if __name__ == '__main__': full()
a5faeb16a599b4260f32741846607dd05f10bc53
myproject/myproject/project_settings.py
myproject/myproject/project_settings.py
# Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import sys if 'runserver' in sys.argv: from local_settings import * else: from production_settings import *
# Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import os import sys if 'PRODUCTION' in os.environ and os.environ['PRODUCTION'].lower() in [True, 'y', 'yes', '1',]: from production_settings import * elif 'runserver' in sys.argv: from local_settings import * else: from production_settings import *
Add ability to specify which settings are used via `export PRODUCTION=0'
Add ability to specify which settings are used via `export PRODUCTION=0'
Python
unlicense
django-settings/django-settings
# Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import sys if 'runserver' in sys.argv: from local_settings import * else: from production_settings import * Add ability to specify which settings are used via `export PRODUCTION=0'
# Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import os import sys if 'PRODUCTION' in os.environ and os.environ['PRODUCTION'].lower() in [True, 'y', 'yes', '1',]: from production_settings import * elif 'runserver' in sys.argv: from local_settings import * else: from production_settings import *
<commit_before># Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import sys if 'runserver' in sys.argv: from local_settings import * else: from production_settings import * <commit_msg>Add ability to specify which settings are used via `export PRODUCTION=0'<commit_after>
# Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import os import sys if 'PRODUCTION' in os.environ and os.environ['PRODUCTION'].lower() in [True, 'y', 'yes', '1',]: from production_settings import * elif 'runserver' in sys.argv: from local_settings import * else: from production_settings import *
# Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import sys if 'runserver' in sys.argv: from local_settings import * else: from production_settings import * Add ability to specify which settings are used via `export PRODUCTION=0'# Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import os import sys if 'PRODUCTION' in os.environ and os.environ['PRODUCTION'].lower() in [True, 'y', 'yes', '1',]: from production_settings import * elif 'runserver' in sys.argv: from local_settings import * else: from production_settings import *
<commit_before># Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import sys if 'runserver' in sys.argv: from local_settings import * else: from production_settings import * <commit_msg>Add ability to specify which settings are used via `export PRODUCTION=0'<commit_after># Project Settings - Settings that don't exist in settings.py that you want to # add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER, # CELERYD_PREFETCH_MULTIPLIER, etc.) #USE_THOUSAND_SEPARATOR = True #GRAPPELLI_ADMIN_TITLE = '' #import djcelery #djcelery.setup_loader() #CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' #CELERYD_PREFETCH_MULTIPLIER = 1 import os import sys if 'PRODUCTION' in os.environ and os.environ['PRODUCTION'].lower() in [True, 'y', 'yes', '1',]: from production_settings import * elif 'runserver' in sys.argv: from local_settings import * else: from production_settings import *
794596fd6f55806eecca1c54e155533590108eee
openspending/lib/unicode_dict_reader.py
openspending/lib/unicode_dict_reader.py
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, file_or_str, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(file_or_str, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, fp, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(fp, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader
Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader
Python
agpl-3.0
CivicVision/datahub,nathanhilbert/FPA_Core,USStateDept/FPA_Core,johnjohndoe/spendb,openspending/spendb,spendb/spendb,CivicVision/datahub,pudo/spendb,CivicVision/datahub,nathanhilbert/FPA_Core,pudo/spendb,openspending/spendb,johnjohndoe/spendb,spendb/spendb,nathanhilbert/FPA_Core,openspending/spendb,johnjohndoe/spendb,spendb/spendb,USStateDept/FPA_Core,pudo/spendb,USStateDept/FPA_Core
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, file_or_str, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(file_or_str, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding) Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, fp, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(fp, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
<commit_before># work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, file_or_str, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(file_or_str, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding) <commit_msg>Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader<commit_after>
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, fp, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(fp, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, file_or_str, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(file_or_str, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding) Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, fp, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(fp, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
<commit_before># work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, file_or_str, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(file_or_str, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding) <commit_msg>Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader<commit_after># work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, fp, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(fp, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
207d4c71fbc40dd30c0099769d6f12fcb63f826e
tests/test_utils.py
tests/test_utils.py
import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out
import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info pytest_plugins = 'pytester', f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) else: testdir.tmpdir.join('.hg', 'hgrc').write(""" [ui] username = you <you@example.com> """) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out
Add missing username conf for mercurial.
Add missing username conf for mercurial.
Python
bsd-2-clause
thedrow/pytest-benchmark,SectorLabs/pytest-benchmark,ionelmc/pytest-benchmark,aldanor/pytest-benchmark
import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out Add missing username conf for mercurial.
import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info pytest_plugins = 'pytester', f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) else: testdir.tmpdir.join('.hg', 'hgrc').write(""" [ui] username = you <you@example.com> """) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out
<commit_before>import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out <commit_msg>Add missing username conf for mercurial.<commit_after>
import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info pytest_plugins = 'pytester', f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) else: testdir.tmpdir.join('.hg', 'hgrc').write(""" [ui] username = you <you@example.com> """) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out
import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out Add missing username conf for mercurial.import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info pytest_plugins = 'pytester', f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) else: testdir.tmpdir.join('.hg', 'hgrc').write(""" [ui] username = you <you@example.com> """) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out
<commit_before>import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out <commit_msg>Add missing username conf for mercurial.<commit_after>import subprocess from pytest import mark from pytest_benchmark.utils import clonefunc, get_commit_info pytest_plugins = 'pytester', f1 = lambda a: a def f2(a): return a @mark.parametrize('f', [f1, f2]) def test_clonefunc(f): assert clonefunc(f)(1) == f(1) assert clonefunc(f)(1) == f(1) def test_clonefunc_not_function(): assert clonefunc(1) == 1 @mark.parametrize('scm', ['git', 'hg']) def test_get_commit_info(scm, testdir): subprocess.check_call([scm, 'init', '.']) if scm == 'git': subprocess.check_call('git config user.email you@example.com'.split()) subprocess.check_call('git config user.name you'.split()) else: testdir.tmpdir.join('.hg', 'hgrc').write(""" [ui] username = you <you@example.com> """) testdir.makepyfile('asdf') subprocess.check_call([scm, 'add', 'test_get_commit_info.py']) subprocess.check_call([scm, 'commit', '-m', 'asdf']) out = get_commit_info() assert out.get('dirty') == False assert 'id' in out testdir.makepyfile('sadf') out = get_commit_info() assert out.get('dirty') == True assert 'id' in out
967cf8774a5033f310ca69e7ad86fc79b2628882
infrastructure/aws/trigger-provision.py
infrastructure/aws/trigger-provision.py
# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [] } client.run_instances(MinCount=1, MaxCount=1, **launch_spec)
# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [], 'TagSpecifications': [{ 'ResourceType': 'instance', 'Tags': [{ 'Key': 'provisioner', 'Value': sys.argv[1], }], }], } client.run_instances(MinCount=1, MaxCount=1, **launch_spec)
Tag provisioning instances to make them easier to identify
Tag provisioning instances to make them easier to identify
Python
mpl-2.0
bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox
# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [] } client.run_instances(MinCount=1, MaxCount=1, **launch_spec) Tag provisioning instances to make them easier to identify
# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [], 'TagSpecifications': [{ 'ResourceType': 'instance', 'Tags': [{ 'Key': 'provisioner', 'Value': sys.argv[1], }], }], } client.run_instances(MinCount=1, MaxCount=1, **launch_spec)
<commit_before># trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [] } client.run_instances(MinCount=1, MaxCount=1, **launch_spec) <commit_msg>Tag provisioning instances to make them easier to identify<commit_after>
# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [], 'TagSpecifications': [{ 'ResourceType': 'instance', 'Tags': [{ 'Key': 'provisioner', 'Value': sys.argv[1], }], }], } client.run_instances(MinCount=1, MaxCount=1, **launch_spec)
# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [] } client.run_instances(MinCount=1, MaxCount=1, **launch_spec) Tag provisioning instances to make them easier to identify# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [], 'TagSpecifications': [{ 'ResourceType': 'instance', 'Tags': [{ 'Key': 'provisioner', 'Value': sys.argv[1], }], }], } client.run_instances(MinCount=1, MaxCount=1, **launch_spec)
<commit_before># trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [] } client.run_instances(MinCount=1, MaxCount=1, **launch_spec) <commit_msg>Tag provisioning instances to make them easier to identify<commit_after># trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [], 'TagSpecifications': [{ 'ResourceType': 'instance', 'Tags': [{ 'Key': 'provisioner', 'Value': sys.argv[1], }], }], } client.run_instances(MinCount=1, MaxCount=1, **launch_spec)
2f31af1ea22e0bfefe2042f8d2ba5ad6ce365116
RG/drivers/s3/secrets.py
RG/drivers/s3/secrets.py
#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "AKIAI2TRFQV2HZIHUD4A", "AWS_SECRET_ACCESS_KEY": "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" }
#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "XXX", "AWS_SECRET_ACCESS_KEY": "XXX" }
Clear S3 API key from code
Clear S3 API key from code
Python
apache-2.0
jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate
#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "AKIAI2TRFQV2HZIHUD4A", "AWS_SECRET_ACCESS_KEY": "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" } Clear S3 API key from code
#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "XXX", "AWS_SECRET_ACCESS_KEY": "XXX" }
<commit_before>#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "AKIAI2TRFQV2HZIHUD4A", "AWS_SECRET_ACCESS_KEY": "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" } <commit_msg>Clear S3 API key from code<commit_after>
#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "XXX", "AWS_SECRET_ACCESS_KEY": "XXX" }
#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "AKIAI2TRFQV2HZIHUD4A", "AWS_SECRET_ACCESS_KEY": "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" } Clear S3 API key from code#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "XXX", "AWS_SECRET_ACCESS_KEY": "XXX" }
<commit_before>#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "AKIAI2TRFQV2HZIHUD4A", "AWS_SECRET_ACCESS_KEY": "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" } <commit_msg>Clear S3 API key from code<commit_after>#!/usr/bin/python SECRETS = { "AWS_ACCESS_KEY_ID": "XXX", "AWS_SECRET_ACCESS_KEY": "XXX" }
f63a174dd35731b6737e4f653139d92bd2f57aef
lab/hookspec.py
lab/hookspec.py
import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """
import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_location_destroyed(config, location): """Called when a location is released by the environment manager. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """
Add a location destroyed hook
Add a location destroyed hook
Python
mpl-2.0
sangoma/pytestlab
import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """ Add a location destroyed hook
import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_location_destroyed(config, location): """Called when a location is released by the environment manager. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """
<commit_before>import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """ <commit_msg>Add a location destroyed hook<commit_after>
import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_location_destroyed(config, location): """Called when a location is released by the environment manager. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """
import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """ Add a location destroyed hookimport pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_location_destroyed(config, location): """Called when a location is released by the environment manager. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """
<commit_before>import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """ <commit_msg>Add a location destroyed hook<commit_after>import pytest @pytest.hookspec def pytest_lab_configure(envmanager): """pytestlab startup""" @pytest.hookspec(historic=True) def pytest_lab_addroles(config, rolemanager): """new role registered""" # TODO: Hook for publishing new role **should not** be historic - this # no longer makes sense. Roles can now disappear before the historic # hook can be triggered. Any plugin that cares about having a complete # canonical list of roles should talk directly to the role manager # instead. @pytest.hookspec(historic=True) def pytest_lab_role_created(config, ctl): """Called when a new role controller is created (and loaded) at a location. """ @pytest.hookspec def pytest_lab_role_destroyed(config, ctl): """Called when a role controller is destroyed. """ @pytest.hookspec def pytest_lab_location_destroyed(config, location): """Called when a location is released by the environment manager. """ @pytest.hookspec def pytest_lab_add_providers(config, providermanager): """Called to enable adding addtional/external environment providers. """
fbe7b34c575e30114c54587952c9aa919bc28d81
south/introspection_plugins/__init__.py
south/introspection_plugins/__init__.py
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions import south.introspection_plugins.annoying_autoonetoone
Add import of django-annoying patch
Add import of django-annoying patch
Python
apache-2.0
theatlantic/django-south,theatlantic/django-south
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions Add import of django-annoying patch
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions import south.introspection_plugins.annoying_autoonetoone
<commit_before># This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions <commit_msg>Add import of django-annoying patch<commit_after>
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions import south.introspection_plugins.annoying_autoonetoone
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions Add import of django-annoying patch# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions import south.introspection_plugins.annoying_autoonetoone
<commit_before># This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions <commit_msg>Add import of django-annoying patch<commit_after># This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions import south.introspection_plugins.annoying_autoonetoone
0d8585a2ab57ca4d8f3f4ee2429a2137f2045c6a
bumblebee/modules/arch-update.py
bumblebee/modules/arch-update.py
"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return '0' def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100)
"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return 0 def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100)
Return 0 as an int rather than a string.
Return 0 as an int rather than a string. This was causing an ocassional crash in bumblebee/engine.py threshold_state when checkupdates fails, perhaps due to wifi not being up yet. For me this showed up regularly on login.
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return '0' def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100) Return 0 as an int rather than a string. This was causing an ocassional crash in bumblebee/engine.py threshold_state when checkupdates fails, perhaps due to wifi not being up yet. For me this showed up regularly on login.
"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return 0 def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100)
<commit_before>"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return '0' def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100) <commit_msg>Return 0 as an int rather than a string. This was causing an ocassional crash in bumblebee/engine.py threshold_state when checkupdates fails, perhaps due to wifi not being up yet. For me this showed up regularly on login.<commit_after>
"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return 0 def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100)
"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return '0' def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100) Return 0 as an int rather than a string. This was causing an ocassional crash in bumblebee/engine.py threshold_state when checkupdates fails, perhaps due to wifi not being up yet. For me this showed up regularly on login."""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return 0 def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100)
<commit_before>"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return '0' def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100) <commit_msg>Return 0 as an int rather than a string. This was causing an ocassional crash in bumblebee/engine.py threshold_state when checkupdates fails, perhaps due to wifi not being up yet. For me this showed up regularly on login.<commit_after>"""Check updates to Arch Linux.""" import subprocess import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): widget = bumblebee.output.Widget(full_text=self.utilization) super(Module, self).__init__(engine, config, widget) self.packages = self.check_updates() def check_updates(self): p = subprocess.Popen( "checkupdates", stdout=subprocess.PIPE, shell=True) p_status = p.wait() if p_status == 0: (output, err) = p.communicate() output = output.decode('utf-8') packages = output.split('\n') packages.pop() return len(packages) return 0 def utilization(self, widget): return 'Update Arch: {}'.format(self.packages) def hidden(self): return self.check_updates() == 0 def update(self, widgets): self.packages = self.check_updates() def state(self, widget): return self.threshold_state(self.packages, 1, 100)
21b405f1968dd75a663b253feb19d730af34d380
docker-entrypoint.py
docker-entrypoint.py
#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")
#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) # str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")
Revert to old entry point.
Revert to old entry point.
Python
mit
danmcp/pman,FNNDSC/pman,danmcp/pman,FNNDSC/pman
#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")Revert to old entry point.
#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) # str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")
<commit_before>#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")<commit_msg>Revert to old entry point.<commit_after>
#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) # str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")
#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")Revert to old entry point.#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) # str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")
<commit_before>#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")<commit_msg>Revert to old entry point.<commit_after>#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) # str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")
9ff63d002293da44871307960d5b439b5e6ba48f
app/commands/help.py
app/commands/help.py
def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#128161; light controls<br> <b>lights on <i>color</i></b>: I will shine with the specified <i>color</i> (red, green, blue)<br> <b>lights off</b>: I will stop shining!<br><br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True }
def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True }
Remove 'lights' command for a while
Remove 'lights' command for a while
Python
mit
alwye/spark-pi,alwye/spark-pi
def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#128161; light controls<br> <b>lights on <i>color</i></b>: I will shine with the specified <i>color</i> (red, green, blue)<br> <b>lights off</b>: I will stop shining!<br><br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True } Remove 'lights' command for a while
def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True }
<commit_before>def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#128161; light controls<br> <b>lights on <i>color</i></b>: I will shine with the specified <i>color</i> (red, green, blue)<br> <b>lights off</b>: I will stop shining!<br><br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True } <commit_msg>Remove 'lights' command for a while<commit_after>
def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True }
def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#128161; light controls<br> <b>lights on <i>color</i></b>: I will shine with the specified <i>color</i> (red, green, blue)<br> <b>lights off</b>: I will stop shining!<br><br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True } Remove 'lights' command for a whiledef proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True }
<commit_before>def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#128161; light controls<br> <b>lights on <i>color</i></b>: I will shine with the specified <i>color</i> (red, green, blue)<br> <b>lights off</b>: I will stop shining!<br><br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True } <commit_msg>Remove 'lights' command for a while<commit_after>def proc(command, message): return { "data": { "status": "ok", "html": """ <p> Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br> &#128247; camera controls<br> <b>camera photo</b>: I will take a photo and send it back<br> &#9881; subscription to events<br> <b>event subscribe security</b>: if I detect motion, I'll send you a photo<br> <b>event unsubscribe security</b>: I will stop sending photos<br> </p> """ }, "response_required": True }
0a6b43f2202cb63aad18c119d7d46916b4d54873
examples/site-api.py
examples/site-api.py
#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/index.html') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever()
#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever()
Make it easier to load the initial page
Make it easier to load the initial page
Python
bsd-3-clause
chadnickbok/librtcdcpp,chadnickbok/librtcdcpp
#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/index.html') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever() Make it easier to load the initial page
#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever()
<commit_before>#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/index.html') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever() <commit_msg>Make it easier to load the initial page<commit_after>
#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever()
#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/index.html') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever() Make it easier to load the initial page#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever()
<commit_before>#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/index.html') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever() <commit_msg>Make it easier to load the initial page<commit_after>#!/usr/bin/env python # Sets up a basic site that can allow two browsers to connect to each # other via WebRTC DataChannels, sending connection events via WebSockets. from flask import Flask, send_from_directory from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) channels = {} @sockets.route('/channel/<name>') def channel_socket(ws, name): if name in channels: channels[name].append(ws) else: channels[name] = [ws] while not ws.closed: message = ws.receive() print "Got msg:", message if message is None: continue for other_ws in channels[name]: if ws is not other_ws: other_ws.send(message) channels[name].remove(ws) for other_ws in channels[name]: other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}})) @app.route('/static/<path:path>') def send_static(path): return app.send_from_directory('static', path) @app.route('/') def serve_site(): return app.send_static_file("index.html") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever()
dae9d7d67aaf2ab8d39b232d243d860d9597bbd2
django_excel_tools/exceptions.py
django_excel_tools/exceptions.py
class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass
class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass class SerializerConfigError(BaseExcelError): pass
Add error when serializer setup has error
Add error when serializer setup has error
Python
mit
NorakGithub/django-excel-tools
class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass Add error when serializer setup has error
class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass class SerializerConfigError(BaseExcelError): pass
<commit_before>class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass <commit_msg>Add error when serializer setup has error<commit_after>
class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass class SerializerConfigError(BaseExcelError): pass
class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass Add error when serializer setup has errorclass BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass class SerializerConfigError(BaseExcelError): pass
<commit_before>class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass <commit_msg>Add error when serializer setup has error<commit_after>class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass class SerializerConfigError(BaseExcelError): pass
2e6f0934c67baf27cdf3930d48d6b733995e413f
benchmark/_interfaces.py
benchmark/_interfaces.py
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the *latest* results to return. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the results to return. The results are sorted by their timestamp in descending order. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """
Make the query docstring a bit clearer
Make the query docstring a bit clearer
Python
apache-2.0
ClusterHQ/benchmark-server,ClusterHQ/benchmark-server
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the *latest* results to return. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """ Make the query docstring a bit clearer
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the results to return. The results are sorted by their timestamp in descending order. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """
<commit_before># Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the *latest* results to return. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """ <commit_msg>Make the query docstring a bit clearer<commit_after>
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the results to return. The results are sorted by their timestamp in descending order. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the *latest* results to return. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """ Make the query docstring a bit clearer# Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the results to return. The results are sorted by their timestamp in descending order. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """
<commit_before># Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the *latest* results to return. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """ <commit_msg>Make the query docstring a bit clearer<commit_after># Copyright ClusterHQ Inc. See LICENSE file for details. """ Interfaces for the benchmarking results server. """ from zope.interface import Interface class IBackend(Interface): """ A backend for storing and querying the results. """ def store(result): """ Store a single benchmarking result. :param dict result: The result in the JSON compatible format. :return: A Deferred that produces an identifier for the stored result. """ def retrieve(id): """ Retrieve a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires with the result in the JSON format. """ def query(filter, limit): """ Retrieve previously stored results that match the given filter. The returned results will have the same values as specified in the filter for the fields that are specified in the filter. :param dict filter: The filter in the JSON compatible format. :param int limit: The number of the results to return. The results are sorted by their timestamp in descending order. :return: A Deferred that fires with a list of the results in the JSON compatible format. """ def delete(id): """ Delete a previously stored result by its identifier. :param id: The identifier of the result. :return: A Deferred that fires when the result is removed. """
b2befc496741a904f8988b2ec8fa5b57aba96a91
bin/deploy/giles_conf.py
bin/deploy/giles_conf.py
import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close()
import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(sample_path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close()
Fix the path to read the sample file from
Fix the path to read the sample file from Gah! so annoying!
Python
bsd-3-clause
e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server
import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close() Fix the path to read the sample file from Gah! so annoying!
import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(sample_path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close()
<commit_before>import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close() <commit_msg>Fix the path to read the sample file from Gah! so annoying!<commit_after>
import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(sample_path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close()
import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close() Fix the path to read the sample file from Gah! so annoying!import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(sample_path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close()
<commit_before>import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close() <commit_msg>Fix the path to read the sample file from Gah! so annoying!<commit_after>import json sample_path = "conf/net/int_service/giles_conf.json.sample" f = open(sample_path, "r") data = json.loads(f.read()) f.close() real_path = "conf/net/int_service/giles_conf.json" data['giles_base_url'] = 'http://50.17.111.19:8079' f = open(real_path, "w") f.write(json.dumps(data)) f.close()
0039eefbfa546f24b3f10031e664341d60e4055c
ranger/commands.py
ranger/commands.py
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file)
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file)
Use previews in ranger fzf
Use previews in ranger fzf
Python
mit
darthdeus/dotfiles,darthdeus/dotfiles,darthdeus/dotfiles,darthdeus/dotfiles
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file) Use previews in ranger fzf
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file)
<commit_before>from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file) <commit_msg>Use previews in ranger fzf<commit_after>
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file)
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file) Use previews in ranger fzffrom ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file)
<commit_before>from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file) <commit_msg>Use previews in ranger fzf<commit_after>from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file)
f5e8bfaf5c4f7a2131fbe0ffd0f8d14a316b907e
camoco/Exceptions.py
camoco/Exceptions.py
# Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) )
# Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) class CamocoInteractive(CamocoError): def __init__(self,expr=None,message='',*args): self.expr = expr self.message = 'Camoco interactive ipython session.'
Add exception for cli command line to run interactively.
Add exception for cli command line to run interactively.
Python
mit
schae234/Camoco,schae234/Camoco
# Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) Add exception for cli command line to run interactively.
# Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) class CamocoInteractive(CamocoError): def __init__(self,expr=None,message='',*args): self.expr = expr self.message = 'Camoco interactive ipython session.'
<commit_before># Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) <commit_msg>Add exception for cli command line to run interactively.<commit_after>
# Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) class CamocoInteractive(CamocoError): def __init__(self,expr=None,message='',*args): self.expr = expr self.message = 'Camoco interactive ipython session.'
# Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) Add exception for cli command line to run interactively.# Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) class CamocoInteractive(CamocoError): def __init__(self,expr=None,message='',*args): self.expr = expr self.message = 'Camoco interactive ipython session.'
<commit_before># Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) <commit_msg>Add exception for cli command line to run interactively.<commit_after># Exception abstract class class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) class CamocoInteractive(CamocoError): def __init__(self,expr=None,message='',*args): self.expr = expr self.message = 'Camoco interactive ipython session.'
5da928fd9b08aeb0028b71535413159da18393b4
comics/sets/forms.py
comics/sets/forms.py
import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set
import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.filter(active=True), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set
Exclude inactive comics from sets editing, effectively throwing them out of the set when saved
Exclude inactive comics from sets editing, effectively throwing them out of the set when saved
Python
agpl-3.0
datagutten/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,datagutten/comics
import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set Exclude inactive comics from sets editing, effectively throwing them out of the set when saved
import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.filter(active=True), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set
<commit_before>import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set <commit_msg>Exclude inactive comics from sets editing, effectively throwing them out of the set when saved<commit_after>
import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.filter(active=True), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set
import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set Exclude inactive comics from sets editing, effectively throwing them out of the set when savedimport datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.filter(active=True), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set
<commit_before>import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set <commit_msg>Exclude inactive comics from sets editing, effectively throwing them out of the set when saved<commit_after>import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.filter(active=True), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set
5425e10a39ce66d3c50e730d1e7b7878e8e88eb0
dmoj/executors/PHP7.py
dmoj/executors/PHP7.py
from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$'] initialize = Executor.initialize
from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$'] initialize = Executor.initialize
Allow /dev/urandom for PHP 7
Allow /dev/urandom for PHP 7
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$'] initialize = Executor.initialize Allow /dev/urandom for PHP 7
from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$'] initialize = Executor.initialize
<commit_before>from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$'] initialize = Executor.initialize <commit_msg>Allow /dev/urandom for PHP 7<commit_after>
from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$'] initialize = Executor.initialize
from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$'] initialize = Executor.initialize Allow /dev/urandom for PHP 7from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$'] initialize = Executor.initialize
<commit_before>from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$'] initialize = Executor.initialize <commit_msg>Allow /dev/urandom for PHP 7<commit_after>from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$'] initialize = Executor.initialize
ec8d7b035617f9239a0a52be346d8611cf77cb6f
integration-tests/features/src/utils.py
integration-tests/features/src/utils.py
"""Unsorted utility functions used in integration tests.""" import requests def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')]
"""Unsorted utility functions used in integration tests.""" import requests import subprocess def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] def oc_login(url, username, password, tls_verify=True): """Wrapper around `oc login`. :param url: str, OpenShift URL :param username: str, username :param password: str, password :param tls_verify: bool, verify server's certificate?; default: True :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'login', url, '--username', username, '--password', password] if not tls_verify: command.extend(['--insecure-skip-tls-verify=true']) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: # replace password with '***' so somebody will not accidentally leak it in CI logs e.cmd = [x if x != password else '***' for x in e.cmd] raise e def oc_delete_pods(selector, namespace=None): """Wrapper around `oc delete`. Selector determines which pods will be deleted. More on selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Note k8s/OpenShift will immediately restart deleted pods, to match desired number of replicas for given deployment. The expectation is that the user is already logged in and has permissions to delete pods. Example usage: oc_delete_pods('service=bayesian-pgbouncer' :param selector: str, selector identifying pods that will be deleted :param namespace: str, namespace in which `oc delete` command should be executed, default: currently selected namespace :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'delete', 'pods', '--selector=', selector] if namespace: command.extend(['--namespace', namespace]) subprocess.check_call(command)
Add few oc wrappers for future resiliency testing
Add few oc wrappers for future resiliency testing Not used anywhere yet.
Python
apache-2.0
jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common
"""Unsorted utility functions used in integration tests.""" import requests def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] Add few oc wrappers for future resiliency testing Not used anywhere yet.
"""Unsorted utility functions used in integration tests.""" import requests import subprocess def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] def oc_login(url, username, password, tls_verify=True): """Wrapper around `oc login`. :param url: str, OpenShift URL :param username: str, username :param password: str, password :param tls_verify: bool, verify server's certificate?; default: True :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'login', url, '--username', username, '--password', password] if not tls_verify: command.extend(['--insecure-skip-tls-verify=true']) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: # replace password with '***' so somebody will not accidentally leak it in CI logs e.cmd = [x if x != password else '***' for x in e.cmd] raise e def oc_delete_pods(selector, namespace=None): """Wrapper around `oc delete`. Selector determines which pods will be deleted. More on selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Note k8s/OpenShift will immediately restart deleted pods, to match desired number of replicas for given deployment. The expectation is that the user is already logged in and has permissions to delete pods. Example usage: oc_delete_pods('service=bayesian-pgbouncer' :param selector: str, selector identifying pods that will be deleted :param namespace: str, namespace in which `oc delete` command should be executed, default: currently selected namespace :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'delete', 'pods', '--selector=', selector] if namespace: command.extend(['--namespace', namespace]) subprocess.check_call(command)
<commit_before>"""Unsorted utility functions used in integration tests.""" import requests def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] <commit_msg>Add few oc wrappers for future resiliency testing Not used anywhere yet.<commit_after>
"""Unsorted utility functions used in integration tests.""" import requests import subprocess def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] def oc_login(url, username, password, tls_verify=True): """Wrapper around `oc login`. :param url: str, OpenShift URL :param username: str, username :param password: str, password :param tls_verify: bool, verify server's certificate?; default: True :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'login', url, '--username', username, '--password', password] if not tls_verify: command.extend(['--insecure-skip-tls-verify=true']) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: # replace password with '***' so somebody will not accidentally leak it in CI logs e.cmd = [x if x != password else '***' for x in e.cmd] raise e def oc_delete_pods(selector, namespace=None): """Wrapper around `oc delete`. Selector determines which pods will be deleted. More on selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Note k8s/OpenShift will immediately restart deleted pods, to match desired number of replicas for given deployment. The expectation is that the user is already logged in and has permissions to delete pods. Example usage: oc_delete_pods('service=bayesian-pgbouncer' :param selector: str, selector identifying pods that will be deleted :param namespace: str, namespace in which `oc delete` command should be executed, default: currently selected namespace :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'delete', 'pods', '--selector=', selector] if namespace: command.extend(['--namespace', namespace]) subprocess.check_call(command)
"""Unsorted utility functions used in integration tests.""" import requests def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] Add few oc wrappers for future resiliency testing Not used anywhere yet."""Unsorted utility functions used in integration tests.""" import requests import subprocess def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] def oc_login(url, username, password, tls_verify=True): """Wrapper around `oc login`. :param url: str, OpenShift URL :param username: str, username :param password: str, password :param tls_verify: bool, verify server's certificate?; default: True :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'login', url, '--username', username, '--password', password] if not tls_verify: command.extend(['--insecure-skip-tls-verify=true']) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: # replace password with '***' so somebody will not accidentally leak it in CI logs e.cmd = [x if x != password else '***' for x in e.cmd] raise e def oc_delete_pods(selector, namespace=None): """Wrapper around `oc delete`. Selector determines which pods will be deleted. More on selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Note k8s/OpenShift will immediately restart deleted pods, to match desired number of replicas for given deployment. The expectation is that the user is already logged in and has permissions to delete pods. Example usage: oc_delete_pods('service=bayesian-pgbouncer' :param selector: str, selector identifying pods that will be deleted :param namespace: str, namespace in which `oc delete` command should be executed, default: currently selected namespace :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'delete', 'pods', '--selector=', selector] if namespace: command.extend(['--namespace', namespace]) subprocess.check_call(command)
<commit_before>"""Unsorted utility functions used in integration tests.""" import requests def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] <commit_msg>Add few oc wrappers for future resiliency testing Not used anywhere yet.<commit_after>"""Unsorted utility functions used in integration tests.""" import requests import subprocess def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] def oc_login(url, username, password, tls_verify=True): """Wrapper around `oc login`. :param url: str, OpenShift URL :param username: str, username :param password: str, password :param tls_verify: bool, verify server's certificate?; default: True :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'login', url, '--username', username, '--password', password] if not tls_verify: command.extend(['--insecure-skip-tls-verify=true']) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: # replace password with '***' so somebody will not accidentally leak it in CI logs e.cmd = [x if x != password else '***' for x in e.cmd] raise e def oc_delete_pods(selector, namespace=None): """Wrapper around `oc delete`. Selector determines which pods will be deleted. More on selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Note k8s/OpenShift will immediately restart deleted pods, to match desired number of replicas for given deployment. The expectation is that the user is already logged in and has permissions to delete pods. Example usage: oc_delete_pods('service=bayesian-pgbouncer' :param selector: str, selector identifying pods that will be deleted :param namespace: str, namespace in which `oc delete` command should be executed, default: currently selected namespace :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'delete', 'pods', '--selector=', selector] if namespace: command.extend(['--namespace', namespace]) subprocess.check_call(command)
65266813c6438eeb67002e17dd4cd70a00e84b5d
meta-iotqa/lib/oeqa/runtime/boottime.py
meta-iotqa/lib/oeqa/runtime/boottime.py
#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status,output) = self.target.copy_to(os.path.join(os.path.dirname(__file__), 'files','systemd-analyze'),"/tmp/systemd-analyze") self.assertEqual(status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status,output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual(status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename=os.path.basename(__file__) casename=os.path.splitext(filename)[0] (status,output) = self.target.run("/tmp/systemd-analyze time | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" %(casename, output) self.assertEqual(status, 0, output)
#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status, output) = self.target.copy_to( os.path.join(os.path.dirname(__file__), 'files', 'systemd-analyze'), "/tmp/systemd-analyze") self.assertEqual( status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status, output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual( status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename = os.path.basename(__file__) casename = os.path.splitext(filename)[0] (status, output) = self.target.run("/tmp/systemd-analyze time" " | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" % (casename, output) self.assertEqual(status, 0, output)
Clean the code with autopen8
Clean the code with autopen8
Python
mit
daweiwu/meta-iotqa-1,ostroproject/meta-iotqa,ostroproject/meta-iotqa,ostroproject/meta-iotqa,daweiwu/meta-iotqa-1,wanghongjuan/meta-iotqa-1,wanghongjuan/meta-iotqa-1,ostroproject/meta-iotqa,daweiwu/meta-iotqa-1,daweiwu/meta-iotqa-1,wanghongjuan/meta-iotqa-1,wanghongjuan/meta-iotqa-1,ostroproject/meta-iotqa,daweiwu/meta-iotqa-1,wanghongjuan/meta-iotqa-1
#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status,output) = self.target.copy_to(os.path.join(os.path.dirname(__file__), 'files','systemd-analyze'),"/tmp/systemd-analyze") self.assertEqual(status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status,output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual(status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename=os.path.basename(__file__) casename=os.path.splitext(filename)[0] (status,output) = self.target.run("/tmp/systemd-analyze time | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" %(casename, output) self.assertEqual(status, 0, output) Clean the code with autopen8
#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status, output) = self.target.copy_to( os.path.join(os.path.dirname(__file__), 'files', 'systemd-analyze'), "/tmp/systemd-analyze") self.assertEqual( status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status, output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual( status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename = os.path.basename(__file__) casename = os.path.splitext(filename)[0] (status, output) = self.target.run("/tmp/systemd-analyze time" " | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" % (casename, output) self.assertEqual(status, 0, output)
<commit_before>#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status,output) = self.target.copy_to(os.path.join(os.path.dirname(__file__), 'files','systemd-analyze'),"/tmp/systemd-analyze") self.assertEqual(status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status,output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual(status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename=os.path.basename(__file__) casename=os.path.splitext(filename)[0] (status,output) = self.target.run("/tmp/systemd-analyze time | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" %(casename, output) self.assertEqual(status, 0, output) <commit_msg>Clean the code with autopen8<commit_after>
#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status, output) = self.target.copy_to( os.path.join(os.path.dirname(__file__), 'files', 'systemd-analyze'), "/tmp/systemd-analyze") self.assertEqual( status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status, output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual( status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename = os.path.basename(__file__) casename = os.path.splitext(filename)[0] (status, output) = self.target.run("/tmp/systemd-analyze time" " | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" % (casename, output) self.assertEqual(status, 0, output)
#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status,output) = self.target.copy_to(os.path.join(os.path.dirname(__file__), 'files','systemd-analyze'),"/tmp/systemd-analyze") self.assertEqual(status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status,output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual(status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename=os.path.basename(__file__) casename=os.path.splitext(filename)[0] (status,output) = self.target.run("/tmp/systemd-analyze time | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" %(casename, output) self.assertEqual(status, 0, output) Clean the code with autopen8#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status, output) = self.target.copy_to( os.path.join(os.path.dirname(__file__), 'files', 'systemd-analyze'), "/tmp/systemd-analyze") self.assertEqual( status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status, output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual( status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename = os.path.basename(__file__) casename = os.path.splitext(filename)[0] (status, output) = self.target.run("/tmp/systemd-analyze time" " | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" % (casename, output) self.assertEqual(status, 0, output)
<commit_before>#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status,output) = self.target.copy_to(os.path.join(os.path.dirname(__file__), 'files','systemd-analyze'),"/tmp/systemd-analyze") self.assertEqual(status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status,output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual(status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename=os.path.basename(__file__) casename=os.path.splitext(filename)[0] (status,output) = self.target.run("/tmp/systemd-analyze time | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" %(casename, output) self.assertEqual(status, 0, output) <commit_msg>Clean the code with autopen8<commit_after>#[PROTEXCAT] #\License: ALL RIGHTS RESERVED """System boot time""" import os from oeqa.oetest import oeRuntimeTest from oeqa.runtime.helper import collect_pnp_log class BootTimeTest(oeRuntimeTest): def _setup(self): (status, output) = self.target.copy_to( os.path.join(os.path.dirname(__file__), 'files', 'systemd-analyze'), "/tmp/systemd-analyze") self.assertEqual( status, 0, msg="systemd-analyze could not be copied. Output: %s" % output) (status, output) = self.target.run(" ls -la /tmp/systemd-analyze") self.assertEqual( status, 0, msg="Failed to find systemd-analyze command") def test_boot_time(self): self._setup() filename = os.path.basename(__file__) casename = os.path.splitext(filename)[0] (status, output) = self.target.run("/tmp/systemd-analyze time" " | awk -F '=' '{print $2}'") collect_pnp_log(casename, output) print "\n%s:%s\n" % (casename, output) self.assertEqual(status, 0, output)
860e16f506d0a601540847fe21e617d8f7fbf882
malware/pickle_tool.py
malware/pickle_tool.py
import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache
import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache def pickle2json(pkl): if os.path.isfile(pkl): cache = pickle.load(open(pkl, 'rb')) with open('pkl2json.json', 'wb') as fp: json.dump(cache, fp) else: print "No such file"
Add pickle convert to json method
Add pickle convert to json method
Python
apache-2.0
John-Lin/malware,John-Lin/malware
import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache Add pickle convert to json method
import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache def pickle2json(pkl): if os.path.isfile(pkl): cache = pickle.load(open(pkl, 'rb')) with open('pkl2json.json', 'wb') as fp: json.dump(cache, fp) else: print "No such file"
<commit_before>import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache <commit_msg>Add pickle convert to json method<commit_after>
import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache def pickle2json(pkl): if os.path.isfile(pkl): cache = pickle.load(open(pkl, 'rb')) with open('pkl2json.json', 'wb') as fp: json.dump(cache, fp) else: print "No such file"
import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache Add pickle convert to json methodimport os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache def pickle2json(pkl): if os.path.isfile(pkl): cache = pickle.load(open(pkl, 'rb')) with open('pkl2json.json', 'wb') as fp: json.dump(cache, fp) else: print "No such file"
<commit_before>import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache <commit_msg>Add pickle convert to json method<commit_after>import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache def pickle2json(pkl): if os.path.isfile(pkl): cache = pickle.load(open(pkl, 'rb')) with open('pkl2json.json', 'wb') as fp: json.dump(cache, fp) else: print "No such file"
45c4c1f627f224f36c24acebbec43a17a5c59fcb
nib/plugins/lesscss.py
nib/plugins/lesscss.py
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
Print out file being processed, need to do to other modules, add -v flag
Print out file being processed, need to do to other modules, add -v flag
Python
mit
jreese/nib
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource Print out file being processed, need to do to other modules, add -v flag
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
<commit_before>from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource <commit_msg>Print out file being processed, need to do to other modules, add -v flag<commit_after>
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource Print out file being processed, need to do to other modules, add -v flagfrom __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
<commit_before>from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource <commit_msg>Print out file being processed, need to do to other modules, add -v flag<commit_after>from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
3266ecee8f9a6601d8678a91e8923c6d7137adb3
oggm/tests/conftest.py
oggm/tests/conftest.py
import pytest import logging import multiprocessing as mp from oggm import cfg, utils import pickle logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock") logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests")
import pytest import logging import getpass from oggm import cfg, utils logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock_" + getpass.getuser()) logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests")
Make ilock lock name user specific
Make ilock lock name user specific
Python
bsd-3-clause
OGGM/oggm,OGGM/oggm,bearecinos/oggm,bearecinos/oggm,juliaeis/oggm,TimoRoth/oggm,anoukvlug/oggm,TimoRoth/oggm,juliaeis/oggm,anoukvlug/oggm
import pytest import logging import multiprocessing as mp from oggm import cfg, utils import pickle logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock") logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests") Make ilock lock name user specific
import pytest import logging import getpass from oggm import cfg, utils logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock_" + getpass.getuser()) logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests")
<commit_before>import pytest import logging import multiprocessing as mp from oggm import cfg, utils import pickle logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock") logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests") <commit_msg>Make ilock lock name user specific<commit_after>
import pytest import logging import getpass from oggm import cfg, utils logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock_" + getpass.getuser()) logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests")
import pytest import logging import multiprocessing as mp from oggm import cfg, utils import pickle logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock") logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests") Make ilock lock name user specificimport pytest import logging import getpass from oggm import cfg, utils logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock_" + getpass.getuser()) logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests")
<commit_before>import pytest import logging import multiprocessing as mp from oggm import cfg, utils import pickle logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock") logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests") <commit_msg>Make ilock lock name user specific<commit_after>import pytest import logging import getpass from oggm import cfg, utils logger = logging.getLogger(__name__) def pytest_configure(config): if config.pluginmanager.hasplugin('xdist'): try: from ilock import ILock utils.lock = ILock("oggm_xdist_download_lock_" + getpass.getuser()) logger.info("ilock locking setup successfully for xdist tests") except: logger.warning("could not setup ilock locking for distributed tests")
102f7979338b948744b6af06689f928deb72f27c
spacy/tests/regression/test_issue781.py
spacy/tests/regression/test_issue781.py
# coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocalize", "colocaliz"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas
# coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocaliz", "colocalize"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas
Fix lemma ordering in test
Fix lemma ordering in test
Python
mit
spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,recognai/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy
# coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocalize", "colocaliz"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas Fix lemma ordering in test
# coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocaliz", "colocalize"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas
<commit_before># coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocalize", "colocaliz"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas <commit_msg>Fix lemma ordering in test<commit_after>
# coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocaliz", "colocalize"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas
# coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocalize", "colocaliz"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas Fix lemma ordering in test# coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocaliz", "colocalize"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas
<commit_before># coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocalize", "colocaliz"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas <commit_msg>Fix lemma ordering in test<commit_after># coding: utf-8 from __future__ import unicode_literals import pytest # Note: "chromosomes" worked previous the bug fix @pytest.mark.models('en') @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocaliz", "colocalize"])]) def test_issue781(EN, word, lemmas): lemmatizer = EN.Defaults.create_lemmatizer() assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == lemmas
0ae9b232b82285f2fa275b8ffa5dced6b9377b0e
keyring/credentials.py
keyring/credentials.py
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def __eq__(self, other: object) -> bool: if not isinstance(other, EnvironCredential): return NotImplemented return ( self.user_env_var == other.user_env_var and self.pwd_env_var == other.pwd_env_var ) def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
Add equality operator to EnvironCredential
Add equality operator to EnvironCredential Equality operator is useful for testing EnvironCredential
Python
mit
jaraco/keyring
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var) Add equality operator to EnvironCredential Equality operator is useful for testing EnvironCredential
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def __eq__(self, other: object) -> bool: if not isinstance(other, EnvironCredential): return NotImplemented return ( self.user_env_var == other.user_env_var and self.pwd_env_var == other.pwd_env_var ) def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
<commit_before>import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var) <commit_msg>Add equality operator to EnvironCredential Equality operator is useful for testing EnvironCredential<commit_after>
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def __eq__(self, other: object) -> bool: if not isinstance(other, EnvironCredential): return NotImplemented return ( self.user_env_var == other.user_env_var and self.pwd_env_var == other.pwd_env_var ) def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var) Add equality operator to EnvironCredential Equality operator is useful for testing EnvironCredentialimport os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def __eq__(self, other: object) -> bool: if not isinstance(other, EnvironCredential): return NotImplemented return ( self.user_env_var == other.user_env_var and self.pwd_env_var == other.pwd_env_var ) def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
<commit_before>import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var) <commit_msg>Add equality operator to EnvironCredential Equality operator is useful for testing EnvironCredential<commit_after>import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def __eq__(self, other: object) -> bool: if not isinstance(other, EnvironCredential): return NotImplemented return ( self.user_env_var == other.user_env_var and self.pwd_env_var == other.pwd_env_var ) def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
97312b55525f81ecba3c0df1d6c2e55fa217ce83
testsettings.py
testsettings.py
import os import dj_database_url DATABASES = { "default": dj_database_url.parse(os.environ["DATABASE_URL"]), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, }
import os import dj_database_url DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:") DATABASES = { "default": dj_database_url.parse(DATABASE_URL), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, }
Make tests run on sqlite by default
Make tests run on sqlite by default
Python
bsd-2-clause
dabapps/django-db-queue
import os import dj_database_url DATABASES = { "default": dj_database_url.parse(os.environ["DATABASE_URL"]), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, } Make tests run on sqlite by default
import os import dj_database_url DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:") DATABASES = { "default": dj_database_url.parse(DATABASE_URL), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, }
<commit_before>import os import dj_database_url DATABASES = { "default": dj_database_url.parse(os.environ["DATABASE_URL"]), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, } <commit_msg>Make tests run on sqlite by default<commit_after>
import os import dj_database_url DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:") DATABASES = { "default": dj_database_url.parse(DATABASE_URL), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, }
import os import dj_database_url DATABASES = { "default": dj_database_url.parse(os.environ["DATABASE_URL"]), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, } Make tests run on sqlite by defaultimport os import dj_database_url DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:") DATABASES = { "default": dj_database_url.parse(DATABASE_URL), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, }
<commit_before>import os import dj_database_url DATABASES = { "default": dj_database_url.parse(os.environ["DATABASE_URL"]), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, } <commit_msg>Make tests run on sqlite by default<commit_after>import os import dj_database_url DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:") DATABASES = { "default": dj_database_url.parse(DATABASE_URL), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, }
e8c180e65dda3422ab472a6580183c715ef325c3
easyium/decorator.py
easyium/decorator.py
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "This operation is not supported by web driver [%s]." % current_web_driver_type) return func(*args, **kwargs) return handle_args return handle_func
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
Update error message of UnsupportedOperationException.
Update error message of UnsupportedOperationException.
Python
apache-2.0
KarlGong/easyium-python,KarlGong/easyium
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "This operation is not supported by web driver [%s]." % current_web_driver_type) return func(*args, **kwargs) return handle_args return handle_func Update error message of UnsupportedOperationException.
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
<commit_before>__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "This operation is not supported by web driver [%s]." % current_web_driver_type) return func(*args, **kwargs) return handle_args return handle_func <commit_msg>Update error message of UnsupportedOperationException.<commit_after>
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "This operation is not supported by web driver [%s]." % current_web_driver_type) return func(*args, **kwargs) return handle_args return handle_func Update error message of UnsupportedOperationException.__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
<commit_before>__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "This operation is not supported by web driver [%s]." % current_web_driver_type) return func(*args, **kwargs) return handle_args return handle_func <commit_msg>Update error message of UnsupportedOperationException.<commit_after>__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
e893ac40de2dda19196c7de7d9f7767b20b23884
headers/cpp/functions.py
headers/cpp/functions.py
#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. condition = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], condition) if __name__ == '__main__': main(sys.argv)
#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. IsFunction = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], IsFunction) if __name__ == '__main__': main(sys.argv)
Use a better function (lambda) name
Use a better function (lambda) name git-svn-id: b0ea89ea3bf41df64b6a046736e217d0ae4a0fba@40 806ff5bb-693f-0410-b502-81bc3482ff28
Python
apache-2.0
myint/cppclean,myint/cppclean,myint/cppclean,myint/cppclean
#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. condition = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], condition) if __name__ == '__main__': main(sys.argv) Use a better function (lambda) name git-svn-id: b0ea89ea3bf41df64b6a046736e217d0ae4a0fba@40 806ff5bb-693f-0410-b502-81bc3482ff28
#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. IsFunction = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], IsFunction) if __name__ == '__main__': main(sys.argv)
<commit_before>#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. condition = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], condition) if __name__ == '__main__': main(sys.argv) <commit_msg>Use a better function (lambda) name git-svn-id: b0ea89ea3bf41df64b6a046736e217d0ae4a0fba@40 806ff5bb-693f-0410-b502-81bc3482ff28<commit_after>
#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. IsFunction = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], IsFunction) if __name__ == '__main__': main(sys.argv)
#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. condition = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], condition) if __name__ == '__main__': main(sys.argv) Use a better function (lambda) name git-svn-id: b0ea89ea3bf41df64b6a046736e217d0ae4a0fba@40 806ff5bb-693f-0410-b502-81bc3482ff28#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. IsFunction = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], IsFunction) if __name__ == '__main__': main(sys.argv)
<commit_before>#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. condition = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], condition) if __name__ == '__main__': main(sys.argv) <commit_msg>Use a better function (lambda) name git-svn-id: b0ea89ea3bf41df64b6a046736e217d0ae4a0fba@40 806ff5bb-693f-0410-b502-81bc3482ff28<commit_after>#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. IsFunction = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], IsFunction) if __name__ == '__main__': main(sys.argv)
60ee6a5d2ad9e85fefd973c020ef65bd212e687c
astrobin/management/commands/notify_new_blog_entry.py
astrobin/management/commands/notify_new_blog_entry.py
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from zinnia.models import Entry from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] push_notification( User.objects.all(), 'new_blog_entry', { 'object': entry.title, 'object_url': entry.get_absolute_url() } )
from django.core.management.base import BaseCommand from django.contrib.auth.models import User import persistent_messages from zinnia.models import Entry class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] for u in User.objects.all(): m = persistent_messages.models.Message( user = u, from_user = User.objects.get(username = 'astrobin'), message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>', level = persistent_messages.INFO, ) m.save()
Fix management command to send notification about new blog post.
Fix management command to send notification about new blog post.
Python
agpl-3.0
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from zinnia.models import Entry from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] push_notification( User.objects.all(), 'new_blog_entry', { 'object': entry.title, 'object_url': entry.get_absolute_url() } ) Fix management command to send notification about new blog post.
from django.core.management.base import BaseCommand from django.contrib.auth.models import User import persistent_messages from zinnia.models import Entry class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] for u in User.objects.all(): m = persistent_messages.models.Message( user = u, from_user = User.objects.get(username = 'astrobin'), message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>', level = persistent_messages.INFO, ) m.save()
<commit_before>from django.core.management.base import BaseCommand from django.contrib.auth.models import User from zinnia.models import Entry from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] push_notification( User.objects.all(), 'new_blog_entry', { 'object': entry.title, 'object_url': entry.get_absolute_url() } ) <commit_msg>Fix management command to send notification about new blog post.<commit_after>
from django.core.management.base import BaseCommand from django.contrib.auth.models import User import persistent_messages from zinnia.models import Entry class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] for u in User.objects.all(): m = persistent_messages.models.Message( user = u, from_user = User.objects.get(username = 'astrobin'), message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>', level = persistent_messages.INFO, ) m.save()
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from zinnia.models import Entry from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] push_notification( User.objects.all(), 'new_blog_entry', { 'object': entry.title, 'object_url': entry.get_absolute_url() } ) Fix management command to send notification about new blog post.from django.core.management.base import BaseCommand from django.contrib.auth.models import User import persistent_messages from zinnia.models import Entry class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] for u in User.objects.all(): m = persistent_messages.models.Message( user = u, from_user = User.objects.get(username = 'astrobin'), message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>', level = persistent_messages.INFO, ) m.save()
<commit_before>from django.core.management.base import BaseCommand from django.contrib.auth.models import User from zinnia.models import Entry from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] push_notification( User.objects.all(), 'new_blog_entry', { 'object': entry.title, 'object_url': entry.get_absolute_url() } ) <commit_msg>Fix management command to send notification about new blog post.<commit_after>from django.core.management.base import BaseCommand from django.contrib.auth.models import User import persistent_messages from zinnia.models import Entry class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] for u in User.objects.all(): m = persistent_messages.models.Message( user = u, from_user = User.objects.get(username = 'astrobin'), message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>', level = persistent_messages.INFO, ) m.save()
1af1a7acface58cd8a6df5671d83b0a1a3ad4f3e
tiddlywebplugins/tiddlyspace/config.py
tiddlywebplugins/tiddlyspace/config.py
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', }
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', 'tiddlywebwiki.binary_limit': 1048576, # 1MB }
Set the tiddlywebwiki binary limit to 1MB.
Set the tiddlywebwiki binary limit to 1MB.
Python
bsd-3-clause
FND/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,TiddlySpace/tiddlyspace
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', } Set the tiddlywebwiki binary limit to 1MB.
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', 'tiddlywebwiki.binary_limit': 1048576, # 1MB }
<commit_before>""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', } <commit_msg>Set the tiddlywebwiki binary limit to 1MB.<commit_after>
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', 'tiddlywebwiki.binary_limit': 1048576, # 1MB }
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', } Set the tiddlywebwiki binary limit to 1MB.""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', 'tiddlywebwiki.binary_limit': 1048576, # 1MB }
<commit_before>""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', } <commit_msg>Set the tiddlywebwiki binary limit to 1MB.<commit_after>""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', 'tiddlywebwiki.binary_limit': 1048576, # 1MB }
18f29b2b1a99614b09591df4a60c1670c845aa9b
students/crobison/session04/dict_lab.py
students/crobison/session04/dict_lab.py
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} #Display the dictionary. d # Delete the entry for “cake”. del d['cake'] # Display the dictionary. d # Add an entry for “fruit” with “Mango” and display the dictionary. d['fruit'] = 'Mango' d # Display the dictionary keys. d.keys() # Display the dictionary values. d.values() # Display whether or not “cake” is a key in the dictionary # (i.e. False) (now). 'cake' in d # Display whether or not “Mango” is a value in the dictionary # (i.e. True). 'Mango' in d.values() # Using the dictionary from item 1: Make a dictionary using # the same keys but with the number of ‘t’s in each value. # Create sets s2, s3 and s4 that contain numbers from zero through # twenty, divisible 2, 3 and 4. # Display the sets. # Display if s3 is a subset of s2 (False) # and if s4 is a subset of s2 (True). # Create a set with the letters in ‘Python’ and add ‘i’ to the set. # Create a frozenset with the letters in ‘marathon’ # display the union and intersection of the two sets.
Add first set of exercises.
Add first set of exercises.
Python
unlicense
Baumelbi/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,Baumelbi/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} Add first set of exercises.
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} #Display the dictionary. d # Delete the entry for “cake”. del d['cake'] # Display the dictionary. d # Add an entry for “fruit” with “Mango” and display the dictionary. d['fruit'] = 'Mango' d # Display the dictionary keys. d.keys() # Display the dictionary values. d.values() # Display whether or not “cake” is a key in the dictionary # (i.e. False) (now). 'cake' in d # Display whether or not “Mango” is a value in the dictionary # (i.e. True). 'Mango' in d.values() # Using the dictionary from item 1: Make a dictionary using # the same keys but with the number of ‘t’s in each value. # Create sets s2, s3 and s4 that contain numbers from zero through # twenty, divisible 2, 3 and 4. # Display the sets. # Display if s3 is a subset of s2 (False) # and if s4 is a subset of s2 (True). # Create a set with the letters in ‘Python’ and add ‘i’ to the set. # Create a frozenset with the letters in ‘marathon’ # display the union and intersection of the two sets.
<commit_before># Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} <commit_msg>Add first set of exercises.<commit_after>
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} #Display the dictionary. d # Delete the entry for “cake”. del d['cake'] # Display the dictionary. d # Add an entry for “fruit” with “Mango” and display the dictionary. d['fruit'] = 'Mango' d # Display the dictionary keys. d.keys() # Display the dictionary values. d.values() # Display whether or not “cake” is a key in the dictionary # (i.e. False) (now). 'cake' in d # Display whether or not “Mango” is a value in the dictionary # (i.e. True). 'Mango' in d.values() # Using the dictionary from item 1: Make a dictionary using # the same keys but with the number of ‘t’s in each value. # Create sets s2, s3 and s4 that contain numbers from zero through # twenty, divisible 2, 3 and 4. # Display the sets. # Display if s3 is a subset of s2 (False) # and if s4 is a subset of s2 (True). # Create a set with the letters in ‘Python’ and add ‘i’ to the set. # Create a frozenset with the letters in ‘marathon’ # display the union and intersection of the two sets.
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} Add first set of exercises.# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} #Display the dictionary. d # Delete the entry for “cake”. del d['cake'] # Display the dictionary. d # Add an entry for “fruit” with “Mango” and display the dictionary. d['fruit'] = 'Mango' d # Display the dictionary keys. d.keys() # Display the dictionary values. d.values() # Display whether or not “cake” is a key in the dictionary # (i.e. False) (now). 'cake' in d # Display whether or not “Mango” is a value in the dictionary # (i.e. True). 'Mango' in d.values() # Using the dictionary from item 1: Make a dictionary using # the same keys but with the number of ‘t’s in each value. # Create sets s2, s3 and s4 that contain numbers from zero through # twenty, divisible 2, 3 and 4. # Display the sets. # Display if s3 is a subset of s2 (False) # and if s4 is a subset of s2 (True). # Create a set with the letters in ‘Python’ and add ‘i’ to the set. # Create a frozenset with the letters in ‘marathon’ # display the union and intersection of the two sets.
<commit_before># Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} <commit_msg>Add first set of exercises.<commit_after># Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} #Display the dictionary. d # Delete the entry for “cake”. del d['cake'] # Display the dictionary. d # Add an entry for “fruit” with “Mango” and display the dictionary. d['fruit'] = 'Mango' d # Display the dictionary keys. d.keys() # Display the dictionary values. d.values() # Display whether or not “cake” is a key in the dictionary # (i.e. False) (now). 'cake' in d # Display whether or not “Mango” is a value in the dictionary # (i.e. True). 'Mango' in d.values() # Using the dictionary from item 1: Make a dictionary using # the same keys but with the number of ‘t’s in each value. # Create sets s2, s3 and s4 that contain numbers from zero through # twenty, divisible 2, 3 and 4. # Display the sets. # Display if s3 is a subset of s2 (False) # and if s4 is a subset of s2 (True). # Create a set with the letters in ‘Python’ and add ‘i’ to the set. # Create a frozenset with the letters in ‘marathon’ # display the union and intersection of the two sets.
c9b6387702baee3da0a3bca8b302b619e69893f7
steel/chunks/iff.py
steel/chunks/iff.py
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class ChunkList(base.ChunkList): def __init__(self, *args, **kwargs): # Just a simple override to default to a list of IFF chunks return super(ChunkList, self).__init__(Chunk, *args, **kwargs) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
Customize a ChunkList just for IFF chunks
Customize a ChunkList just for IFF chunks
Python
bsd-3-clause
gulopine/steel
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size) Customize a ChunkList just for IFF chunks
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class ChunkList(base.ChunkList): def __init__(self, *args, **kwargs): # Just a simple override to default to a list of IFF chunks return super(ChunkList, self).__init__(Chunk, *args, **kwargs) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
<commit_before>import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size) <commit_msg>Customize a ChunkList just for IFF chunks<commit_after>
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class ChunkList(base.ChunkList): def __init__(self, *args, **kwargs): # Just a simple override to default to a list of IFF chunks return super(ChunkList, self).__init__(Chunk, *args, **kwargs) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size) Customize a ChunkList just for IFF chunksimport collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class ChunkList(base.ChunkList): def __init__(self, *args, **kwargs): # Just a simple override to default to a list of IFF chunks return super(ChunkList, self).__init__(Chunk, *args, **kwargs) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
<commit_before>import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size) <commit_msg>Customize a ChunkList just for IFF chunks<commit_after>import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class ChunkList(base.ChunkList): def __init__(self, *args, **kwargs): # Just a simple override to default to a list of IFF chunks return super(ChunkList, self).__init__(Chunk, *args, **kwargs) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
f7d4a3df11a67e3ae679b4c8f25780538c4c3c32
core/management/commands/send_tweets.py
core/management/commands/send_tweets.py
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostMedia(tweet.text, tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
Use the newer PostUpdate instead of PostMedia
Use the newer PostUpdate instead of PostMedia
Python
agpl-3.0
osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostMedia(tweet.text, tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save() Use the newer PostUpdate instead of PostMedia
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
<commit_before>import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostMedia(tweet.text, tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save() <commit_msg>Use the newer PostUpdate instead of PostMedia<commit_after>
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostMedia(tweet.text, tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save() Use the newer PostUpdate instead of PostMediaimport twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
<commit_before>import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostMedia(tweet.text, tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save() <commit_msg>Use the newer PostUpdate instead of PostMedia<commit_after>import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
7a952d605b629b9c8ef2c96c451ee4db4274d545
suddendev/config.py
suddendev/config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 10 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 1 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
Set max celery connections to 1.
[NG] Set max celery connections to 1.
Python
mit
SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 10 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True [NG] Set max celery connections to 1.
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 1 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
<commit_before>import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 10 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True <commit_msg>[NG] Set max celery connections to 1.<commit_after>
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 1 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 10 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True [NG] Set max celery connections to 1.import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 1 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
<commit_before>import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 10 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True <commit_msg>[NG] Set max celery connections to 1.<commit_after>import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] CELERY_RESULT_BACKEND = 'rpc' REDIS_URL = os.environ['REDIS_URL'] CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com' AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] CLIENT_SECRET = os.environ['CLIENT_SECRET'] REDIS_MAX_CONNECTIONS = 10 CELERY_MAX_CONNECTIONS = 1 class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
70a40f50e9988fadfbc42f236881c1e3e78f40f1
icekit/project/settings/_test.py
icekit/project/settings/_test.py
from ._develop import * # DJANGO ###################################################################### DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
from ._base import * # DJANGO ###################################################################### ALLOWED_HOSTS = ('*', ) CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
Extend base settings for test settings. Don't use live cache backend for tests.
Extend base settings for test settings. Don't use live cache backend for tests.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
from ._develop import * # DJANGO ###################################################################### DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive') Extend base settings for test settings. Don't use live cache backend for tests.
from ._base import * # DJANGO ###################################################################### ALLOWED_HOSTS = ('*', ) CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
<commit_before>from ._develop import * # DJANGO ###################################################################### DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive') <commit_msg>Extend base settings for test settings. Don't use live cache backend for tests.<commit_after>
from ._base import * # DJANGO ###################################################################### ALLOWED_HOSTS = ('*', ) CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
from ._develop import * # DJANGO ###################################################################### DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive') Extend base settings for test settings. Don't use live cache backend for tests.from ._base import * # DJANGO ###################################################################### ALLOWED_HOSTS = ('*', ) CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
<commit_before>from ._develop import * # DJANGO ###################################################################### DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive') <commit_msg>Extend base settings for test settings. Don't use live cache backend for tests.<commit_after>from ._base import * # DJANGO ###################################################################### ALLOWED_HOSTS = ('*', ) CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
6c74e5c2bc08fd48af9e646dc911cff5e22064cb
django_performance_recorder/__init__.py
django_performance_recorder/__init__.py
# -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from .api import record # noqa: F401 __version__ = '1.0.0'
# -*- coding:utf-8 -*- """ isort:skip_file """ from __future__ import absolute_import, division, print_function, unicode_literals import six try: import pytest except ImportError: pytest = None if pytest is not None: if six.PY2: pytest.register_assert_rewrite(b'django_performance_recorder.api') else: pytest.register_assert_rewrite('django_performance_recorder.api') from .api import record # noqa: F401 __version__ = '1.0.0'
Make assert statement rich in pytest
Make assert statement rich in pytest
Python
mit
moumoutte/django-perf-rec,YPlan/django-perf-rec
# -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from .api import record # noqa: F401 __version__ = '1.0.0' Make assert statement rich in pytest
# -*- coding:utf-8 -*- """ isort:skip_file """ from __future__ import absolute_import, division, print_function, unicode_literals import six try: import pytest except ImportError: pytest = None if pytest is not None: if six.PY2: pytest.register_assert_rewrite(b'django_performance_recorder.api') else: pytest.register_assert_rewrite('django_performance_recorder.api') from .api import record # noqa: F401 __version__ = '1.0.0'
<commit_before># -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from .api import record # noqa: F401 __version__ = '1.0.0' <commit_msg>Make assert statement rich in pytest<commit_after>
# -*- coding:utf-8 -*- """ isort:skip_file """ from __future__ import absolute_import, division, print_function, unicode_literals import six try: import pytest except ImportError: pytest = None if pytest is not None: if six.PY2: pytest.register_assert_rewrite(b'django_performance_recorder.api') else: pytest.register_assert_rewrite('django_performance_recorder.api') from .api import record # noqa: F401 __version__ = '1.0.0'
# -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from .api import record # noqa: F401 __version__ = '1.0.0' Make assert statement rich in pytest# -*- coding:utf-8 -*- """ isort:skip_file """ from __future__ import absolute_import, division, print_function, unicode_literals import six try: import pytest except ImportError: pytest = None if pytest is not None: if six.PY2: pytest.register_assert_rewrite(b'django_performance_recorder.api') else: pytest.register_assert_rewrite('django_performance_recorder.api') from .api import record # noqa: F401 __version__ = '1.0.0'
<commit_before># -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from .api import record # noqa: F401 __version__ = '1.0.0' <commit_msg>Make assert statement rich in pytest<commit_after># -*- coding:utf-8 -*- """ isort:skip_file """ from __future__ import absolute_import, division, print_function, unicode_literals import six try: import pytest except ImportError: pytest = None if pytest is not None: if six.PY2: pytest.register_assert_rewrite(b'django_performance_recorder.api') else: pytest.register_assert_rewrite('django_performance_recorder.api') from .api import record # noqa: F401 __version__ = '1.0.0'
89984eb5e9e8cdb8420ff1da07c54ce0dd265629
tests/test_git_pre_commit_hook_utils.py
tests/test_git_pre_commit_hook_utils.py
import git_pre_commit_hook_utils as utils def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code()
import git_pre_commit_hook_utils as utils import scripttest import os import copy def test_with_empty_repo(tmpdir): os_environ = copy.deepcopy(os.environ) os_environ['GIT_DIR'] = str(tmpdir) os_environ['GIT_WORK_TREE'] = str(tmpdir) env = scripttest.TestFileEnvironment( str(tmpdir), start_clear=False, template_path='data', environ=os_environ, ) env.writefile('empty_file', content='') env.run('git', 'init') env.run('git', 'add', 'empty_file') files_staged_for_commit = list(utils.files_staged_for_commit()) assert len(files_staged_for_commit) == 1 file_at_index = files_staged_for_commit[0] assert file_at_index.path == 'empty_file' assert file_at_index.contents == '' assert file_at_index.size == 0 assert file_at_index.status == 'A' def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code()
Add test for commit to empty repo case
Add test for commit to empty repo case
Python
mit
evvers/git-pre-commit-hook-utils
import git_pre_commit_hook_utils as utils def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code() Add test for commit to empty repo case
import git_pre_commit_hook_utils as utils import scripttest import os import copy def test_with_empty_repo(tmpdir): os_environ = copy.deepcopy(os.environ) os_environ['GIT_DIR'] = str(tmpdir) os_environ['GIT_WORK_TREE'] = str(tmpdir) env = scripttest.TestFileEnvironment( str(tmpdir), start_clear=False, template_path='data', environ=os_environ, ) env.writefile('empty_file', content='') env.run('git', 'init') env.run('git', 'add', 'empty_file') files_staged_for_commit = list(utils.files_staged_for_commit()) assert len(files_staged_for_commit) == 1 file_at_index = files_staged_for_commit[0] assert file_at_index.path == 'empty_file' assert file_at_index.contents == '' assert file_at_index.size == 0 assert file_at_index.status == 'A' def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code()
<commit_before>import git_pre_commit_hook_utils as utils def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code() <commit_msg>Add test for commit to empty repo case<commit_after>
import git_pre_commit_hook_utils as utils import scripttest import os import copy def test_with_empty_repo(tmpdir): os_environ = copy.deepcopy(os.environ) os_environ['GIT_DIR'] = str(tmpdir) os_environ['GIT_WORK_TREE'] = str(tmpdir) env = scripttest.TestFileEnvironment( str(tmpdir), start_clear=False, template_path='data', environ=os_environ, ) env.writefile('empty_file', content='') env.run('git', 'init') env.run('git', 'add', 'empty_file') files_staged_for_commit = list(utils.files_staged_for_commit()) assert len(files_staged_for_commit) == 1 file_at_index = files_staged_for_commit[0] assert file_at_index.path == 'empty_file' assert file_at_index.contents == '' assert file_at_index.size == 0 assert file_at_index.status == 'A' def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code()
import git_pre_commit_hook_utils as utils def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code() Add test for commit to empty repo caseimport git_pre_commit_hook_utils as utils import scripttest import os import copy def test_with_empty_repo(tmpdir): os_environ = copy.deepcopy(os.environ) os_environ['GIT_DIR'] = str(tmpdir) os_environ['GIT_WORK_TREE'] = str(tmpdir) env = scripttest.TestFileEnvironment( str(tmpdir), start_clear=False, template_path='data', environ=os_environ, ) env.writefile('empty_file', content='') env.run('git', 'init') env.run('git', 'add', 'empty_file') files_staged_for_commit = list(utils.files_staged_for_commit()) assert len(files_staged_for_commit) == 1 file_at_index = files_staged_for_commit[0] assert file_at_index.path == 'empty_file' assert file_at_index.contents == '' assert file_at_index.size == 0 assert file_at_index.status == 'A' def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code()
<commit_before>import git_pre_commit_hook_utils as utils def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code() <commit_msg>Add test for commit to empty repo case<commit_after>import git_pre_commit_hook_utils as utils import scripttest import os import copy def test_with_empty_repo(tmpdir): os_environ = copy.deepcopy(os.environ) os_environ['GIT_DIR'] = str(tmpdir) os_environ['GIT_WORK_TREE'] = str(tmpdir) env = scripttest.TestFileEnvironment( str(tmpdir), start_clear=False, template_path='data', environ=os_environ, ) env.writefile('empty_file', content='') env.run('git', 'init') env.run('git', 'add', 'empty_file') files_staged_for_commit = list(utils.files_staged_for_commit()) assert len(files_staged_for_commit) == 1 file_at_index = files_staged_for_commit[0] assert file_at_index.path == 'empty_file' assert file_at_index.contents == '' assert file_at_index.size == 0 assert file_at_index.status == 'A' def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code()
30a173da5850a457393cfdf47b7c0db303cdd2e9
tests/test_utils.py
tests/test_utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai.core.nonexistingimport') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
Test importing of module with unexisting target inside
Test importing of module with unexisting target inside There's a coverage case where a module exists, but what's inside it isn't covered.
Python
mit
cihai/cihai-python,cihai/cihai,cihai/cihai
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2') Test importing of module with unexisting target inside There's a coverage case where a module exists, but what's inside it isn't covered.
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai.core.nonexistingimport') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2') <commit_msg>Test importing of module with unexisting target inside There's a coverage case where a module exists, but what's inside it isn't covered.<commit_after>
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai.core.nonexistingimport') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2') Test importing of module with unexisting target inside There's a coverage case where a module exists, but what's inside it isn't covered.# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai.core.nonexistingimport') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2') <commit_msg>Test importing of module with unexisting target inside There's a coverage case where a module exists, but what's inside it isn't covered.<commit_after># -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai.core.nonexistingimport') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
fc259061ccf048af7e657888eb655da120a6606f
panoptes/test/mount/test_ioptron.py
panoptes/test/mount/test_ioptron.py
from nose.tools import raises import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False
import nose.tools import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @nose.tools.raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @nose.tools.raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False def test_port_set(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) nose.tools.ok_(mount.port == '/dev/ttyUSB0')
Use nose.tools explicitly; test for port
Use nose.tools explicitly; test for port
Python
mit
fmin2958/POCS,Guokr1991/POCS,joshwalawender/POCS,panoptes/POCS,joshwalawender/POCS,panoptes/POCS,panoptes/POCS,Guokr1991/POCS,fmin2958/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,joshwalawender/POCS,AstroHuntsman/POCS,Guokr1991/POCS,panoptes/POCS,fmin2958/POCS,Guokr1991/POCS,AstroHuntsman/POCS
from nose.tools import raises import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is FalseUse nose.tools explicitly; test for port
import nose.tools import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @nose.tools.raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @nose.tools.raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False def test_port_set(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) nose.tools.ok_(mount.port == '/dev/ttyUSB0')
<commit_before>from nose.tools import raises import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False<commit_msg>Use nose.tools explicitly; test for port<commit_after>
import nose.tools import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @nose.tools.raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @nose.tools.raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False def test_port_set(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) nose.tools.ok_(mount.port == '/dev/ttyUSB0')
from nose.tools import raises import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is FalseUse nose.tools explicitly; test for portimport nose.tools import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @nose.tools.raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @nose.tools.raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False def test_port_set(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) nose.tools.ok_(mount.port == '/dev/ttyUSB0')
<commit_before>from nose.tools import raises import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False<commit_msg>Use nose.tools explicitly; test for port<commit_after>import nose.tools import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @nose.tools.raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @nose.tools.raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False def test_port_set(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) nose.tools.ok_(mount.port == '/dev/ttyUSB0')
d448367d68e37c2d719063b8ec2ce543fec5b5e7
sphinxcontrib/reviewbuilder/__init__.py
sphinxcontrib/reviewbuilder/__init__.py
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils.nodes import Text, paragraph from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(Text): if isinstance(node.parent, paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace)
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils import nodes from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(nodes.Text): if isinstance(node.parent, nodes.paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, nodes.Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace)
Access docutils standard nodes through nodes.*
Access docutils standard nodes through nodes.*
Python
lgpl-2.1
shirou/sphinxcontrib-reviewbuilder
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils.nodes import Text, paragraph from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(Text): if isinstance(node.parent, paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace) Access docutils standard nodes through nodes.*
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils import nodes from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(nodes.Text): if isinstance(node.parent, nodes.paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, nodes.Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace)
<commit_before># -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils.nodes import Text, paragraph from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(Text): if isinstance(node.parent, paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace) <commit_msg>Access docutils standard nodes through nodes.*<commit_after>
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils import nodes from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(nodes.Text): if isinstance(node.parent, nodes.paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, nodes.Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace)
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils.nodes import Text, paragraph from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(Text): if isinstance(node.parent, paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace) Access docutils standard nodes through nodes.*# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils import nodes from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(nodes.Text): if isinstance(node.parent, nodes.paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, nodes.Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace)
<commit_before># -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils.nodes import Text, paragraph from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(Text): if isinstance(node.parent, paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace) <commit_msg>Access docutils standard nodes through nodes.*<commit_after># -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils import nodes from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(nodes.Text): if isinstance(node.parent, nodes.paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, nodes.Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace)
f2f77cd326c3b121eb7e6e53dfcab3964f473451
fileupload/models.py
fileupload/models.py
from django.db import models class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs)
from django.db import models class Picture(models.Model): # This is a small demo using FileField instead of ImageField, not # depending on PIL. You will probably want ImageField in your app. file = models.FileField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs)
Use FileField instead of ImageField, we don't need PIL in this demo.
Use FileField instead of ImageField, we don't need PIL in this demo.
Python
mit
extremoburo/django-jquery-file-upload,indrajithi/mgc-django,Imaginashion/cloud-vision,madteckhead/django-jquery-file-upload,sigurdga/django-jquery-file-upload,vaniakov/django-jquery-file-upload,extremoburo/django-jquery-file-upload,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,madteckhead/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,indrajithi/mgc-django,extremoburo/django-jquery-file-upload,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision,minhlongdo/django-jquery-file-upload,vaniakov/django-jquery-file-upload,minhlongdo/django-jquery-file-upload,vaniakov/django-jquery-file-upload,minhlongdo/django-jquery-file-upload
from django.db import models class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) Use FileField instead of ImageField, we don't need PIL in this demo.
from django.db import models class Picture(models.Model): # This is a small demo using FileField instead of ImageField, not # depending on PIL. You will probably want ImageField in your app. file = models.FileField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs)
<commit_before>from django.db import models class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) <commit_msg>Use FileField instead of ImageField, we don't need PIL in this demo.<commit_after>
from django.db import models class Picture(models.Model): # This is a small demo using FileField instead of ImageField, not # depending on PIL. You will probably want ImageField in your app. file = models.FileField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs)
from django.db import models class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) Use FileField instead of ImageField, we don't need PIL in this demo.from django.db import models class Picture(models.Model): # This is a small demo using FileField instead of ImageField, not # depending on PIL. You will probably want ImageField in your app. file = models.FileField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs)
<commit_before>from django.db import models class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) <commit_msg>Use FileField instead of ImageField, we don't need PIL in this demo.<commit_after>from django.db import models class Picture(models.Model): # This is a small demo using FileField instead of ImageField, not # depending on PIL. You will probably want ImageField in your app. file = models.FileField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs)
72c9a00d691b2b91bf39e1f5bdd1ef2358d8d671
updateCollection.py
updateCollection.py
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/agarner_collections/agarner_Item_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) itemData = fileData['items'] itemArr = [] for value in itemData: item = ItemFactory.factory( fileData['collectionType'], value.values() ) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) for item in collection.items: print(item.id) def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main()
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory from collections import OrderedDict import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/TestUser_collections/TestUser_album_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) collectionType = fileData['collectionType'] collectionName = fileData['collectionName'] username = fileData['username'] itemData = fileData['items'] itemArr = [] for value in itemData: if fileData['collectionType'] == 'item': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit']]) itemArr.append(item) elif fileData['collectionType'] == 'album': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['artist']]) itemArr.append(item) elif fileData['collectionType'] == 'book': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['author']]) itemArr.append(item) elif fileData['collectionType'] == 'movie': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['director']]) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) print collection.collectionType print collection.collectionName print collection.username print collection.items def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main()
Implement base json extraction to collection functionality
Implement base json extraction to collection functionality
Python
apache-2.0
AmosGarner/PyInventory
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/agarner_collections/agarner_Item_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) itemData = fileData['items'] itemArr = [] for value in itemData: item = ItemFactory.factory( fileData['collectionType'], value.values() ) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) for item in collection.items: print(item.id) def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main() Implement base json extraction to collection functionality
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory from collections import OrderedDict import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/TestUser_collections/TestUser_album_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) collectionType = fileData['collectionType'] collectionName = fileData['collectionName'] username = fileData['username'] itemData = fileData['items'] itemArr = [] for value in itemData: if fileData['collectionType'] == 'item': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit']]) itemArr.append(item) elif fileData['collectionType'] == 'album': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['artist']]) itemArr.append(item) elif fileData['collectionType'] == 'book': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['author']]) itemArr.append(item) elif fileData['collectionType'] == 'movie': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['director']]) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) print collection.collectionType print collection.collectionName print collection.username print collection.items def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main()
<commit_before>from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/agarner_collections/agarner_Item_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) itemData = fileData['items'] itemArr = [] for value in itemData: item = ItemFactory.factory( fileData['collectionType'], value.values() ) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) for item in collection.items: print(item.id) def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main() <commit_msg>Implement base json extraction to collection functionality<commit_after>
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory from collections import OrderedDict import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/TestUser_collections/TestUser_album_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) collectionType = fileData['collectionType'] collectionName = fileData['collectionName'] username = fileData['username'] itemData = fileData['items'] itemArr = [] for value in itemData: if fileData['collectionType'] == 'item': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit']]) itemArr.append(item) elif fileData['collectionType'] == 'album': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['artist']]) itemArr.append(item) elif fileData['collectionType'] == 'book': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['author']]) itemArr.append(item) elif fileData['collectionType'] == 'movie': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['director']]) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) print collection.collectionType print collection.collectionName print collection.username print collection.items def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main()
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/agarner_collections/agarner_Item_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) itemData = fileData['items'] itemArr = [] for value in itemData: item = ItemFactory.factory( fileData['collectionType'], value.values() ) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) for item in collection.items: print(item.id) def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main() Implement base json extraction to collection functionalityfrom DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory from collections import OrderedDict import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/TestUser_collections/TestUser_album_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) collectionType = fileData['collectionType'] collectionName = fileData['collectionName'] username = fileData['username'] itemData = fileData['items'] itemArr = [] for value in itemData: if fileData['collectionType'] == 'item': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit']]) itemArr.append(item) elif fileData['collectionType'] == 'album': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['artist']]) itemArr.append(item) elif fileData['collectionType'] == 'book': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['author']]) itemArr.append(item) elif fileData['collectionType'] == 'movie': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['director']]) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) print collection.collectionType print collection.collectionName print collection.username print collection.items def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main()
<commit_before>from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/agarner_collections/agarner_Item_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) itemData = fileData['items'] itemArr = [] for value in itemData: item = ItemFactory.factory( fileData['collectionType'], value.values() ) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) for item in collection.items: print(item.id) def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main() <commit_msg>Implement base json extraction to collection functionality<commit_after>from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory from collections import OrderedDict import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/TestUser_collections/TestUser_album_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) collectionType = fileData['collectionType'] collectionName = fileData['collectionName'] username = fileData['username'] itemData = fileData['items'] itemArr = [] for value in itemData: if fileData['collectionType'] == 'item': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit']]) itemArr.append(item) elif fileData['collectionType'] == 'album': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['artist']]) itemArr.append(item) elif fileData['collectionType'] == 'book': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['author']]) itemArr.append(item) elif fileData['collectionType'] == 'movie': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['director']]) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) print collection.collectionType print collection.collectionName print collection.username print collection.items def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main()