function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def OnInit(self): # Twisted Reactor Code reactor.startRunning() EVT_TIMER(self,999999,self.OnTimer) self.timer=wxTimer(self,999999) self.timer.Start(250,False) # End Twisted Code
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def __init__(self, interpreter, line): self.interpreter = interpreter self.line = line
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def Sync(runnable): if ExecState.PYDEV_CONSOLE_RUN_IN_UI: return RunInUiThread.sync(runnable) else: return runnable.run()
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def __init__(self, interpreter, line): self.interpreter = interpreter self.line = line
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def Sync(runnable): runnable.run()
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def __init__(self, host, client_port, server): BaseInterpreterInterface.__init__(self, server) self.client_port = client_port self.host = host try: import pydevd # @UnresolvedImport if pydevd.GetGlobalDebugger() is None: raise RuntimeError() # Work as if the debugger does not exist as it's not connected. except: self.namespace = globals() else: # Adapted from the code in pydevd # patch provided by: Scott Schlesier - when script is run, it does not # pretend pydevconsole is not the main module, and # convince the file to be debugged that it was loaded as main sys.modules['pydevconsole'] = sys.modules['__main__'] sys.modules['pydevconsole'].__name__ = 'pydevconsole' from imp import new_module m = new_module('__main__') sys.modules['__main__'] = m ns = m.__dict__ try: ns['__builtins__'] = __builtins__ except NameError: pass # Not there on Jython... self.namespace = ns self.interpreter = InteractiveConsole(self.namespace) self._input_error_printed = False
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def getNamespace(self): return self.namespace
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def close(self): sys.exit(0)
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def _DoExit(*args): ''' We have to override the exit because calling sys.exit will only actually exit the main thread, and as we're in a Xml-rpc server, that won't work. ''' try: import java.lang.System java.lang.System.exit(1) except ImportError: if len(args) == 1: os._exit(args[0]) else: os._exit(0)
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def StartServer(host, port, client_port): # replace exit (see comments on method) # note that this does not work in jython!!! (sys method can't be replaced). sys.exit = _DoExit from _pydev_xmlrpc_hook import InputHookedXMLRPCServer try: server = InputHookedXMLRPCServer((host, port), logRequests=False) interpreter = InterpreterInterface(host, client_port, server) except: sys.stderr.write('Error starting server with host: %s, port: %s, client_port: %s\n' % (host, port, client_port)) raise # Tell UMD the proper default namespace _set_globals_function(interpreter.getNamespace) # Functions for basic protocol server.register_function(interpreter.addExec) server.register_function(interpreter.getCompletions) server.register_function(interpreter.getDescription) server.register_function(interpreter.close) # Functions so that the console can work as a debugger (i.e.: variables view, expressions...) server.register_function(interpreter.connectToDebugger) server.register_function(interpreter.hello) # Functions for GUI main loop integration server.register_function(interpreter.enableGui) server.serve_forever()
aptana/Pydev
[ 239, 85, 239, 6, 1250792405 ]
def getPOSCAR(self): return self.getMinimized()
vanceeasleaf/aces
[ 19, 9, 19, 4, 1428476265 ]
def getMinimized(self): return """Mo N
vanceeasleaf/aces
[ 19, 9, 19, 4, 1428476265 ]
def __init__(self): modules = module_loader.load_modules('func/overlord/cmd_modules/', base_command.BaseCommand) for x in modules.keys(): self.subCommandClasses.append(modules[x].__class__) command.Command.__init__(self)
kadamski/func
[ 9, 2, 9, 1, 1211919894 ]
def addOptions(self): self.parser.add_option('', '--version', action="store_true", help="show version information")
kadamski/func
[ 9, 2, 9, 1, 1211919894 ]
def _isGlob(self, str): if str.find("*") or str.find("?") or str.find("[") or str.find("]"): return True return False
kadamski/func
[ 9, 2, 9, 1, 1211919894 ]
def handleArguments(self, args): if len(args) < 2: sys.stderr.write("see the func manpage for usage\n") sys.exit(411) minion_string = args[0] # try to be clever about this for now if client.is_minion(minion_string) or self._isGlob(minion_string): self.server_spec = minion_string args.pop(0) # if it doesn't look like server, assume it # is a sub command? that seems wrong, what about # typo's and such? How to catch that? -akl # maybe a class variable self.data on Command?
kadamski/func
[ 9, 2, 9, 1, 1211919894 ]
def __init__(self, name, uri, image=u'', fanart=u''): BaseItem.__init__(self, name, uri, image, fanart) self._duration = None self._track_number = None self._year = None self._genre = None self._album = None self._artist = None self._title = name self._rating = None
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def get_rating(self): return self._rating
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def get_title(self): return self._title
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def get_artist_name(self): return self._artist
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def get_album_name(self): return self._album
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def get_genre(self): return self._genre
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def set_year_from_datetime(self, date_time): self.set_year(date_time.year)
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def set_track_number(self, track_number): self._track_number = int(track_number)
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def set_duration_from_milli_seconds(self, milli_seconds): self.set_duration_from_seconds(int(milli_seconds) / 1000)
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def set_duration_from_minutes(self, minutes): self.set_duration_from_seconds(int(minutes) * 60)
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def to_grade_number(year): """Returns a `Grade` object for a year.""" return Grade(year).number
tjcsl/ion
[ 89, 57, 89, 90, 1408078781 ]
def index( self, trans, group_id, **kwd ): """ GET /api/groups/{encoded_group_id}/roles Displays a collection (list) of groups. """ decoded_group_id = trans.security.decode_id( group_id ) try: group = trans.sa_session.query( trans.app.model.Group ).get( decoded_group_id ) except: group = None if not group: trans.response.status = 400 return "Invalid group id ( %s ) specified." % str( group_id ) rval = [] try: for gra in group.roles: role = gra.role encoded_id = trans.security.encode_id( role.id ) rval.append( dict( id = encoded_id, name = role.name, url = url_for( 'group_role', group_id=group_id, id=encoded_id, ) ) ) except Exception, e: rval = "Error in group API at listing roles" log.error( rval + ": %s" % str(e) ) trans.response.status = 500 return rval
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def show( self, trans, id, group_id, **kwd ): """ GET /api/groups/{encoded_group_id}/roles/{encoded_role_id} Displays information about a group role. """ role_id = id decoded_group_id = trans.security.decode_id( group_id ) decoded_role_id = trans.security.decode_id( role_id ) item = None try: group = trans.sa_session.query( trans.app.model.Group ).get( decoded_group_id ) role = trans.sa_session.query( trans.app.model.Role ).get( decoded_role_id ) for gra in group.roles: if gra.role == role: item = dict( id = role_id, name = role.name, url = url_for( 'group_role', group_id=group_id, id=role_id) ) # TODO Fix This if not item: item = "role %s not in group %s" % (role.name,group.name) except Exception, e: item = "Error in group_role API group %s role %s" % (group.name, role.name) log.error(item + ": %s" % str(e)) return item
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def update( self, trans, id, group_id, **kwd ): """ PUT /api/groups/{encoded_group_id}/roles/{encoded_role_id} Adds a role to a group """ role_id = id decoded_group_id = trans.security.decode_id( group_id ) decoded_role_id = trans.security.decode_id( role_id ) item = None try: group = trans.sa_session.query( trans.app.model.Group ).get( decoded_group_id ) role = trans.sa_session.query( trans.app.model.Role ).get( decoded_role_id ) for gra in group.roles: if gra.role == role: item = dict( id = role_id, name = role.name, url = url_for( 'group_role', group_id=group_id, id=role_id) ) if not item: gra = trans.app.model.GroupRoleAssociation( group, role ) # Add GroupRoleAssociation trans.sa_session.add( gra ) trans.sa_session.flush() item = dict( id = role_id, name = role.name, url = url_for( 'group_role', group_id=group_id, id=role_id) ) except Exception, e: item = "Error in group_role API Adding role %s to group %s" % (role.name,group.name) log.error(item + ": %s" % str(e)) return item
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def test_creation(self): tag = 'Root' value = ' Value ' anAttr = 'elValue' new_value = 'New Value' node = Node(tag, value=value, anAttr=anAttr) self.assertEqual(node.tag, tag) self.assertDictEqual(node.attributes, {'anAttr': anAttr}) self.assertEqual(node.value, value.strip()) self.assertEqual(node[tag], value.strip()) node[tag] = new_value self.assertEqual(node.value, new_value)
nansencenter/nansat
[ 169, 65, 169, 91, 1374067434 ]
def test_insert(self): contents = ('<Element attr="attrValue"><Subnode>testValue</Subnode>' '</Element>') root = Node('root') root2 = root.insert(contents) element = root2.node('Element') rawElement = Node.create(contents) self.assertEqual(element.xml(), rawElement.xml())
nansencenter/nansat
[ 169, 65, 169, 91, 1374067434 ]
def test_delete_attribute(self): tag = 'Root' value = ' Value ' anAttr = 'elValue' node = Node(tag, value=value, anAttr=anAttr) self.assertIn('anAttr', node.attributes) node.delAttribute('anAttr') self.assertNotIn('anAttr', node.attributes)
nansencenter/nansat
[ 169, 65, 169, 91, 1374067434 ]
def test_add_nodes(self): rootTag = 'Root' root = Node(rootTag) firstLevelTag = 'FirstLevel' firstLevel = Node(firstLevelTag) root += firstLevel firstLevel2 = Node(firstLevelTag) root += firstLevel2 firstLevel2ndTag = 'FirstLevel2ndTag' firstLevel3 = Node(firstLevel2ndTag) root = root + firstLevel3 self.assertIn(firstLevel, root.children) self.assertIn(firstLevel2, root.children) self.assertIn(firstLevel3, root.children)
nansencenter/nansat
[ 169, 65, 169, 91, 1374067434 ]
def test_replace_node(self): rootTag = 'Root' root = Node(rootTag) firstLevelTag = 'FirstLevel' firstLevel = Node(firstLevelTag) root += firstLevel firstLevel2 = Node(firstLevelTag) root += firstLevel2 firstLevel2ndTag = 'FirstLevel2ndTag' firstLevel3 = Node(firstLevel2ndTag) root.replaceNode(firstLevelTag, 1, firstLevel3) self.assertIn(firstLevel, root.children) self.assertNotIn(firstLevel2, root.children) self.assertIn(firstLevel3, root.children) self.assertEqual(len(root.children), 2)
nansencenter/nansat
[ 169, 65, 169, 91, 1374067434 ]
def test_str(self): tag = 'Root' value = 'Value' node = Node(tag, value=value) self.assertEqual(str(node), '%s\n value: [%s]' % (tag, value))
nansencenter/nansat
[ 169, 65, 169, 91, 1374067434 ]
def convert_date(d: Dict[str, Any], key: str) -> None: """ Modifies ``d[key]``, if it exists, to convert it to a :class:`datetime.datetime` or ``None``. Args: d: dictionary key: key """ if key not in d: return value = d[key] if value: d[key] = datetime.datetime.strptime(value, YEAR_MONTH_FMT) else: d[key] = None
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def convert_float(d: Dict[str, Any], key: str) -> None: """ Modifies ``d[key]``, if it exists, to convert it to a float or ``None``. Args: d: dictionary key: key """ if key not in d: return value = d[key] if value is None or (isinstance(value, str) and not value.strip()): d[key] = None else: d[key] = float(value)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def commit_and_announce(session: Session) -> None: """ Commits an SQLAlchemy ORM session and says so. """ log.info("COMMIT") session.commit()
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __call__(self, *args, **kwargs) -> None: # Represents __init__... not sure I have this quite right, but it # appeases PyCharm; see populate_generic_lookup_table() pass
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __table__(self) -> Table: pass
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __tablename__(self) -> str: pass
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __filename__(self) -> str: pass
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: convert_date(kwargs, 'dointr') convert_date(kwargs, 'doterm') convert_int(kwargs, 'usertype') convert_int(kwargs, 'oseast1m') convert_int(kwargs, 'osnrth1m') convert_int(kwargs, 'osgrdind') convert_int(kwargs, 'streg') convert_int(kwargs, 'edind') convert_int(kwargs, 'imd') kwargs['pcd_nospace'] = kwargs['pcd'].replace(" ", "") super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'OAC11', 'oac11') rename_key(kwargs, 'Supergroup', 'supergroup_desc') rename_key(kwargs, 'Group', 'group_desc') rename_key(kwargs, 'Subgroup', 'subgroup_desc') kwargs['supergroup_code'] = kwargs['oac11'][0:1] kwargs['group_code'] = kwargs['oac11'][0:2] kwargs['subgroup_code'] = kwargs['oac11'] super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'BUA13CD', 'bua_code') rename_key(kwargs, 'BUA13NM', 'bua_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'BUASD13CD', 'buasd_code') rename_key(kwargs, 'BUASD13NM', 'buasd_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'WDCAS03CD', 'cas_ward_code') rename_key(kwargs, 'WDCAS03NM', 'cas_ward_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'CCG19CD', 'ccg_ons_code') rename_key(kwargs, 'CCG19CDH', 'ccg_ccg_code') rename_key(kwargs, 'CCG19NM', 'ccg_name') rename_key(kwargs, 'CCG19NMW', 'ccg_name_welsh') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'CTRY12CD', 'country_code') rename_key(kwargs, 'CTRY12CDO', 'country_code_old') rename_key(kwargs, 'CTRY12NM', 'country_name') rename_key(kwargs, 'CTRY12NMW', 'country_name_welsh') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'CTY19CD', 'county_code') rename_key(kwargs, 'CTY19NM', 'county_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'EER10CD', 'eer_code') rename_key(kwargs, 'EER10CDO', 'eer_code_old') rename_key(kwargs, 'EER10NM', 'eer_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'LSOA11CD', 'lsoa_code') rename_key(kwargs, 'LSOA11NM', 'lsoa_name') rename_key(kwargs, 'IMD15', 'imd_rank') convert_int(kwargs, 'imd_rank') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'DZ11CD', 'dz_code') rename_key(kwargs, 'IMD16', 'imd_rank') convert_int(kwargs, 'imd_rank') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'LSOA11CD', 'lsoa_code') rename_key(kwargs, 'LSOA11NM', 'lsoa_name') rename_key(kwargs, 'IMD14', 'imd_rank') convert_int(kwargs, 'imd_rank') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'LAU219CD', 'lau2_code') rename_key(kwargs, 'LAU219NM', 'lau2_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'LAD19CD', 'lad_code') rename_key(kwargs, 'LAD19NM', 'lad_name') rename_key(kwargs, 'LAD19NMW', 'lad_name_welsh') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'LEP17CD', 'lep_code') rename_key(kwargs, 'LEP17NM', 'lep_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'LSOA11CD', 'lsoa_code') rename_key(kwargs, 'LSOA11NM', 'lsoa_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'MSOA11CD', 'msoa_code') rename_key(kwargs, 'MSOA11NM', 'msoa_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'NPARK16CD', 'park_code') rename_key(kwargs, 'NPARK16NM', 'park_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'PARNCP18CD', 'parish_code') rename_key(kwargs, 'PARNCP18NM', 'parish_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'PCTCD', 'pct_code') rename_key(kwargs, 'PCTCDO', 'pct_code_old') rename_key(kwargs, 'PCTNM', 'pct_name') rename_key(kwargs, 'PCTNMW', 'pct_name_welsh') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'PFA15CD', 'pfa_code') rename_key(kwargs, 'PFA15NM', 'pfa_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'GOR10CD', 'gor_code') rename_key(kwargs, 'GOR10CDO', 'gor_code_old') rename_key(kwargs, 'GOR10NM', 'gor_name') rename_key(kwargs, 'GOR10NMW', 'gor_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'SSR95CD', 'ssr_code') rename_key(kwargs, 'SSR95NM', 'ssr_name') convert_int(kwargs, 'ssr_code') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'WDSTL05CD', 'ward_code') rename_key(kwargs, 'WDSTL05NM', 'ward_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'WD19CD', 'ward_code') rename_key(kwargs, 'WD19NM', 'ward_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'TTWA11CD', 'ttwa_code') rename_key(kwargs, 'TTWA11NM', 'ttwa_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'PCON14CD', 'pcon_code') rename_key(kwargs, 'PCON14NM', 'pcon_name') super().__init__(**kwargs)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def __init__(self, **kwargs: Any) -> None: rename_key(kwargs, 'LSOA11CD', 'lsoa_code') rename_key(kwargs, 'LSOA11NM', 'lsoa_name') rename_key(kwargs, 'BNGNORTH', 'bng_north') rename_key(kwargs, 'BNGEAST', 'bng_east') rename_key(kwargs, 'LONGITUDE', 'longitude') rename_key(kwargs, 'LATITUDE', 'latitude') # MySQL doesn't care if you pass a string to a numeric field, but # SQL server does. So: convert_int(kwargs, 'bng_north') convert_int(kwargs, 'bng_east') convert_float(kwargs, 'longitude') convert_float(kwargs, 'latitude') super().__init__(**kwargs) if not self.lsoa_code: raise ValueError("Can't have a blank lsoa_code")
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def populate_postcode_table(filename: str, session: Session, replace: bool = False, startswith: List[str] = None, reportevery: int = DEFAULT_REPORT_EVERY, commit: bool = True, commitevery: int = DEFAULT_COMMIT_EVERY) -> None: """ Populates the :class:`Postcode` table, which is very big, from Office of National Statistics Postcode Database (ONSPD) database that you have downloaded. Args: filename: CSV file to read session: SQLAlchemy ORM database session replace: replace tables even if they exist? (Otherwise, skip existing tables.) startswith: if specified, restrict to postcodes that start with one of these strings reportevery: report to the Python log every *n* rows commit: COMMIT the session once we've inserted the data? commitevery: if committing: commit every *n* rows inserted """ tablename = Postcode.__tablename__ # noinspection PyUnresolvedReferences table = Postcode.__table__ if not replace: engine = session.bind if engine.has_table(tablename): log.info(f"Table {tablename} exists; skipping") return log.info(f"Dropping/recreating table: {tablename}") table.drop(checkfirst=True) table.create(checkfirst=True) log.info(f"Using ONSPD data file: {filename}") n = 0 n_inserted = 0 extra_fields = [] # type: List[str] db_fields = sorted(k for k in table.columns.keys() if k != 'pcd_nospace') with open(filename) as csvfile: reader = csv.DictReader(csvfile) for row in reader: n += 1 if n % reportevery == 0: log.info(f"Processing row {n}: {row['pcds']} " f"({n_inserted} inserted)") # log.debug(row) if n == 1: file_fields = sorted(row.keys()) missing_fields = sorted(set(db_fields) - set(file_fields)) extra_fields = sorted(set(file_fields) - set(db_fields)) if missing_fields: log.warning( f"Fields in database but not file: {missing_fields}") if extra_fields: log.warning( f"Fields in file but not database : {extra_fields}") for k in extra_fields: del row[k] if startswith: ok = False for s in startswith: if row['pcd'].startswith(s): ok = True break if not ok: continue obj = Postcode(**row) session.add(obj) n_inserted += 1 if commit and n % commitevery == 0: commit_and_announce(session) if commit: commit_and_announce(session)
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def populate_generic_lookup_table( sa_class: GenericLookupClassType, datadir: str, session: Session, replace: bool = False, commit: bool = True, commitevery: int = DEFAULT_COMMIT_EVERY) -> None: """ Populates one of many generic lookup tables with ONSPD data. We find the data filename from the ``__filename__`` property of the specific class, hunting for it within ``datadir`` and its subdirectories. The ``.TXT`` files look at first glance like tab-separated values files, but in some cases have inconsistent numbers of tabs (e.g. "2011 Census Output Area Classification Names and Codes UK.txt"). So we'll use the ``.XLSX`` files. If the headings parameter is passed, those headings are used. Otherwise, the first row is used for headings. Args: sa_class: SQLAlchemy ORM class datadir: root directory of ONSPD data session: SQLAlchemy ORM database session replace: replace tables even if they exist? (Otherwise, skip existing tables.) commit: COMMIT the session once we've inserted the data? commitevery: if committing: commit every *n* rows inserted """ tablename = sa_class.__tablename__ filename = find_first(sa_class.__filename__, datadir) headings = getattr(sa_class, '__headings__', []) debug = getattr(sa_class, '__debug_content__', False) n = 0 if not replace: engine = session.bind if engine.has_table(tablename): log.info(f"Table {tablename} exists; skipping") return log.info(f"Dropping/recreating table: {tablename}") sa_class.__table__.drop(checkfirst=True) sa_class.__table__.create(checkfirst=True) log.info(f'Processing file "{filename}" -> table "{tablename}"') ext = os.path.splitext(filename)[1].lower() type_xlsx = ext in ['.xlsx'] type_csv = ext in ['.csv'] file = None # type: Optional[TextIO] def dict_from_rows(row_iterator: Iterable[List]) \ -> Generator[Dict, None, None]: local_headings = headings first_row = True for row in row_iterator: values = values_from_row(row) if first_row and not local_headings: local_headings = values else: yield dict(zip(local_headings, values)) first_row = False if type_xlsx: workbook = openpyxl.load_workbook(filename) # read_only=True # openpyxl BUG: with read_only=True, cells can have None as their value # when they're fine if opened in non-read-only mode. # May be related to this: # https://bitbucket.org/openpyxl/openpyxl/issues/601/read_only-cell-row-column-attributes-are # noqa sheet = workbook.active dict_iterator = dict_from_rows(sheet.iter_rows()) elif type_csv: file = open(filename, 'r') csv_reader = csv.DictReader(file) dict_iterator = csv_reader else: raise ValueError("Only XLSX and CSV these days") # workbook = xlrd.open_workbook(filename) # sheet = workbook.sheet_by_index(0) # dict_iterator = dict_from_rows(sheet.get_rows()) for datadict in dict_iterator: n += 1 if debug: log.critical(f"{n}: {datadict}") # filter out blanks: datadict = {k: v for k, v in datadict.items() if k} # noinspection PyNoneFunctionAssignment obj = sa_class(**datadict) session.add(obj) if commit and n % commitevery == 0: commit_and_announce(session) if commit: commit_and_announce(session) log.info(f"... inserted {n} rows") if file: file.close()
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def show_docs() -> None: """ Print the column ``doc`` attributes from the :class:`Postcode` class, in tabular form, to stdout. """ # noinspection PyUnresolvedReferences table = Postcode.__table__ columns = sorted(table.columns.keys()) pt = prettytable.PrettyTable( ["postcode field", "Description"], # header=False, border=True, hrules=prettytable.ALL, vrules=prettytable.NONE, ) pt.align = 'l' pt.valign = 't' pt.max_width = 80 for col in columns: doc = getattr(Postcode, col).doc doc = wordwrap(doc, width=70) ptrow = [col, doc] pt.add_row(ptrow) print(pt.get_string())
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def main() -> None: """ Command-line entry point. See command-line help. """ # noinspection PyTypeChecker parser = argparse.ArgumentParser( formatter_class=RawDescriptionArgumentDefaultsHelpFormatter, description=r"""
RudolfCardinal/crate
[ 12, 5, 12, 5, 1425998885 ]
def show_match(match_id: int) -> str: view = Match(match.get_match(match_id)) return view.page()
PennyDreadfulMTG/Penny-Dreadful-Discord-Bot
[ 33, 26, 33, 354, 1474960935 ]
def __init__(self, viewed_match: match.Match) -> None: super().__init__() if not viewed_match: raise DoesNotExistException() self.match = viewed_match self.id = viewed_match.id self.comment = viewed_match.comment self.format_name = viewed_match.format_name() self.players_string = ' vs '.join([p.name for p in viewed_match.players]) self.players_string_safe = ' vs '.join([player_link(p.name) for p in viewed_match.players]) self.module_string = ', '.join([m.name for m in viewed_match.modules]) if not viewed_match.games: self.no_games = True return self.game_one = viewed_match.games[0] self.has_game_two = False self.has_game_three = False if len(viewed_match.games) > 1: self.has_game_two = True self.game_two = viewed_match.games[1] if len(viewed_match.games) > 2: self.has_game_three = True self.game_three = viewed_match.games[2] if viewed_match.has_unexpected_third_game is None: importing.reimport(viewed_match) self.has_unexpected_third_game = viewed_match.has_unexpected_third_game if viewed_match.is_tournament is None: importing.reimport(viewed_match) self.is_tournament = viewed_match.is_tournament
PennyDreadfulMTG/Penny-Dreadful-Discord-Bot
[ 33, 26, 33, 354, 1474960935 ]
def og_url(self) -> str: return url_for('show_match', match_id=self.id, _external=True)
PennyDreadfulMTG/Penny-Dreadful-Discord-Bot
[ 33, 26, 33, 354, 1474960935 ]
def __init__(self, block_hasher): """ :type block_hasher: BlockHasher """ self.block_hasher=block_hasher
psy0rz/zfs_autobackup
[ 387, 49, 387, 18, 1446023195 ]
def walkerror(e): raise e
psy0rz/zfs_autobackup
[ 387, 49, 387, 18, 1446023195 ]
def test_degree_mixing_dict_undirected(self): d = nx.degree_mixing_dict(self.P4) d_result = { 1: {2: 2}, 2: {1: 2, 2: 2}, } assert d == d_result
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_degree_mixing_dict_directed(self): d = nx.degree_mixing_dict(self.D) print(d) d_result = {1: {3: 2}, 2: {1: 1, 3: 1}, 3: {}} assert d == d_result
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_degree_mixing_matrix_undirected(self): # fmt: off a_result = np.array([[0, 0, 0], [0, 0, 2], [0, 2, 2]] ) # fmt: on a = nx.degree_mixing_matrix(self.P4, normalized=False) npt.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.P4) npt.assert_equal(a, a_result / float(a_result.sum()))
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_degree_mixing_matrix_multigraph(self): # fmt: off a_result = np.array([[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 3], [0, 0, 3, 0]] ) # fmt: on a = nx.degree_mixing_matrix(self.M, normalized=False) npt.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.M) npt.assert_equal(a, a_result / float(a_result.sum()))
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_attribute_mixing_dict_undirected(self): d = nx.attribute_mixing_dict(self.G, "fish") d_result = { "one": {"one": 2, "red": 1}, "two": {"two": 2, "blue": 1}, "red": {"one": 1}, "blue": {"two": 1}, } assert d == d_result
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_attribute_mixing_dict_multigraph(self): d = nx.attribute_mixing_dict(self.M, "fish") d_result = { "one": {"one": 4}, "two": {"two": 2}, } assert d == d_result
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_attribute_mixing_matrix_undirected(self): mapping = {"one": 0, "two": 1, "red": 2, "blue": 3} a_result = np.array([[2, 0, 1, 0], [0, 2, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]]) a = nx.attribute_mixing_matrix( self.G, "fish", mapping=mapping, normalized=False ) npt.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.G, "fish", mapping=mapping) npt.assert_equal(a, a_result / float(a_result.sum()))
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def __init__(self, proc, p_args): super().__init__() self._proc = proc self._args = p_args self.errored = False self.error_msg = None
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def validate_byond_build(byond_str): """ A little shit of a failed command argument.
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def __init__(self, bot): self.bot = bot self._instances = [] self._safety_patterns = [r'#(\s*)?include', r'include', r'##', r'```.*```', r'`.*`', r'Reboot'] self._safety_expressions = [] self._arg_expression = re.compile(r'(?:(?P<pre_proc>.*);;;)?(?:(?P<proc>.*);;)?(?P<to_out>.*)?') for patt in self._safety_patterns: self._safety_expressions.append(re.compile(patt))
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def new_instance(self, length): """Generates a unique instance ID, one which is currently not in use.""" while True: rand = "".join([random.choice(string.ascii_letters + string.digits) for _ in range(length)]) if rand not in self._instances: self._instances.append(rand) return rand
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def process_args(self, code): """ Generates an array of code segments to be placed into the compiled DM code.
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def validate_dm(self, code): """Validates the code given for potential exploits.""" for expr in self._safety_expressions: if expr.search(code): raise BotError("Disallowed/dangerous code found. Aborting.", "validate_dm")
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def validate_compile(self, instance_dir): """Checks wether or not the compiled end result is safe to run.""" dmb_found = False for fname in os.listdir(instance_dir): if fname.endswith(".rsc"): raise BotError("Resource file detected. Execution aborted.", "validate_compile") elif fname.endswith(".dmb"): dmb_found = True if not dmb_found: raise BotError("Compilation failed and no .dmb was generated.", "validate_compile")
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def get_output(self, instance_dir): """Returns a string containing the first 30 lines from the test instance's log.""" log_path = os.path.join(instance_dir, "output.log") if not os.path.isfile(log_path): return "Error: no log file found." with open(log_path, "r") as file: content = file.readlines() if len(content) < 2: return "No contents found in the log file." content = [x.strip() for x in content] content = content[1:11] content = "\n".join(content)
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def byond_found(self, major=DEFAULT_MAJOR, minor=DEFAULT_MINOR): """Checks whether or not the specified version is already found in the test folder.""" path = self.get_work_dir() byond_path = os.path.join(path, f"byond{major}.{minor}") if os.path.isdir(byond_path) and os.path.isfile(f"{byond_path}\\byond\\bin\\dm.exe"): return True return False
Aurorastation/BOREALISbot2
[ 2, 8, 2, 4, 1468354854 ]
def setUp(self): # noqa self.set_prefix_and_model( "/maps", MAP_TYPE, TopoMap, ArchiveTopoMap, ArchiveDocumentLocale) BaseDocumentTestRest.setUp(self) self._add_test_data()
c2corg/v6_api
[ 21, 18, 21, 89, 1439983299 ]
def test_get_collection_paginated(self): self.app.get("/maps?offset=invalid", status=400) self.assertResultsEqual( self.get_collection({'offset': 0, 'limit': 0}), [], 4) self.assertResultsEqual( self.get_collection({'offset': 0, 'limit': 1}), [self.map4.document_id], 4) self.assertResultsEqual( self.get_collection({'offset': 0, 'limit': 2}), [self.map4.document_id, self.map3.document_id], 4) self.assertResultsEqual( self.get_collection({'offset': 1, 'limit': 2}), [self.map3.document_id, self.map2.document_id], 4)
c2corg/v6_api
[ 21, 18, 21, 89, 1439983299 ]
def test_get_collection_search(self): reset_search_index(self.session) self.assertResultsEqual( self.get_collection_search({'l': 'en'}), [self.map4.document_id, self.map1.document_id], 2)
c2corg/v6_api
[ 21, 18, 21, 89, 1439983299 ]
def test_get_cooked(self): self.get_cooked(self.map1)
c2corg/v6_api
[ 21, 18, 21, 89, 1439983299 ]