code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def build_template(self, mapfile, names, renderer): """ Build source from global and item templates """ AVAILABLE_DUMPS = json.load(open(mapfile, "r")) manager = self.get_deps_manager(AVAILABLE_DUMPS) fp = StringIO.StringIO() for i, item in enumerate(manager.get_dump_order(names), start=1): fp = renderer(fp, i, item, manager[item]) if self.dump_other_apps: exclude_models = ['-e {0}'.format(app) for app in self.exclude_apps] for i, item in enumerate(manager.get_dump_order(names), start=1): for model in manager[item]['models']: if '-e ' not in model: model = "-e {0}".format(model) if model not in exclude_models: exclude_models.append(model) fp = renderer(fp, i+1, 'other_apps', {'models': exclude_models, 'use_natural_key': True}) content = fp.getvalue() fp.close() context = self.get_global_context().copy() context.update({'items': content}) return self.base_template.format(**context)
def function[build_template, parameter[self, mapfile, names, renderer]]: constant[ Build source from global and item templates ] variable[AVAILABLE_DUMPS] assign[=] call[name[json].load, parameter[call[name[open], parameter[name[mapfile], constant[r]]]]] variable[manager] assign[=] call[name[self].get_deps_manager, parameter[name[AVAILABLE_DUMPS]]] variable[fp] assign[=] call[name[StringIO].StringIO, parameter[]] for taget[tuple[[<ast.Name object at 0x7da18f00fbb0>, <ast.Name object at 0x7da18f00ebc0>]]] in starred[call[name[enumerate], parameter[call[name[manager].get_dump_order, parameter[name[names]]]]]] begin[:] variable[fp] assign[=] call[name[renderer], parameter[name[fp], name[i], name[item], call[name[manager]][name[item]]]] if name[self].dump_other_apps begin[:] variable[exclude_models] assign[=] <ast.ListComp object at 0x7da18f00c520> for taget[tuple[[<ast.Name object at 0x7da18f00f880>, <ast.Name object at 0x7da18f00c5b0>]]] in starred[call[name[enumerate], parameter[call[name[manager].get_dump_order, parameter[name[names]]]]]] begin[:] for taget[name[model]] in starred[call[call[name[manager]][name[item]]][constant[models]]] begin[:] if compare[constant[-e ] <ast.NotIn object at 0x7da2590d7190> name[model]] begin[:] variable[model] assign[=] call[constant[-e {0}].format, parameter[name[model]]] if compare[name[model] <ast.NotIn object at 0x7da2590d7190> name[exclude_models]] begin[:] call[name[exclude_models].append, parameter[name[model]]] variable[fp] assign[=] call[name[renderer], parameter[name[fp], binary_operation[name[i] + constant[1]], constant[other_apps], dictionary[[<ast.Constant object at 0x7da20c6c5a80>, <ast.Constant object at 0x7da20c6c4a60>], [<ast.Name object at 0x7da20c6c5030>, <ast.Constant object at 0x7da20c6c5570>]]]] variable[content] assign[=] call[name[fp].getvalue, parameter[]] call[name[fp].close, parameter[]] variable[context] assign[=] call[call[name[self].get_global_context, parameter[]].copy, parameter[]] call[name[context].update, parameter[dictionary[[<ast.Constant object at 0x7da20c6c7d60>], [<ast.Name object at 0x7da20c6c5e70>]]]] return[call[name[self].base_template.format, parameter[]]]
keyword[def] identifier[build_template] ( identifier[self] , identifier[mapfile] , identifier[names] , identifier[renderer] ): literal[string] identifier[AVAILABLE_DUMPS] = identifier[json] . identifier[load] ( identifier[open] ( identifier[mapfile] , literal[string] )) identifier[manager] = identifier[self] . identifier[get_deps_manager] ( identifier[AVAILABLE_DUMPS] ) identifier[fp] = identifier[StringIO] . identifier[StringIO] () keyword[for] identifier[i] , identifier[item] keyword[in] identifier[enumerate] ( identifier[manager] . identifier[get_dump_order] ( identifier[names] ), identifier[start] = literal[int] ): identifier[fp] = identifier[renderer] ( identifier[fp] , identifier[i] , identifier[item] , identifier[manager] [ identifier[item] ]) keyword[if] identifier[self] . identifier[dump_other_apps] : identifier[exclude_models] =[ literal[string] . identifier[format] ( identifier[app] ) keyword[for] identifier[app] keyword[in] identifier[self] . identifier[exclude_apps] ] keyword[for] identifier[i] , identifier[item] keyword[in] identifier[enumerate] ( identifier[manager] . identifier[get_dump_order] ( identifier[names] ), identifier[start] = literal[int] ): keyword[for] identifier[model] keyword[in] identifier[manager] [ identifier[item] ][ literal[string] ]: keyword[if] literal[string] keyword[not] keyword[in] identifier[model] : identifier[model] = literal[string] . identifier[format] ( identifier[model] ) keyword[if] identifier[model] keyword[not] keyword[in] identifier[exclude_models] : identifier[exclude_models] . identifier[append] ( identifier[model] ) identifier[fp] = identifier[renderer] ( identifier[fp] , identifier[i] + literal[int] , literal[string] ,{ literal[string] : identifier[exclude_models] , literal[string] : keyword[True] }) identifier[content] = identifier[fp] . identifier[getvalue] () identifier[fp] . identifier[close] () identifier[context] = identifier[self] . identifier[get_global_context] (). identifier[copy] () identifier[context] . identifier[update] ({ literal[string] : identifier[content] }) keyword[return] identifier[self] . identifier[base_template] . identifier[format] (** identifier[context] )
def build_template(self, mapfile, names, renderer): """ Build source from global and item templates """ AVAILABLE_DUMPS = json.load(open(mapfile, 'r')) manager = self.get_deps_manager(AVAILABLE_DUMPS) fp = StringIO.StringIO() for (i, item) in enumerate(manager.get_dump_order(names), start=1): fp = renderer(fp, i, item, manager[item]) # depends on [control=['for'], data=[]] if self.dump_other_apps: exclude_models = ['-e {0}'.format(app) for app in self.exclude_apps] for (i, item) in enumerate(manager.get_dump_order(names), start=1): for model in manager[item]['models']: if '-e ' not in model: model = '-e {0}'.format(model) # depends on [control=['if'], data=['model']] if model not in exclude_models: exclude_models.append(model) # depends on [control=['if'], data=['model', 'exclude_models']] # depends on [control=['for'], data=['model']] # depends on [control=['for'], data=[]] fp = renderer(fp, i + 1, 'other_apps', {'models': exclude_models, 'use_natural_key': True}) # depends on [control=['if'], data=[]] content = fp.getvalue() fp.close() context = self.get_global_context().copy() context.update({'items': content}) return self.base_template.format(**context)
def wait_for_zero_canvases(middle_mouse_close=False): """ Wait for all canvases to be closed, or CTRL-c. If `middle_mouse_close`, middle click will shut the canvas. incpy.ignore """ if not __ACTIVE: wait_failover(wait_for_zero_canvases) return @dispatcher def count_canvases(): """ Count the number of active canvases and finish gApplication.Run() if there are none remaining. incpy.ignore """ if not get_visible_canvases(): try: ROOT.gSystem.ExitLoop() except AttributeError: # We might be exiting and ROOT.gROOT will raise an AttributeError pass @dispatcher def exit_application_loop(): """ Signal handler for CTRL-c to cause gApplication.Run() to finish. incpy.ignore """ ROOT.gSystem.ExitLoop() # Handle CTRL-c sh = ROOT.TSignalHandler(ROOT.kSigInterrupt, True) sh.Add() sh.Connect("Notified()", "TPyDispatcher", exit_application_loop, "Dispatch()") visible_canvases = get_visible_canvases() for canvas in visible_canvases: log.debug("waiting for canvas {0} to close".format(canvas.GetName())) canvas.Update() if middle_mouse_close: attach_event_handler(canvas) if not getattr(canvas, "_py_close_dispatcher_attached", False): # Attach a handler only once to each canvas canvas._py_close_dispatcher_attached = True canvas.Connect("Closed()", "TPyDispatcher", count_canvases, "Dispatch()") keepalive(canvas, count_canvases) if visible_canvases and not ROOT.gROOT.IsBatch(): run_application_until_done() # Disconnect from canvases for canvas in visible_canvases: if getattr(canvas, "_py_close_dispatcher_attached", False): canvas._py_close_dispatcher_attached = False canvas.Disconnect("Closed()", count_canvases, "Dispatch()")
def function[wait_for_zero_canvases, parameter[middle_mouse_close]]: constant[ Wait for all canvases to be closed, or CTRL-c. If `middle_mouse_close`, middle click will shut the canvas. incpy.ignore ] if <ast.UnaryOp object at 0x7da1b11bf3a0> begin[:] call[name[wait_failover], parameter[name[wait_for_zero_canvases]]] return[None] def function[count_canvases, parameter[]]: constant[ Count the number of active canvases and finish gApplication.Run() if there are none remaining. incpy.ignore ] if <ast.UnaryOp object at 0x7da1b11be200> begin[:] <ast.Try object at 0x7da1b11bca00> def function[exit_application_loop, parameter[]]: constant[ Signal handler for CTRL-c to cause gApplication.Run() to finish. incpy.ignore ] call[name[ROOT].gSystem.ExitLoop, parameter[]] variable[sh] assign[=] call[name[ROOT].TSignalHandler, parameter[name[ROOT].kSigInterrupt, constant[True]]] call[name[sh].Add, parameter[]] call[name[sh].Connect, parameter[constant[Notified()], constant[TPyDispatcher], name[exit_application_loop], constant[Dispatch()]]] variable[visible_canvases] assign[=] call[name[get_visible_canvases], parameter[]] for taget[name[canvas]] in starred[name[visible_canvases]] begin[:] call[name[log].debug, parameter[call[constant[waiting for canvas {0} to close].format, parameter[call[name[canvas].GetName, parameter[]]]]]] call[name[canvas].Update, parameter[]] if name[middle_mouse_close] begin[:] call[name[attach_event_handler], parameter[name[canvas]]] if <ast.UnaryOp object at 0x7da1b1192f50> begin[:] name[canvas]._py_close_dispatcher_attached assign[=] constant[True] call[name[canvas].Connect, parameter[constant[Closed()], constant[TPyDispatcher], name[count_canvases], constant[Dispatch()]]] call[name[keepalive], parameter[name[canvas], name[count_canvases]]] if <ast.BoolOp object at 0x7da1b1192320> begin[:] call[name[run_application_until_done], parameter[]] for taget[name[canvas]] in starred[name[visible_canvases]] begin[:] if call[name[getattr], parameter[name[canvas], constant[_py_close_dispatcher_attached], constant[False]]] begin[:] name[canvas]._py_close_dispatcher_attached assign[=] constant[False] call[name[canvas].Disconnect, parameter[constant[Closed()], name[count_canvases], constant[Dispatch()]]]
keyword[def] identifier[wait_for_zero_canvases] ( identifier[middle_mouse_close] = keyword[False] ): literal[string] keyword[if] keyword[not] identifier[__ACTIVE] : identifier[wait_failover] ( identifier[wait_for_zero_canvases] ) keyword[return] @ identifier[dispatcher] keyword[def] identifier[count_canvases] (): literal[string] keyword[if] keyword[not] identifier[get_visible_canvases] (): keyword[try] : identifier[ROOT] . identifier[gSystem] . identifier[ExitLoop] () keyword[except] identifier[AttributeError] : keyword[pass] @ identifier[dispatcher] keyword[def] identifier[exit_application_loop] (): literal[string] identifier[ROOT] . identifier[gSystem] . identifier[ExitLoop] () identifier[sh] = identifier[ROOT] . identifier[TSignalHandler] ( identifier[ROOT] . identifier[kSigInterrupt] , keyword[True] ) identifier[sh] . identifier[Add] () identifier[sh] . identifier[Connect] ( literal[string] , literal[string] , identifier[exit_application_loop] , literal[string] ) identifier[visible_canvases] = identifier[get_visible_canvases] () keyword[for] identifier[canvas] keyword[in] identifier[visible_canvases] : identifier[log] . identifier[debug] ( literal[string] . identifier[format] ( identifier[canvas] . identifier[GetName] ())) identifier[canvas] . identifier[Update] () keyword[if] identifier[middle_mouse_close] : identifier[attach_event_handler] ( identifier[canvas] ) keyword[if] keyword[not] identifier[getattr] ( identifier[canvas] , literal[string] , keyword[False] ): identifier[canvas] . identifier[_py_close_dispatcher_attached] = keyword[True] identifier[canvas] . identifier[Connect] ( literal[string] , literal[string] , identifier[count_canvases] , literal[string] ) identifier[keepalive] ( identifier[canvas] , identifier[count_canvases] ) keyword[if] identifier[visible_canvases] keyword[and] keyword[not] identifier[ROOT] . identifier[gROOT] . identifier[IsBatch] (): identifier[run_application_until_done] () keyword[for] identifier[canvas] keyword[in] identifier[visible_canvases] : keyword[if] identifier[getattr] ( identifier[canvas] , literal[string] , keyword[False] ): identifier[canvas] . identifier[_py_close_dispatcher_attached] = keyword[False] identifier[canvas] . identifier[Disconnect] ( literal[string] , identifier[count_canvases] , literal[string] )
def wait_for_zero_canvases(middle_mouse_close=False): """ Wait for all canvases to be closed, or CTRL-c. If `middle_mouse_close`, middle click will shut the canvas. incpy.ignore """ if not __ACTIVE: wait_failover(wait_for_zero_canvases) return # depends on [control=['if'], data=[]] @dispatcher def count_canvases(): """ Count the number of active canvases and finish gApplication.Run() if there are none remaining. incpy.ignore """ if not get_visible_canvases(): try: ROOT.gSystem.ExitLoop() # depends on [control=['try'], data=[]] except AttributeError: # We might be exiting and ROOT.gROOT will raise an AttributeError pass # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] @dispatcher def exit_application_loop(): """ Signal handler for CTRL-c to cause gApplication.Run() to finish. incpy.ignore """ ROOT.gSystem.ExitLoop() # Handle CTRL-c sh = ROOT.TSignalHandler(ROOT.kSigInterrupt, True) sh.Add() sh.Connect('Notified()', 'TPyDispatcher', exit_application_loop, 'Dispatch()') visible_canvases = get_visible_canvases() for canvas in visible_canvases: log.debug('waiting for canvas {0} to close'.format(canvas.GetName())) canvas.Update() if middle_mouse_close: attach_event_handler(canvas) # depends on [control=['if'], data=[]] if not getattr(canvas, '_py_close_dispatcher_attached', False): # Attach a handler only once to each canvas canvas._py_close_dispatcher_attached = True canvas.Connect('Closed()', 'TPyDispatcher', count_canvases, 'Dispatch()') keepalive(canvas, count_canvases) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['canvas']] if visible_canvases and (not ROOT.gROOT.IsBatch()): run_application_until_done() # Disconnect from canvases for canvas in visible_canvases: if getattr(canvas, '_py_close_dispatcher_attached', False): canvas._py_close_dispatcher_attached = False canvas.Disconnect('Closed()', count_canvases, 'Dispatch()') # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['canvas']] # depends on [control=['if'], data=[]]
def start(self): """Launch this postgres server. If it's already running, do nothing. If the backing storage directory isn't configured, raise NotInitializedError. This method is optional. If you're running in an environment where the DBMS is provided as part of the basic infrastructure, you probably want to skip this step! """ log.info('Starting PostgreSQL at %s:%s', self.host, self.port) if not self.base_pathname: tmpl = ('Invalid base_pathname: %r. Did you forget to call ' '.initdb()?') raise NotInitializedError(tmpl % self.base_pathname) conf_file = os.path.join(self.base_pathname, 'postgresql.conf') if not os.path.exists(conf_file): tmpl = 'No config file at: %r. Did you forget to call .initdb()?' raise NotInitializedError(tmpl % self.base_pathname) if not self.is_running(): version = self.get_version() if version and version >= (9, 3): socketop = 'unix_socket_directories' else: socketop = 'unix_socket_directory' postgres_options = [ # When running not as root, postgres might try to put files # where they're not writable (see # https://paste.yougov.net/YKdgi). So set the socket_dir. '-c', '{}={}'.format(socketop, self.base_pathname), '-h', self.host, '-i', # enable TCP/IP connections '-p', self.port, ] subprocess.check_call([ PostgresFinder.find_root() / 'pg_ctl', 'start', '-D', self.base_pathname, '-l', os.path.join(self.base_pathname, 'postgresql.log'), '-o', subprocess.list2cmdline(postgres_options), ]) # Postgres may launch, then abort if it's unhappy with some parameter. # This post-launch test helps us decide. if not self.is_running(): tmpl = ('%s aborted immediately after launch, check ' 'postgresql.log in storage dir') raise RuntimeError(tmpl % self)
def function[start, parameter[self]]: constant[Launch this postgres server. If it's already running, do nothing. If the backing storage directory isn't configured, raise NotInitializedError. This method is optional. If you're running in an environment where the DBMS is provided as part of the basic infrastructure, you probably want to skip this step! ] call[name[log].info, parameter[constant[Starting PostgreSQL at %s:%s], name[self].host, name[self].port]] if <ast.UnaryOp object at 0x7da1b0b3b6a0> begin[:] variable[tmpl] assign[=] constant[Invalid base_pathname: %r. Did you forget to call .initdb()?] <ast.Raise object at 0x7da1b0b3a350> variable[conf_file] assign[=] call[name[os].path.join, parameter[name[self].base_pathname, constant[postgresql.conf]]] if <ast.UnaryOp object at 0x7da1b0b38d30> begin[:] variable[tmpl] assign[=] constant[No config file at: %r. Did you forget to call .initdb()?] <ast.Raise object at 0x7da1b0b396c0> if <ast.UnaryOp object at 0x7da1b0b38f70> begin[:] variable[version] assign[=] call[name[self].get_version, parameter[]] if <ast.BoolOp object at 0x7da18f09dcf0> begin[:] variable[socketop] assign[=] constant[unix_socket_directories] variable[postgres_options] assign[=] list[[<ast.Constant object at 0x7da18f09f340>, <ast.Call object at 0x7da18f09c7c0>, <ast.Constant object at 0x7da18f09cd90>, <ast.Attribute object at 0x7da18f09d8a0>, <ast.Constant object at 0x7da1b0b3ace0>, <ast.Constant object at 0x7da1b0b3b700>, <ast.Attribute object at 0x7da1b0b39960>]] call[name[subprocess].check_call, parameter[list[[<ast.BinOp object at 0x7da1b0b39b40>, <ast.Constant object at 0x7da1b0b3ab30>, <ast.Constant object at 0x7da1b0b38640>, <ast.Attribute object at 0x7da1b0b39d20>, <ast.Constant object at 0x7da1b0b39e70>, <ast.Call object at 0x7da1b0b39c00>, <ast.Constant object at 0x7da1b0b3b280>, <ast.Call object at 0x7da1b0b39510>]]]] if <ast.UnaryOp object at 0x7da1b0b3b370> begin[:] variable[tmpl] assign[=] constant[%s aborted immediately after launch, check postgresql.log in storage dir] <ast.Raise object at 0x7da1b0b3a950>
keyword[def] identifier[start] ( identifier[self] ): literal[string] identifier[log] . identifier[info] ( literal[string] , identifier[self] . identifier[host] , identifier[self] . identifier[port] ) keyword[if] keyword[not] identifier[self] . identifier[base_pathname] : identifier[tmpl] =( literal[string] literal[string] ) keyword[raise] identifier[NotInitializedError] ( identifier[tmpl] % identifier[self] . identifier[base_pathname] ) identifier[conf_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[base_pathname] , literal[string] ) keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[conf_file] ): identifier[tmpl] = literal[string] keyword[raise] identifier[NotInitializedError] ( identifier[tmpl] % identifier[self] . identifier[base_pathname] ) keyword[if] keyword[not] identifier[self] . identifier[is_running] (): identifier[version] = identifier[self] . identifier[get_version] () keyword[if] identifier[version] keyword[and] identifier[version] >=( literal[int] , literal[int] ): identifier[socketop] = literal[string] keyword[else] : identifier[socketop] = literal[string] identifier[postgres_options] =[ literal[string] , literal[string] . identifier[format] ( identifier[socketop] , identifier[self] . identifier[base_pathname] ), literal[string] , identifier[self] . identifier[host] , literal[string] , literal[string] , identifier[self] . identifier[port] , ] identifier[subprocess] . identifier[check_call] ([ identifier[PostgresFinder] . identifier[find_root] ()/ literal[string] , literal[string] , literal[string] , identifier[self] . identifier[base_pathname] , literal[string] , identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[base_pathname] , literal[string] ), literal[string] , identifier[subprocess] . identifier[list2cmdline] ( identifier[postgres_options] ), ]) keyword[if] keyword[not] identifier[self] . identifier[is_running] (): identifier[tmpl] =( literal[string] literal[string] ) keyword[raise] identifier[RuntimeError] ( identifier[tmpl] % identifier[self] )
def start(self): """Launch this postgres server. If it's already running, do nothing. If the backing storage directory isn't configured, raise NotInitializedError. This method is optional. If you're running in an environment where the DBMS is provided as part of the basic infrastructure, you probably want to skip this step! """ log.info('Starting PostgreSQL at %s:%s', self.host, self.port) if not self.base_pathname: tmpl = 'Invalid base_pathname: %r. Did you forget to call .initdb()?' raise NotInitializedError(tmpl % self.base_pathname) # depends on [control=['if'], data=[]] conf_file = os.path.join(self.base_pathname, 'postgresql.conf') if not os.path.exists(conf_file): tmpl = 'No config file at: %r. Did you forget to call .initdb()?' raise NotInitializedError(tmpl % self.base_pathname) # depends on [control=['if'], data=[]] if not self.is_running(): version = self.get_version() if version and version >= (9, 3): socketop = 'unix_socket_directories' # depends on [control=['if'], data=[]] else: socketop = 'unix_socket_directory' # When running not as root, postgres might try to put files # where they're not writable (see # https://paste.yougov.net/YKdgi). So set the socket_dir. # enable TCP/IP connections postgres_options = ['-c', '{}={}'.format(socketop, self.base_pathname), '-h', self.host, '-i', '-p', self.port] subprocess.check_call([PostgresFinder.find_root() / 'pg_ctl', 'start', '-D', self.base_pathname, '-l', os.path.join(self.base_pathname, 'postgresql.log'), '-o', subprocess.list2cmdline(postgres_options)]) # depends on [control=['if'], data=[]] # Postgres may launch, then abort if it's unhappy with some parameter. # This post-launch test helps us decide. if not self.is_running(): tmpl = '%s aborted immediately after launch, check postgresql.log in storage dir' raise RuntimeError(tmpl % self) # depends on [control=['if'], data=[]]
def resizeEvent(self, event): """Schedules an item layout if resize mode is \"adjust\". Somehow this is needed for correctly scaling down items. The reason this was reimplemented was the CommentDelegate. :param event: the resize event :type event: QtCore.QEvent :returns: None :rtype: None :raises: None """ if self.resizeMode() == self.Adjust: self.scheduleDelayedItemsLayout() return super(ListLevel, self).resizeEvent(event)
def function[resizeEvent, parameter[self, event]]: constant[Schedules an item layout if resize mode is "adjust". Somehow this is needed for correctly scaling down items. The reason this was reimplemented was the CommentDelegate. :param event: the resize event :type event: QtCore.QEvent :returns: None :rtype: None :raises: None ] if compare[call[name[self].resizeMode, parameter[]] equal[==] name[self].Adjust] begin[:] call[name[self].scheduleDelayedItemsLayout, parameter[]] return[call[call[name[super], parameter[name[ListLevel], name[self]]].resizeEvent, parameter[name[event]]]]
keyword[def] identifier[resizeEvent] ( identifier[self] , identifier[event] ): literal[string] keyword[if] identifier[self] . identifier[resizeMode] ()== identifier[self] . identifier[Adjust] : identifier[self] . identifier[scheduleDelayedItemsLayout] () keyword[return] identifier[super] ( identifier[ListLevel] , identifier[self] ). identifier[resizeEvent] ( identifier[event] )
def resizeEvent(self, event): """Schedules an item layout if resize mode is "adjust". Somehow this is needed for correctly scaling down items. The reason this was reimplemented was the CommentDelegate. :param event: the resize event :type event: QtCore.QEvent :returns: None :rtype: None :raises: None """ if self.resizeMode() == self.Adjust: self.scheduleDelayedItemsLayout() # depends on [control=['if'], data=[]] return super(ListLevel, self).resizeEvent(event)
def nii_gzip(imfile, outpath=''): '''Compress *.gz file''' import gzip with open(imfile, 'rb') as f: d = f.read() # Now store the compressed data if outpath=='': fout = imfile+'.gz' else: fout = os.path.join(outpath, os.path.basename(imfile)+'.gz') # store compressed file data from 'd' variable with gzip.open(fout, 'wb') as f: f.write(d) return fout
def function[nii_gzip, parameter[imfile, outpath]]: constant[Compress *.gz file] import module[gzip] with call[name[open], parameter[name[imfile], constant[rb]]] begin[:] variable[d] assign[=] call[name[f].read, parameter[]] if compare[name[outpath] equal[==] constant[]] begin[:] variable[fout] assign[=] binary_operation[name[imfile] + constant[.gz]] with call[name[gzip].open, parameter[name[fout], constant[wb]]] begin[:] call[name[f].write, parameter[name[d]]] return[name[fout]]
keyword[def] identifier[nii_gzip] ( identifier[imfile] , identifier[outpath] = literal[string] ): literal[string] keyword[import] identifier[gzip] keyword[with] identifier[open] ( identifier[imfile] , literal[string] ) keyword[as] identifier[f] : identifier[d] = identifier[f] . identifier[read] () keyword[if] identifier[outpath] == literal[string] : identifier[fout] = identifier[imfile] + literal[string] keyword[else] : identifier[fout] = identifier[os] . identifier[path] . identifier[join] ( identifier[outpath] , identifier[os] . identifier[path] . identifier[basename] ( identifier[imfile] )+ literal[string] ) keyword[with] identifier[gzip] . identifier[open] ( identifier[fout] , literal[string] ) keyword[as] identifier[f] : identifier[f] . identifier[write] ( identifier[d] ) keyword[return] identifier[fout]
def nii_gzip(imfile, outpath=''): """Compress *.gz file""" import gzip with open(imfile, 'rb') as f: d = f.read() # depends on [control=['with'], data=['f']] # Now store the compressed data if outpath == '': fout = imfile + '.gz' # depends on [control=['if'], data=[]] else: fout = os.path.join(outpath, os.path.basename(imfile) + '.gz') # store compressed file data from 'd' variable with gzip.open(fout, 'wb') as f: f.write(d) # depends on [control=['with'], data=['f']] return fout
def create_scraper(cls, sess=None, **kwargs): """ Convenience function for creating a ready-to-go CloudflareScraper object. """ scraper = cls(**kwargs) if sess: attrs = ["auth", "cert", "cookies", "headers", "hooks", "params", "proxies", "data"] for attr in attrs: val = getattr(sess, attr, None) if val: setattr(scraper, attr, val) return scraper
def function[create_scraper, parameter[cls, sess]]: constant[ Convenience function for creating a ready-to-go CloudflareScraper object. ] variable[scraper] assign[=] call[name[cls], parameter[]] if name[sess] begin[:] variable[attrs] assign[=] list[[<ast.Constant object at 0x7da1b1f95240>, <ast.Constant object at 0x7da1b1f94e80>, <ast.Constant object at 0x7da1b1f94eb0>, <ast.Constant object at 0x7da1b1f94dc0>, <ast.Constant object at 0x7da1b1f94b50>, <ast.Constant object at 0x7da1b1f955a0>, <ast.Constant object at 0x7da1b1f95450>, <ast.Constant object at 0x7da1b1f954e0>]] for taget[name[attr]] in starred[name[attrs]] begin[:] variable[val] assign[=] call[name[getattr], parameter[name[sess], name[attr], constant[None]]] if name[val] begin[:] call[name[setattr], parameter[name[scraper], name[attr], name[val]]] return[name[scraper]]
keyword[def] identifier[create_scraper] ( identifier[cls] , identifier[sess] = keyword[None] ,** identifier[kwargs] ): literal[string] identifier[scraper] = identifier[cls] (** identifier[kwargs] ) keyword[if] identifier[sess] : identifier[attrs] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ] keyword[for] identifier[attr] keyword[in] identifier[attrs] : identifier[val] = identifier[getattr] ( identifier[sess] , identifier[attr] , keyword[None] ) keyword[if] identifier[val] : identifier[setattr] ( identifier[scraper] , identifier[attr] , identifier[val] ) keyword[return] identifier[scraper]
def create_scraper(cls, sess=None, **kwargs): """ Convenience function for creating a ready-to-go CloudflareScraper object. """ scraper = cls(**kwargs) if sess: attrs = ['auth', 'cert', 'cookies', 'headers', 'hooks', 'params', 'proxies', 'data'] for attr in attrs: val = getattr(sess, attr, None) if val: setattr(scraper, attr, val) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['attr']] # depends on [control=['if'], data=[]] return scraper
def remove(self, *members): """ Removes @members from the set -> #int the number of members that were removed from the set """ if self.serialized: members = list(map(self._dumps, members)) return self._client.srem(self.key_prefix, *members)
def function[remove, parameter[self]]: constant[ Removes @members from the set -> #int the number of members that were removed from the set ] if name[self].serialized begin[:] variable[members] assign[=] call[name[list], parameter[call[name[map], parameter[name[self]._dumps, name[members]]]]] return[call[name[self]._client.srem, parameter[name[self].key_prefix, <ast.Starred object at 0x7da1b27255d0>]]]
keyword[def] identifier[remove] ( identifier[self] ,* identifier[members] ): literal[string] keyword[if] identifier[self] . identifier[serialized] : identifier[members] = identifier[list] ( identifier[map] ( identifier[self] . identifier[_dumps] , identifier[members] )) keyword[return] identifier[self] . identifier[_client] . identifier[srem] ( identifier[self] . identifier[key_prefix] ,* identifier[members] )
def remove(self, *members): """ Removes @members from the set -> #int the number of members that were removed from the set """ if self.serialized: members = list(map(self._dumps, members)) # depends on [control=['if'], data=[]] return self._client.srem(self.key_prefix, *members)
def tuple2dict(mytuple, constructor=dict): """ Turn a tuple as returned by dict2tuple back into a dictionary structure. The optional parameter "constructor" governs, what class is used to create the dictionary: by default, the standard dict class is used, but in DINGO we mostly use the DingoObjDict class. """ result = constructor() for elt in mytuple: key, value = elt if type(value) == type(()): key_value = tuple2dict(value, constructor=constructor) elif type(value) == type([]): key_value = [] for elt in value: key_value.append(tuple2dict(elt, constructor=constructor)) else: key_value = value result[key] = key_value return result
def function[tuple2dict, parameter[mytuple, constructor]]: constant[ Turn a tuple as returned by dict2tuple back into a dictionary structure. The optional parameter "constructor" governs, what class is used to create the dictionary: by default, the standard dict class is used, but in DINGO we mostly use the DingoObjDict class. ] variable[result] assign[=] call[name[constructor], parameter[]] for taget[name[elt]] in starred[name[mytuple]] begin[:] <ast.Tuple object at 0x7da1b14280d0> assign[=] name[elt] if compare[call[name[type], parameter[name[value]]] equal[==] call[name[type], parameter[tuple[[]]]]] begin[:] variable[key_value] assign[=] call[name[tuple2dict], parameter[name[value]]] call[name[result]][name[key]] assign[=] name[key_value] return[name[result]]
keyword[def] identifier[tuple2dict] ( identifier[mytuple] , identifier[constructor] = identifier[dict] ): literal[string] identifier[result] = identifier[constructor] () keyword[for] identifier[elt] keyword[in] identifier[mytuple] : identifier[key] , identifier[value] = identifier[elt] keyword[if] identifier[type] ( identifier[value] )== identifier[type] (()): identifier[key_value] = identifier[tuple2dict] ( identifier[value] , identifier[constructor] = identifier[constructor] ) keyword[elif] identifier[type] ( identifier[value] )== identifier[type] ([]): identifier[key_value] =[] keyword[for] identifier[elt] keyword[in] identifier[value] : identifier[key_value] . identifier[append] ( identifier[tuple2dict] ( identifier[elt] , identifier[constructor] = identifier[constructor] )) keyword[else] : identifier[key_value] = identifier[value] identifier[result] [ identifier[key] ]= identifier[key_value] keyword[return] identifier[result]
def tuple2dict(mytuple, constructor=dict): """ Turn a tuple as returned by dict2tuple back into a dictionary structure. The optional parameter "constructor" governs, what class is used to create the dictionary: by default, the standard dict class is used, but in DINGO we mostly use the DingoObjDict class. """ result = constructor() for elt in mytuple: (key, value) = elt if type(value) == type(()): key_value = tuple2dict(value, constructor=constructor) # depends on [control=['if'], data=[]] elif type(value) == type([]): key_value = [] for elt in value: key_value.append(tuple2dict(elt, constructor=constructor)) # depends on [control=['for'], data=['elt']] # depends on [control=['if'], data=[]] else: key_value = value result[key] = key_value # depends on [control=['for'], data=['elt']] return result
def getInitialArguments(self): """ Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of L{initialPerson} and the value of L{initialState}, if they are set. """ initialArguments = (self.organizer.storeOwnerPerson.name,) if self.initialPerson is not None: initialArguments += (self.initialPerson.name, self.initialState) return initialArguments
def function[getInitialArguments, parameter[self]]: constant[ Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of L{initialPerson} and the value of L{initialState}, if they are set. ] variable[initialArguments] assign[=] tuple[[<ast.Attribute object at 0x7da1b0a4f940>]] if compare[name[self].initialPerson is_not constant[None]] begin[:] <ast.AugAssign object at 0x7da1b0a4e320> return[name[initialArguments]]
keyword[def] identifier[getInitialArguments] ( identifier[self] ): literal[string] identifier[initialArguments] =( identifier[self] . identifier[organizer] . identifier[storeOwnerPerson] . identifier[name] ,) keyword[if] identifier[self] . identifier[initialPerson] keyword[is] keyword[not] keyword[None] : identifier[initialArguments] +=( identifier[self] . identifier[initialPerson] . identifier[name] , identifier[self] . identifier[initialState] ) keyword[return] identifier[initialArguments]
def getInitialArguments(self): """ Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of L{initialPerson} and the value of L{initialState}, if they are set. """ initialArguments = (self.organizer.storeOwnerPerson.name,) if self.initialPerson is not None: initialArguments += (self.initialPerson.name, self.initialState) # depends on [control=['if'], data=[]] return initialArguments
def open_pspsfile(self, ecut=20, pawecutdg=None): """ Calls Abinit to compute the internal tables for the application of the pseudopotential part. Returns :class:`PspsFile` object providing methods to plot and analyze the data or None if file is not found or it's not readable. Args: ecut: Cutoff energy in Hartree. pawecutdg: Cutoff energy for the PAW double grid. """ from pymatgen.io.abinit.tasks import AbinitTask from abipy.core.structure import Structure from abipy.abio.factories import gs_input from abipy.electrons.psps import PspsFile # Build fake structure. lattice = 10 * np.eye(3) structure = Structure(lattice, [self.element], coords=[[0, 0, 0]]) if self.ispaw and pawecutdg is None: pawecutdg = ecut * 4 inp = gs_input(structure, pseudos=[self], ecut=ecut, pawecutdg=pawecutdg, spin_mode="unpolarized", kppa=1) # Add prtpsps = -1 to make Abinit print the PSPS.nc file and stop. inp["prtpsps"] = -1 # Build temporary task and run it (ignore retcode because we don't exit cleanly) task = AbinitTask.temp_shell_task(inp) task.start_and_wait() filepath = task.outdir.has_abiext("_PSPS.nc") if not filepath: logger.critical("Cannot find PSPS.nc file in %s" % task.outdir) return None # Open the PSPS.nc file. try: return PspsFile(filepath) except Exception as exc: logger.critical("Exception while reading PSPS file at %s:\n%s" % (filepath, str(exc))) return None
def function[open_pspsfile, parameter[self, ecut, pawecutdg]]: constant[ Calls Abinit to compute the internal tables for the application of the pseudopotential part. Returns :class:`PspsFile` object providing methods to plot and analyze the data or None if file is not found or it's not readable. Args: ecut: Cutoff energy in Hartree. pawecutdg: Cutoff energy for the PAW double grid. ] from relative_module[pymatgen.io.abinit.tasks] import module[AbinitTask] from relative_module[abipy.core.structure] import module[Structure] from relative_module[abipy.abio.factories] import module[gs_input] from relative_module[abipy.electrons.psps] import module[PspsFile] variable[lattice] assign[=] binary_operation[constant[10] * call[name[np].eye, parameter[constant[3]]]] variable[structure] assign[=] call[name[Structure], parameter[name[lattice], list[[<ast.Attribute object at 0x7da20c6c7400>]]]] if <ast.BoolOp object at 0x7da20c6c62c0> begin[:] variable[pawecutdg] assign[=] binary_operation[name[ecut] * constant[4]] variable[inp] assign[=] call[name[gs_input], parameter[name[structure]]] call[name[inp]][constant[prtpsps]] assign[=] <ast.UnaryOp object at 0x7da20c6c54e0> variable[task] assign[=] call[name[AbinitTask].temp_shell_task, parameter[name[inp]]] call[name[task].start_and_wait, parameter[]] variable[filepath] assign[=] call[name[task].outdir.has_abiext, parameter[constant[_PSPS.nc]]] if <ast.UnaryOp object at 0x7da20c6c77c0> begin[:] call[name[logger].critical, parameter[binary_operation[constant[Cannot find PSPS.nc file in %s] <ast.Mod object at 0x7da2590d6920> name[task].outdir]]] return[constant[None]] <ast.Try object at 0x7da2101f5060>
keyword[def] identifier[open_pspsfile] ( identifier[self] , identifier[ecut] = literal[int] , identifier[pawecutdg] = keyword[None] ): literal[string] keyword[from] identifier[pymatgen] . identifier[io] . identifier[abinit] . identifier[tasks] keyword[import] identifier[AbinitTask] keyword[from] identifier[abipy] . identifier[core] . identifier[structure] keyword[import] identifier[Structure] keyword[from] identifier[abipy] . identifier[abio] . identifier[factories] keyword[import] identifier[gs_input] keyword[from] identifier[abipy] . identifier[electrons] . identifier[psps] keyword[import] identifier[PspsFile] identifier[lattice] = literal[int] * identifier[np] . identifier[eye] ( literal[int] ) identifier[structure] = identifier[Structure] ( identifier[lattice] ,[ identifier[self] . identifier[element] ], identifier[coords] =[[ literal[int] , literal[int] , literal[int] ]]) keyword[if] identifier[self] . identifier[ispaw] keyword[and] identifier[pawecutdg] keyword[is] keyword[None] : identifier[pawecutdg] = identifier[ecut] * literal[int] identifier[inp] = identifier[gs_input] ( identifier[structure] , identifier[pseudos] =[ identifier[self] ], identifier[ecut] = identifier[ecut] , identifier[pawecutdg] = identifier[pawecutdg] , identifier[spin_mode] = literal[string] , identifier[kppa] = literal[int] ) identifier[inp] [ literal[string] ]=- literal[int] identifier[task] = identifier[AbinitTask] . identifier[temp_shell_task] ( identifier[inp] ) identifier[task] . identifier[start_and_wait] () identifier[filepath] = identifier[task] . identifier[outdir] . identifier[has_abiext] ( literal[string] ) keyword[if] keyword[not] identifier[filepath] : identifier[logger] . identifier[critical] ( literal[string] % identifier[task] . identifier[outdir] ) keyword[return] keyword[None] keyword[try] : keyword[return] identifier[PspsFile] ( identifier[filepath] ) keyword[except] identifier[Exception] keyword[as] identifier[exc] : identifier[logger] . identifier[critical] ( literal[string] %( identifier[filepath] , identifier[str] ( identifier[exc] ))) keyword[return] keyword[None]
def open_pspsfile(self, ecut=20, pawecutdg=None): """ Calls Abinit to compute the internal tables for the application of the pseudopotential part. Returns :class:`PspsFile` object providing methods to plot and analyze the data or None if file is not found or it's not readable. Args: ecut: Cutoff energy in Hartree. pawecutdg: Cutoff energy for the PAW double grid. """ from pymatgen.io.abinit.tasks import AbinitTask from abipy.core.structure import Structure from abipy.abio.factories import gs_input from abipy.electrons.psps import PspsFile # Build fake structure. lattice = 10 * np.eye(3) structure = Structure(lattice, [self.element], coords=[[0, 0, 0]]) if self.ispaw and pawecutdg is None: pawecutdg = ecut * 4 # depends on [control=['if'], data=[]] inp = gs_input(structure, pseudos=[self], ecut=ecut, pawecutdg=pawecutdg, spin_mode='unpolarized', kppa=1) # Add prtpsps = -1 to make Abinit print the PSPS.nc file and stop. inp['prtpsps'] = -1 # Build temporary task and run it (ignore retcode because we don't exit cleanly) task = AbinitTask.temp_shell_task(inp) task.start_and_wait() filepath = task.outdir.has_abiext('_PSPS.nc') if not filepath: logger.critical('Cannot find PSPS.nc file in %s' % task.outdir) return None # depends on [control=['if'], data=[]] # Open the PSPS.nc file. try: return PspsFile(filepath) # depends on [control=['try'], data=[]] except Exception as exc: logger.critical('Exception while reading PSPS file at %s:\n%s' % (filepath, str(exc))) return None # depends on [control=['except'], data=['exc']]
def secpolicy_sa_secpolicy_defined_policy_policies_policy(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") secpolicy_sa = ET.SubElement(config, "secpolicy-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth") secpolicy = ET.SubElement(secpolicy_sa, "secpolicy") defined_policy = ET.SubElement(secpolicy, "defined-policy") policies = ET.SubElement(defined_policy, "policies") policy = ET.SubElement(policies, "policy") policy.text = kwargs.pop('policy') callback = kwargs.pop('callback', self._callback) return callback(config)
def function[secpolicy_sa_secpolicy_defined_policy_policies_policy, parameter[self]]: constant[Auto Generated Code ] variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]] variable[secpolicy_sa] assign[=] call[name[ET].SubElement, parameter[name[config], constant[secpolicy-sa]]] variable[secpolicy] assign[=] call[name[ET].SubElement, parameter[name[secpolicy_sa], constant[secpolicy]]] variable[defined_policy] assign[=] call[name[ET].SubElement, parameter[name[secpolicy], constant[defined-policy]]] variable[policies] assign[=] call[name[ET].SubElement, parameter[name[defined_policy], constant[policies]]] variable[policy] assign[=] call[name[ET].SubElement, parameter[name[policies], constant[policy]]] name[policy].text assign[=] call[name[kwargs].pop, parameter[constant[policy]]] variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]] return[call[name[callback], parameter[name[config]]]]
keyword[def] identifier[secpolicy_sa_secpolicy_defined_policy_policies_policy] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[config] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[secpolicy_sa] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , identifier[xmlns] = literal[string] ) identifier[secpolicy] = identifier[ET] . identifier[SubElement] ( identifier[secpolicy_sa] , literal[string] ) identifier[defined_policy] = identifier[ET] . identifier[SubElement] ( identifier[secpolicy] , literal[string] ) identifier[policies] = identifier[ET] . identifier[SubElement] ( identifier[defined_policy] , literal[string] ) identifier[policy] = identifier[ET] . identifier[SubElement] ( identifier[policies] , literal[string] ) identifier[policy] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[callback] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_callback] ) keyword[return] identifier[callback] ( identifier[config] )
def secpolicy_sa_secpolicy_defined_policy_policies_policy(self, **kwargs): """Auto Generated Code """ config = ET.Element('config') secpolicy_sa = ET.SubElement(config, 'secpolicy-sa', xmlns='urn:brocade.com:mgmt:brocade-fc-auth') secpolicy = ET.SubElement(secpolicy_sa, 'secpolicy') defined_policy = ET.SubElement(secpolicy, 'defined-policy') policies = ET.SubElement(defined_policy, 'policies') policy = ET.SubElement(policies, 'policy') policy.text = kwargs.pop('policy') callback = kwargs.pop('callback', self._callback) return callback(config)
def _apply_record_checks(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply record checks on `r`.""" for check, modulus in self._record_checks: if i % modulus == 0: # support sampling rdict = self._as_dict(r) try: check(rdict) except RecordError as e: code = e.code if e.code is not None else RECORD_CHECK_FAILED p = {'code': code} if not summarize: message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED] p['message'] = message p['row'] = i + 1 p['record'] = r if context is not None: p['context'] = context if e.details is not None: p['details'] = e.details yield p except Exception as e: if report_unexpected_exceptions: p = {'code': UNEXPECTED_EXCEPTION} if not summarize: p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e) p['row'] = i + 1 p['record'] = r p['exception'] = e p['function'] = '%s: %s' % (check.__name__, check.__doc__) if context is not None: p['context'] = context yield p
def function[_apply_record_checks, parameter[self, i, r, summarize, report_unexpected_exceptions, context]]: constant[Apply record checks on `r`.] for taget[tuple[[<ast.Name object at 0x7da1affe6ad0>, <ast.Name object at 0x7da1affe5db0>]]] in starred[name[self]._record_checks] begin[:] if compare[binary_operation[name[i] <ast.Mod object at 0x7da2590d6920> name[modulus]] equal[==] constant[0]] begin[:] variable[rdict] assign[=] call[name[self]._as_dict, parameter[name[r]]] <ast.Try object at 0x7da1affe5ff0>
keyword[def] identifier[_apply_record_checks] ( identifier[self] , identifier[i] , identifier[r] , identifier[summarize] = keyword[False] , identifier[report_unexpected_exceptions] = keyword[True] , identifier[context] = keyword[None] ): literal[string] keyword[for] identifier[check] , identifier[modulus] keyword[in] identifier[self] . identifier[_record_checks] : keyword[if] identifier[i] % identifier[modulus] == literal[int] : identifier[rdict] = identifier[self] . identifier[_as_dict] ( identifier[r] ) keyword[try] : identifier[check] ( identifier[rdict] ) keyword[except] identifier[RecordError] keyword[as] identifier[e] : identifier[code] = identifier[e] . identifier[code] keyword[if] identifier[e] . identifier[code] keyword[is] keyword[not] keyword[None] keyword[else] identifier[RECORD_CHECK_FAILED] identifier[p] ={ literal[string] : identifier[code] } keyword[if] keyword[not] identifier[summarize] : identifier[message] = identifier[e] . identifier[message] keyword[if] identifier[e] . identifier[message] keyword[is] keyword[not] keyword[None] keyword[else] identifier[MESSAGES] [ identifier[RECORD_CHECK_FAILED] ] identifier[p] [ literal[string] ]= identifier[message] identifier[p] [ literal[string] ]= identifier[i] + literal[int] identifier[p] [ literal[string] ]= identifier[r] keyword[if] identifier[context] keyword[is] keyword[not] keyword[None] : identifier[p] [ literal[string] ]= identifier[context] keyword[if] identifier[e] . identifier[details] keyword[is] keyword[not] keyword[None] : identifier[p] [ literal[string] ]= identifier[e] . identifier[details] keyword[yield] identifier[p] keyword[except] identifier[Exception] keyword[as] identifier[e] : keyword[if] identifier[report_unexpected_exceptions] : identifier[p] ={ literal[string] : identifier[UNEXPECTED_EXCEPTION] } keyword[if] keyword[not] identifier[summarize] : identifier[p] [ literal[string] ]= identifier[MESSAGES] [ identifier[UNEXPECTED_EXCEPTION] ]%( identifier[e] . identifier[__class__] . identifier[__name__] , identifier[e] ) identifier[p] [ literal[string] ]= identifier[i] + literal[int] identifier[p] [ literal[string] ]= identifier[r] identifier[p] [ literal[string] ]= identifier[e] identifier[p] [ literal[string] ]= literal[string] %( identifier[check] . identifier[__name__] , identifier[check] . identifier[__doc__] ) keyword[if] identifier[context] keyword[is] keyword[not] keyword[None] : identifier[p] [ literal[string] ]= identifier[context] keyword[yield] identifier[p]
def _apply_record_checks(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply record checks on `r`.""" for (check, modulus) in self._record_checks: if i % modulus == 0: # support sampling rdict = self._as_dict(r) try: check(rdict) # depends on [control=['try'], data=[]] except RecordError as e: code = e.code if e.code is not None else RECORD_CHECK_FAILED p = {'code': code} if not summarize: message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED] p['message'] = message p['row'] = i + 1 p['record'] = r if context is not None: p['context'] = context # depends on [control=['if'], data=['context']] if e.details is not None: p['details'] = e.details # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] yield p # depends on [control=['except'], data=['e']] except Exception as e: if report_unexpected_exceptions: p = {'code': UNEXPECTED_EXCEPTION} if not summarize: p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e) p['row'] = i + 1 p['record'] = r p['exception'] = e p['function'] = '%s: %s' % (check.__name__, check.__doc__) if context is not None: p['context'] = context # depends on [control=['if'], data=['context']] # depends on [control=['if'], data=[]] yield p # depends on [control=['if'], data=[]] # depends on [control=['except'], data=['e']] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
def spawn_program(self, name, arguments=[], timeout=30, exclusive=False): """Spawns a program in the working directory. This method allows the interaction with the running program, based on the returned RunningProgram object. Args: name (str): The name of the program to be executed. arguments (tuple): Command-line arguments for the program. timeout (int): The timeout for execution. exclusive (bool): Prevent parallel validation runs on the test machines, e.g. when doing performance measurements for submitted code. Returns: RunningProgram: An object representing the running program. """ logger.debug("Spawning program for interaction ...") if exclusive: kill_longrunning(self.config) return RunningProgram(self, name, arguments, timeout)
def function[spawn_program, parameter[self, name, arguments, timeout, exclusive]]: constant[Spawns a program in the working directory. This method allows the interaction with the running program, based on the returned RunningProgram object. Args: name (str): The name of the program to be executed. arguments (tuple): Command-line arguments for the program. timeout (int): The timeout for execution. exclusive (bool): Prevent parallel validation runs on the test machines, e.g. when doing performance measurements for submitted code. Returns: RunningProgram: An object representing the running program. ] call[name[logger].debug, parameter[constant[Spawning program for interaction ...]]] if name[exclusive] begin[:] call[name[kill_longrunning], parameter[name[self].config]] return[call[name[RunningProgram], parameter[name[self], name[name], name[arguments], name[timeout]]]]
keyword[def] identifier[spawn_program] ( identifier[self] , identifier[name] , identifier[arguments] =[], identifier[timeout] = literal[int] , identifier[exclusive] = keyword[False] ): literal[string] identifier[logger] . identifier[debug] ( literal[string] ) keyword[if] identifier[exclusive] : identifier[kill_longrunning] ( identifier[self] . identifier[config] ) keyword[return] identifier[RunningProgram] ( identifier[self] , identifier[name] , identifier[arguments] , identifier[timeout] )
def spawn_program(self, name, arguments=[], timeout=30, exclusive=False): """Spawns a program in the working directory. This method allows the interaction with the running program, based on the returned RunningProgram object. Args: name (str): The name of the program to be executed. arguments (tuple): Command-line arguments for the program. timeout (int): The timeout for execution. exclusive (bool): Prevent parallel validation runs on the test machines, e.g. when doing performance measurements for submitted code. Returns: RunningProgram: An object representing the running program. """ logger.debug('Spawning program for interaction ...') if exclusive: kill_longrunning(self.config) # depends on [control=['if'], data=[]] return RunningProgram(self, name, arguments, timeout)
def registerLoggers(info, error, debug): """ Add logging functions to this module. Functions will be called on various severities (log, error, or debug respectively). Each function must have the signature: fn(message, **kwargs) If Python str.format()-style placeholders are in message, kwargs will be interpolated. """ global log_info global log_error global log_debug log_info = info log_error = error log_debug = debug
def function[registerLoggers, parameter[info, error, debug]]: constant[ Add logging functions to this module. Functions will be called on various severities (log, error, or debug respectively). Each function must have the signature: fn(message, **kwargs) If Python str.format()-style placeholders are in message, kwargs will be interpolated. ] <ast.Global object at 0x7da2054a6470> <ast.Global object at 0x7da2054a4100> <ast.Global object at 0x7da2054a62c0> variable[log_info] assign[=] name[info] variable[log_error] assign[=] name[error] variable[log_debug] assign[=] name[debug]
keyword[def] identifier[registerLoggers] ( identifier[info] , identifier[error] , identifier[debug] ): literal[string] keyword[global] identifier[log_info] keyword[global] identifier[log_error] keyword[global] identifier[log_debug] identifier[log_info] = identifier[info] identifier[log_error] = identifier[error] identifier[log_debug] = identifier[debug]
def registerLoggers(info, error, debug): """ Add logging functions to this module. Functions will be called on various severities (log, error, or debug respectively). Each function must have the signature: fn(message, **kwargs) If Python str.format()-style placeholders are in message, kwargs will be interpolated. """ global log_info global log_error global log_debug log_info = info log_error = error log_debug = debug
def create_from_tables(cls, norm_type='eflux', tab_s="SCANDATA", tab_e="EBOUNDS"): """Create a CastroData object from two tables Parameters ---------- norm_type : str Type of normalization to use. Valid options are: * norm : Normalization w.r.t. to test source * flux : Flux of the test source ( ph cm^-2 s^-1 ) * eflux: Energy Flux of the test source ( MeV cm^-2 s^-1 ) * npred: Number of predicted photons (Not implemented) * dnde : Differential flux of the test source ( ph cm^-2 s^-1 MeV^-1 ) tab_s : str table scan data tab_e : str table energy binning and normalization data Returns ------- castro : `~fermipy.castro.CastroData` """ if norm_type in ['flux', 'eflux', 'dnde']: norm_vals = np.array(tab_s['norm_scan'] * tab_e['ref_%s' % norm_type][:, np.newaxis]) elif norm_type == "norm": norm_vals = np.array(tab_s['norm_scan']) else: raise Exception('Unrecognized normalization type: %s' % norm_type) nll_vals = -np.array(tab_s['dloglike_scan']) rs = ReferenceSpec.create_from_table(tab_e) return cls(norm_vals, nll_vals, rs, norm_type)
def function[create_from_tables, parameter[cls, norm_type, tab_s, tab_e]]: constant[Create a CastroData object from two tables Parameters ---------- norm_type : str Type of normalization to use. Valid options are: * norm : Normalization w.r.t. to test source * flux : Flux of the test source ( ph cm^-2 s^-1 ) * eflux: Energy Flux of the test source ( MeV cm^-2 s^-1 ) * npred: Number of predicted photons (Not implemented) * dnde : Differential flux of the test source ( ph cm^-2 s^-1 MeV^-1 ) tab_s : str table scan data tab_e : str table energy binning and normalization data Returns ------- castro : `~fermipy.castro.CastroData` ] if compare[name[norm_type] in list[[<ast.Constant object at 0x7da18dc07a00>, <ast.Constant object at 0x7da18dc04280>, <ast.Constant object at 0x7da18dc06d40>]]] begin[:] variable[norm_vals] assign[=] call[name[np].array, parameter[binary_operation[call[name[tab_s]][constant[norm_scan]] * call[call[name[tab_e]][binary_operation[constant[ref_%s] <ast.Mod object at 0x7da2590d6920> name[norm_type]]]][tuple[[<ast.Slice object at 0x7da18dc05ed0>, <ast.Attribute object at 0x7da18dc06e90>]]]]]] variable[nll_vals] assign[=] <ast.UnaryOp object at 0x7da18dc04760> variable[rs] assign[=] call[name[ReferenceSpec].create_from_table, parameter[name[tab_e]]] return[call[name[cls], parameter[name[norm_vals], name[nll_vals], name[rs], name[norm_type]]]]
keyword[def] identifier[create_from_tables] ( identifier[cls] , identifier[norm_type] = literal[string] , identifier[tab_s] = literal[string] , identifier[tab_e] = literal[string] ): literal[string] keyword[if] identifier[norm_type] keyword[in] [ literal[string] , literal[string] , literal[string] ]: identifier[norm_vals] = identifier[np] . identifier[array] ( identifier[tab_s] [ literal[string] ]* identifier[tab_e] [ literal[string] % identifier[norm_type] ][:, identifier[np] . identifier[newaxis] ]) keyword[elif] identifier[norm_type] == literal[string] : identifier[norm_vals] = identifier[np] . identifier[array] ( identifier[tab_s] [ literal[string] ]) keyword[else] : keyword[raise] identifier[Exception] ( literal[string] % identifier[norm_type] ) identifier[nll_vals] =- identifier[np] . identifier[array] ( identifier[tab_s] [ literal[string] ]) identifier[rs] = identifier[ReferenceSpec] . identifier[create_from_table] ( identifier[tab_e] ) keyword[return] identifier[cls] ( identifier[norm_vals] , identifier[nll_vals] , identifier[rs] , identifier[norm_type] )
def create_from_tables(cls, norm_type='eflux', tab_s='SCANDATA', tab_e='EBOUNDS'): """Create a CastroData object from two tables Parameters ---------- norm_type : str Type of normalization to use. Valid options are: * norm : Normalization w.r.t. to test source * flux : Flux of the test source ( ph cm^-2 s^-1 ) * eflux: Energy Flux of the test source ( MeV cm^-2 s^-1 ) * npred: Number of predicted photons (Not implemented) * dnde : Differential flux of the test source ( ph cm^-2 s^-1 MeV^-1 ) tab_s : str table scan data tab_e : str table energy binning and normalization data Returns ------- castro : `~fermipy.castro.CastroData` """ if norm_type in ['flux', 'eflux', 'dnde']: norm_vals = np.array(tab_s['norm_scan'] * tab_e['ref_%s' % norm_type][:, np.newaxis]) # depends on [control=['if'], data=['norm_type']] elif norm_type == 'norm': norm_vals = np.array(tab_s['norm_scan']) # depends on [control=['if'], data=[]] else: raise Exception('Unrecognized normalization type: %s' % norm_type) nll_vals = -np.array(tab_s['dloglike_scan']) rs = ReferenceSpec.create_from_table(tab_e) return cls(norm_vals, nll_vals, rs, norm_type)
def advance(parser): # type: (Parser) -> None """Moves the internal parser object to the next lexed token.""" prev_end = parser.token.end parser.prev_end = prev_end parser.token = parser.lexer.next_token(prev_end)
def function[advance, parameter[parser]]: constant[Moves the internal parser object to the next lexed token.] variable[prev_end] assign[=] name[parser].token.end name[parser].prev_end assign[=] name[prev_end] name[parser].token assign[=] call[name[parser].lexer.next_token, parameter[name[prev_end]]]
keyword[def] identifier[advance] ( identifier[parser] ): literal[string] identifier[prev_end] = identifier[parser] . identifier[token] . identifier[end] identifier[parser] . identifier[prev_end] = identifier[prev_end] identifier[parser] . identifier[token] = identifier[parser] . identifier[lexer] . identifier[next_token] ( identifier[prev_end] )
def advance(parser): # type: (Parser) -> None 'Moves the internal parser object to the next lexed token.' prev_end = parser.token.end parser.prev_end = prev_end parser.token = parser.lexer.next_token(prev_end)
def suspendJustTabProviders(installation): """ Replace INavigableElements with facades that indicate their suspension. """ if installation.suspended: raise RuntimeError("Installation already suspended") powerups = list(installation.allPowerups) for p in powerups: if INavigableElement.providedBy(p): p.store.powerDown(p, INavigableElement) sne = SuspendedNavigableElement(store=p.store, originalNE=p) p.store.powerUp(sne, INavigableElement) p.store.powerUp(sne, ISuspender) installation.suspended = True
def function[suspendJustTabProviders, parameter[installation]]: constant[ Replace INavigableElements with facades that indicate their suspension. ] if name[installation].suspended begin[:] <ast.Raise object at 0x7da1b0a4dab0> variable[powerups] assign[=] call[name[list], parameter[name[installation].allPowerups]] for taget[name[p]] in starred[name[powerups]] begin[:] if call[name[INavigableElement].providedBy, parameter[name[p]]] begin[:] call[name[p].store.powerDown, parameter[name[p], name[INavigableElement]]] variable[sne] assign[=] call[name[SuspendedNavigableElement], parameter[]] call[name[p].store.powerUp, parameter[name[sne], name[INavigableElement]]] call[name[p].store.powerUp, parameter[name[sne], name[ISuspender]]] name[installation].suspended assign[=] constant[True]
keyword[def] identifier[suspendJustTabProviders] ( identifier[installation] ): literal[string] keyword[if] identifier[installation] . identifier[suspended] : keyword[raise] identifier[RuntimeError] ( literal[string] ) identifier[powerups] = identifier[list] ( identifier[installation] . identifier[allPowerups] ) keyword[for] identifier[p] keyword[in] identifier[powerups] : keyword[if] identifier[INavigableElement] . identifier[providedBy] ( identifier[p] ): identifier[p] . identifier[store] . identifier[powerDown] ( identifier[p] , identifier[INavigableElement] ) identifier[sne] = identifier[SuspendedNavigableElement] ( identifier[store] = identifier[p] . identifier[store] , identifier[originalNE] = identifier[p] ) identifier[p] . identifier[store] . identifier[powerUp] ( identifier[sne] , identifier[INavigableElement] ) identifier[p] . identifier[store] . identifier[powerUp] ( identifier[sne] , identifier[ISuspender] ) identifier[installation] . identifier[suspended] = keyword[True]
def suspendJustTabProviders(installation): """ Replace INavigableElements with facades that indicate their suspension. """ if installation.suspended: raise RuntimeError('Installation already suspended') # depends on [control=['if'], data=[]] powerups = list(installation.allPowerups) for p in powerups: if INavigableElement.providedBy(p): p.store.powerDown(p, INavigableElement) sne = SuspendedNavigableElement(store=p.store, originalNE=p) p.store.powerUp(sne, INavigableElement) p.store.powerUp(sne, ISuspender) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['p']] installation.suspended = True
def search_one(self, keyword, arg=None, children=None): """Return receiver's substmt with `keyword` and optionally `arg`. """ if children is None: children = self.substmts for ch in children: if ch.keyword == keyword and (arg is None or ch.arg == arg): return ch return None
def function[search_one, parameter[self, keyword, arg, children]]: constant[Return receiver's substmt with `keyword` and optionally `arg`. ] if compare[name[children] is constant[None]] begin[:] variable[children] assign[=] name[self].substmts for taget[name[ch]] in starred[name[children]] begin[:] if <ast.BoolOp object at 0x7da20cabf2e0> begin[:] return[name[ch]] return[constant[None]]
keyword[def] identifier[search_one] ( identifier[self] , identifier[keyword] , identifier[arg] = keyword[None] , identifier[children] = keyword[None] ): literal[string] keyword[if] identifier[children] keyword[is] keyword[None] : identifier[children] = identifier[self] . identifier[substmts] keyword[for] identifier[ch] keyword[in] identifier[children] : keyword[if] identifier[ch] . identifier[keyword] == identifier[keyword] keyword[and] ( identifier[arg] keyword[is] keyword[None] keyword[or] identifier[ch] . identifier[arg] == identifier[arg] ): keyword[return] identifier[ch] keyword[return] keyword[None]
def search_one(self, keyword, arg=None, children=None): """Return receiver's substmt with `keyword` and optionally `arg`. """ if children is None: children = self.substmts # depends on [control=['if'], data=['children']] for ch in children: if ch.keyword == keyword and (arg is None or ch.arg == arg): return ch # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['ch']] return None
def get_jsapi_signature(self, noncestr, ticket, timestamp, url): """ 获取 JSAPI 签名 https://work.weixin.qq.com/api/doc#90001/90144/90539/签名算法/ :param noncestr: nonce string :param ticket: JS-SDK ticket :param timestamp: 时间戳 :param url: URL :return: 签名 """ data = [ 'noncestr={noncestr}'.format(noncestr=noncestr), 'jsapi_ticket={ticket}'.format(ticket=ticket), 'timestamp={timestamp}'.format(timestamp=timestamp), 'url={url}'.format(url=url), ] signer = WeChatSigner(delimiter=b'&') signer.add_data(*data) return signer.signature
def function[get_jsapi_signature, parameter[self, noncestr, ticket, timestamp, url]]: constant[ 获取 JSAPI 签名 https://work.weixin.qq.com/api/doc#90001/90144/90539/签名算法/ :param noncestr: nonce string :param ticket: JS-SDK ticket :param timestamp: 时间戳 :param url: URL :return: 签名 ] variable[data] assign[=] list[[<ast.Call object at 0x7da204963bb0>, <ast.Call object at 0x7da204963c70>, <ast.Call object at 0x7da204963460>, <ast.Call object at 0x7da2049634c0>]] variable[signer] assign[=] call[name[WeChatSigner], parameter[]] call[name[signer].add_data, parameter[<ast.Starred object at 0x7da204961cf0>]] return[name[signer].signature]
keyword[def] identifier[get_jsapi_signature] ( identifier[self] , identifier[noncestr] , identifier[ticket] , identifier[timestamp] , identifier[url] ): literal[string] identifier[data] =[ literal[string] . identifier[format] ( identifier[noncestr] = identifier[noncestr] ), literal[string] . identifier[format] ( identifier[ticket] = identifier[ticket] ), literal[string] . identifier[format] ( identifier[timestamp] = identifier[timestamp] ), literal[string] . identifier[format] ( identifier[url] = identifier[url] ), ] identifier[signer] = identifier[WeChatSigner] ( identifier[delimiter] = literal[string] ) identifier[signer] . identifier[add_data] (* identifier[data] ) keyword[return] identifier[signer] . identifier[signature]
def get_jsapi_signature(self, noncestr, ticket, timestamp, url): """ 获取 JSAPI 签名 https://work.weixin.qq.com/api/doc#90001/90144/90539/签名算法/ :param noncestr: nonce string :param ticket: JS-SDK ticket :param timestamp: 时间戳 :param url: URL :return: 签名 """ data = ['noncestr={noncestr}'.format(noncestr=noncestr), 'jsapi_ticket={ticket}'.format(ticket=ticket), 'timestamp={timestamp}'.format(timestamp=timestamp), 'url={url}'.format(url=url)] signer = WeChatSigner(delimiter=b'&') signer.add_data(*data) return signer.signature
def btc_is_p2sh_script( script_hex ): """ Is the given scriptpubkey a p2sh script? """ if script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46: return True else: return False
def function[btc_is_p2sh_script, parameter[script_hex]]: constant[ Is the given scriptpubkey a p2sh script? ] if <ast.BoolOp object at 0x7da1b26f1270> begin[:] return[constant[True]]
keyword[def] identifier[btc_is_p2sh_script] ( identifier[script_hex] ): literal[string] keyword[if] identifier[script_hex] . identifier[startswith] ( literal[string] ) keyword[and] identifier[script_hex] . identifier[endswith] ( literal[string] ) keyword[and] identifier[len] ( identifier[script_hex] )== literal[int] : keyword[return] keyword[True] keyword[else] : keyword[return] keyword[False]
def btc_is_p2sh_script(script_hex): """ Is the given scriptpubkey a p2sh script? """ if script_hex.startswith('a914') and script_hex.endswith('87') and (len(script_hex) == 46): return True # depends on [control=['if'], data=[]] else: return False
def get_failed_requests(self, results): """Return the requests that failed. :param results: the results of a membership request check :type results: :class:`list` :return: the failed requests :rtype: generator """ data = {member['guid']: member for member in results} for request in self.requests: if request['guid'] not in data: yield request
def function[get_failed_requests, parameter[self, results]]: constant[Return the requests that failed. :param results: the results of a membership request check :type results: :class:`list` :return: the failed requests :rtype: generator ] variable[data] assign[=] <ast.DictComp object at 0x7da1b1107550> for taget[name[request]] in starred[name[self].requests] begin[:] if compare[call[name[request]][constant[guid]] <ast.NotIn object at 0x7da2590d7190> name[data]] begin[:] <ast.Yield object at 0x7da1b1106290>
keyword[def] identifier[get_failed_requests] ( identifier[self] , identifier[results] ): literal[string] identifier[data] ={ identifier[member] [ literal[string] ]: identifier[member] keyword[for] identifier[member] keyword[in] identifier[results] } keyword[for] identifier[request] keyword[in] identifier[self] . identifier[requests] : keyword[if] identifier[request] [ literal[string] ] keyword[not] keyword[in] identifier[data] : keyword[yield] identifier[request]
def get_failed_requests(self, results): """Return the requests that failed. :param results: the results of a membership request check :type results: :class:`list` :return: the failed requests :rtype: generator """ data = {member['guid']: member for member in results} for request in self.requests: if request['guid'] not in data: yield request # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['request']]
def list_assignment_submissions_courses(self, course_id, assignment_id, grouped=None, include=None): """ List assignment submissions. Get all existing submissions for an assignment. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - assignment_id """ID""" path["assignment_id"] = assignment_id # OPTIONAL - include """Associations to include with the group. "group" will add group_id and group_name.""" if include is not None: self._validate_enum(include, ["submission_history", "submission_comments", "rubric_assessment", "assignment", "visibility", "course", "user", "group"]) params["include"] = include # OPTIONAL - grouped """If this argument is true, the response will be grouped by student groups.""" if grouped is not None: params["grouped"] = grouped self.logger.debug("GET /api/v1/courses/{course_id}/assignments/{assignment_id}/submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/assignments/{assignment_id}/submissions".format(**path), data=data, params=params, all_pages=True)
def function[list_assignment_submissions_courses, parameter[self, course_id, assignment_id, grouped, include]]: constant[ List assignment submissions. Get all existing submissions for an assignment. ] variable[path] assign[=] dictionary[[], []] variable[data] assign[=] dictionary[[], []] variable[params] assign[=] dictionary[[], []] constant[ID] call[name[path]][constant[course_id]] assign[=] name[course_id] constant[ID] call[name[path]][constant[assignment_id]] assign[=] name[assignment_id] constant[Associations to include with the group. "group" will add group_id and group_name.] if compare[name[include] is_not constant[None]] begin[:] call[name[self]._validate_enum, parameter[name[include], list[[<ast.Constant object at 0x7da1b0b7eaa0>, <ast.Constant object at 0x7da1b0b7c940>, <ast.Constant object at 0x7da1b0b7cd00>, <ast.Constant object at 0x7da1b0b7d630>, <ast.Constant object at 0x7da1b0b7e6b0>, <ast.Constant object at 0x7da1b0b7c670>, <ast.Constant object at 0x7da1b0b7f670>, <ast.Constant object at 0x7da1b0b7f910>]]]] call[name[params]][constant[include]] assign[=] name[include] constant[If this argument is true, the response will be grouped by student groups.] if compare[name[grouped] is_not constant[None]] begin[:] call[name[params]][constant[grouped]] assign[=] name[grouped] call[name[self].logger.debug, parameter[call[constant[GET /api/v1/courses/{course_id}/assignments/{assignment_id}/submissions with query params: {params} and form data: {data}].format, parameter[]]]] return[call[name[self].generic_request, parameter[constant[GET], call[constant[/api/v1/courses/{course_id}/assignments/{assignment_id}/submissions].format, parameter[]]]]]
keyword[def] identifier[list_assignment_submissions_courses] ( identifier[self] , identifier[course_id] , identifier[assignment_id] , identifier[grouped] = keyword[None] , identifier[include] = keyword[None] ): literal[string] identifier[path] ={} identifier[data] ={} identifier[params] ={} literal[string] identifier[path] [ literal[string] ]= identifier[course_id] literal[string] identifier[path] [ literal[string] ]= identifier[assignment_id] literal[string] keyword[if] identifier[include] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[_validate_enum] ( identifier[include] ,[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]) identifier[params] [ literal[string] ]= identifier[include] literal[string] keyword[if] identifier[grouped] keyword[is] keyword[not] keyword[None] : identifier[params] [ literal[string] ]= identifier[grouped] identifier[self] . identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[params] = identifier[params] , identifier[data] = identifier[data] ,** identifier[path] )) keyword[return] identifier[self] . identifier[generic_request] ( literal[string] , literal[string] . identifier[format] (** identifier[path] ), identifier[data] = identifier[data] , identifier[params] = identifier[params] , identifier[all_pages] = keyword[True] )
def list_assignment_submissions_courses(self, course_id, assignment_id, grouped=None, include=None): """ List assignment submissions. Get all existing submissions for an assignment. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id 'ID' path['course_id'] = course_id # REQUIRED - PATH - assignment_id 'ID' path['assignment_id'] = assignment_id # OPTIONAL - include 'Associations to include with the group. "group" will add group_id and group_name.' if include is not None: self._validate_enum(include, ['submission_history', 'submission_comments', 'rubric_assessment', 'assignment', 'visibility', 'course', 'user', 'group']) params['include'] = include # depends on [control=['if'], data=['include']] # OPTIONAL - grouped 'If this argument is true, the response will be grouped by student groups.' if grouped is not None: params['grouped'] = grouped # depends on [control=['if'], data=['grouped']] self.logger.debug('GET /api/v1/courses/{course_id}/assignments/{assignment_id}/submissions with query params: {params} and form data: {data}'.format(params=params, data=data, **path)) return self.generic_request('GET', '/api/v1/courses/{course_id}/assignments/{assignment_id}/submissions'.format(**path), data=data, params=params, all_pages=True)
def _make_ocs_request(self, method, service, action, **kwargs): """Makes a OCS API request :param method: HTTP method :param service: service name :param action: action path :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`requests.Response` instance """ slash = '' if service: slash = '/' path = self.OCS_BASEPATH + service + slash + action attributes = kwargs.copy() if 'headers' not in attributes: attributes['headers'] = {} attributes['headers']['OCS-APIREQUEST'] = 'true' if self._debug: print('OCS request: %s %s %s' % (method, self.url + path, attributes)) res = self._session.request(method, self.url + path, **attributes) return res
def function[_make_ocs_request, parameter[self, method, service, action]]: constant[Makes a OCS API request :param method: HTTP method :param service: service name :param action: action path :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`requests.Response` instance ] variable[slash] assign[=] constant[] if name[service] begin[:] variable[slash] assign[=] constant[/] variable[path] assign[=] binary_operation[binary_operation[binary_operation[name[self].OCS_BASEPATH + name[service]] + name[slash]] + name[action]] variable[attributes] assign[=] call[name[kwargs].copy, parameter[]] if compare[constant[headers] <ast.NotIn object at 0x7da2590d7190> name[attributes]] begin[:] call[name[attributes]][constant[headers]] assign[=] dictionary[[], []] call[call[name[attributes]][constant[headers]]][constant[OCS-APIREQUEST]] assign[=] constant[true] if name[self]._debug begin[:] call[name[print], parameter[binary_operation[constant[OCS request: %s %s %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b26acc10>, <ast.BinOp object at 0x7da1b26af2b0>, <ast.Name object at 0x7da1b26aef50>]]]]] variable[res] assign[=] call[name[self]._session.request, parameter[name[method], binary_operation[name[self].url + name[path]]]] return[name[res]]
keyword[def] identifier[_make_ocs_request] ( identifier[self] , identifier[method] , identifier[service] , identifier[action] ,** identifier[kwargs] ): literal[string] identifier[slash] = literal[string] keyword[if] identifier[service] : identifier[slash] = literal[string] identifier[path] = identifier[self] . identifier[OCS_BASEPATH] + identifier[service] + identifier[slash] + identifier[action] identifier[attributes] = identifier[kwargs] . identifier[copy] () keyword[if] literal[string] keyword[not] keyword[in] identifier[attributes] : identifier[attributes] [ literal[string] ]={} identifier[attributes] [ literal[string] ][ literal[string] ]= literal[string] keyword[if] identifier[self] . identifier[_debug] : identifier[print] ( literal[string] %( identifier[method] , identifier[self] . identifier[url] + identifier[path] , identifier[attributes] )) identifier[res] = identifier[self] . identifier[_session] . identifier[request] ( identifier[method] , identifier[self] . identifier[url] + identifier[path] ,** identifier[attributes] ) keyword[return] identifier[res]
def _make_ocs_request(self, method, service, action, **kwargs): """Makes a OCS API request :param method: HTTP method :param service: service name :param action: action path :param \\*\\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`requests.Response` instance """ slash = '' if service: slash = '/' # depends on [control=['if'], data=[]] path = self.OCS_BASEPATH + service + slash + action attributes = kwargs.copy() if 'headers' not in attributes: attributes['headers'] = {} # depends on [control=['if'], data=['attributes']] attributes['headers']['OCS-APIREQUEST'] = 'true' if self._debug: print('OCS request: %s %s %s' % (method, self.url + path, attributes)) # depends on [control=['if'], data=[]] res = self._session.request(method, self.url + path, **attributes) return res
def template_engine(self, entry, startnode): """The format template interpetation engine. See the comment at the beginning of this module for the how we interpret format specifications such as %c, %C, and so on. """ # print("-----") # print(startnode) # print(entry[0]) # print('======') startnode_start = len(self.f.getvalue()) start = startnode_start fmt = entry[0] arg = 1 i = 0 lastC = -1 recurse_node = False m = escape.search(fmt) while m: i = m.end() self.write(m.group('prefix')) typ = m.group('type') or '{' node = startnode try: if m.group('child'): node = node[int(m.group('child'))] node.parent = startnode except: print(node.__dict__) raise if typ == '%': start = len(self.f.getvalue()) self.write('%') self.set_pos_info(node, start, len(self.f.getvalue())) elif typ == '+': self.indent_more() elif typ == '-': self.indent_less() elif typ == '|': self.write(self.indent) # no longer used, since BUILD_TUPLE_n is pretty printed: elif typ == 'r': recurse_node = True elif typ == ',': if lastC == 1: self.write(',') elif typ == 'b': finish = len(self.f.getvalue()) self.set_pos_info(node[entry[arg]], start, finish) arg += 1 elif typ == 'c': start = len(self.f.getvalue()) index = entry[arg] if isinstance(index, tuple): assert node[index[0]] == index[1], ( "at %s[%d], expected %s node; got %s" % ( node.kind, arg, node[index[0]].kind, index[1]) ) index = index[0] assert isinstance(index, int), ( "at %s[%d], %s should be int or tuple" % ( node.kind, arg, type(index))) self.preorder(node[index]) finish = len(self.f.getvalue()) self.set_pos_info(node, start, finish) arg += 1 elif typ == 'p': p = self.prec (index, self.prec) = entry[arg] node[index].parent = node start = len(self.f.getvalue()) self.preorder(node[index]) self.set_pos_info(node, start, len(self.f.getvalue())) self.prec = p arg += 1 elif typ == 'C': low, high, sep = entry[arg] lastC = remaining = len(node[low:high]) start = len(self.f.getvalue()) for subnode in node[low:high]: self.preorder(subnode) remaining -= 1 if remaining > 0: self.write(sep) self.set_pos_info(node, start, len(self.f.getvalue())) arg += 1 elif typ == 'D': low, high, sep = entry[arg] lastC = remaining = len(node[low:high]) for subnode in node[low:high]: remaining -= 1 if len(subnode) > 0: self.preorder(subnode) if remaining > 0: self.write(sep) pass pass pass arg += 1 elif typ == 'x': src, dest = entry[arg] for d in dest: self.set_pos_info_recurse(node[d], node[src].start, node[src].finish) pass arg += 1 elif typ == 'P': p = self.prec low, high, sep, self.prec = entry[arg] lastC = remaining = len(node[low:high]) start = self.last_finish for subnode in node[low:high]: self.preorder(subnode) remaining -= 1 if remaining > 0: self.write(sep) self.prec = p arg += 1 elif typ == '{': d = node.__dict__ expr = m.group('expr') # Line mapping stuff if (hasattr(node, 'linestart') and node.linestart and hasattr(node, 'current_line_number')): self.source_linemap[self.current_line_number] = node.linestart # Additional fragment-position stuff try: start = len(self.f.getvalue()) self.write(eval(expr, d, d)) self.set_pos_info(node, start, len(self.f.getvalue())) except: print(node) raise m = escape.search(fmt, i) pass self.write(fmt[i:]) fin = len(self.f.getvalue()) if recurse_node: self.set_pos_info_recurse(startnode, startnode_start, fin) else: self.set_pos_info(startnode, startnode_start, fin) # FIXME rocky: figure out how to get these casess to be table driven. # 2. subroutine calls. It the last op is the call and for purposes of printing # we don't need to print anything special there. However it encompases the # entire string of the node fn(...) if startnode.kind == 'call': last_node = startnode[-1] self.set_pos_info(last_node, startnode_start, self.last_finish) return
def function[template_engine, parameter[self, entry, startnode]]: constant[The format template interpetation engine. See the comment at the beginning of this module for the how we interpret format specifications such as %c, %C, and so on. ] variable[startnode_start] assign[=] call[name[len], parameter[call[name[self].f.getvalue, parameter[]]]] variable[start] assign[=] name[startnode_start] variable[fmt] assign[=] call[name[entry]][constant[0]] variable[arg] assign[=] constant[1] variable[i] assign[=] constant[0] variable[lastC] assign[=] <ast.UnaryOp object at 0x7da18c4cfbb0> variable[recurse_node] assign[=] constant[False] variable[m] assign[=] call[name[escape].search, parameter[name[fmt]]] while name[m] begin[:] variable[i] assign[=] call[name[m].end, parameter[]] call[name[self].write, parameter[call[name[m].group, parameter[constant[prefix]]]]] variable[typ] assign[=] <ast.BoolOp object at 0x7da18c4ce950> variable[node] assign[=] name[startnode] <ast.Try object at 0x7da18c4cd540> if compare[name[typ] equal[==] constant[%]] begin[:] variable[start] assign[=] call[name[len], parameter[call[name[self].f.getvalue, parameter[]]]] call[name[self].write, parameter[constant[%]]] call[name[self].set_pos_info, parameter[name[node], name[start], call[name[len], parameter[call[name[self].f.getvalue, parameter[]]]]]] variable[m] assign[=] call[name[escape].search, parameter[name[fmt], name[i]]] pass call[name[self].write, parameter[call[name[fmt]][<ast.Slice object at 0x7da2044c1570>]]] variable[fin] assign[=] call[name[len], parameter[call[name[self].f.getvalue, parameter[]]]] if name[recurse_node] begin[:] call[name[self].set_pos_info_recurse, parameter[name[startnode], name[startnode_start], name[fin]]] if compare[name[startnode].kind equal[==] constant[call]] begin[:] variable[last_node] assign[=] call[name[startnode]][<ast.UnaryOp object at 0x7da2044c08b0>] call[name[self].set_pos_info, parameter[name[last_node], name[startnode_start], name[self].last_finish]] return[None]
keyword[def] identifier[template_engine] ( identifier[self] , identifier[entry] , identifier[startnode] ): literal[string] identifier[startnode_start] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) identifier[start] = identifier[startnode_start] identifier[fmt] = identifier[entry] [ literal[int] ] identifier[arg] = literal[int] identifier[i] = literal[int] identifier[lastC] =- literal[int] identifier[recurse_node] = keyword[False] identifier[m] = identifier[escape] . identifier[search] ( identifier[fmt] ) keyword[while] identifier[m] : identifier[i] = identifier[m] . identifier[end] () identifier[self] . identifier[write] ( identifier[m] . identifier[group] ( literal[string] )) identifier[typ] = identifier[m] . identifier[group] ( literal[string] ) keyword[or] literal[string] identifier[node] = identifier[startnode] keyword[try] : keyword[if] identifier[m] . identifier[group] ( literal[string] ): identifier[node] = identifier[node] [ identifier[int] ( identifier[m] . identifier[group] ( literal[string] ))] identifier[node] . identifier[parent] = identifier[startnode] keyword[except] : identifier[print] ( identifier[node] . identifier[__dict__] ) keyword[raise] keyword[if] identifier[typ] == literal[string] : identifier[start] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) identifier[self] . identifier[write] ( literal[string] ) identifier[self] . identifier[set_pos_info] ( identifier[node] , identifier[start] , identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ())) keyword[elif] identifier[typ] == literal[string] : identifier[self] . identifier[indent_more] () keyword[elif] identifier[typ] == literal[string] : identifier[self] . identifier[indent_less] () keyword[elif] identifier[typ] == literal[string] : identifier[self] . identifier[write] ( identifier[self] . identifier[indent] ) keyword[elif] identifier[typ] == literal[string] : identifier[recurse_node] = keyword[True] keyword[elif] identifier[typ] == literal[string] : keyword[if] identifier[lastC] == literal[int] : identifier[self] . identifier[write] ( literal[string] ) keyword[elif] identifier[typ] == literal[string] : identifier[finish] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) identifier[self] . identifier[set_pos_info] ( identifier[node] [ identifier[entry] [ identifier[arg] ]], identifier[start] , identifier[finish] ) identifier[arg] += literal[int] keyword[elif] identifier[typ] == literal[string] : identifier[start] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) identifier[index] = identifier[entry] [ identifier[arg] ] keyword[if] identifier[isinstance] ( identifier[index] , identifier[tuple] ): keyword[assert] identifier[node] [ identifier[index] [ literal[int] ]]== identifier[index] [ literal[int] ],( literal[string] %( identifier[node] . identifier[kind] , identifier[arg] , identifier[node] [ identifier[index] [ literal[int] ]]. identifier[kind] , identifier[index] [ literal[int] ]) ) identifier[index] = identifier[index] [ literal[int] ] keyword[assert] identifier[isinstance] ( identifier[index] , identifier[int] ),( literal[string] %( identifier[node] . identifier[kind] , identifier[arg] , identifier[type] ( identifier[index] ))) identifier[self] . identifier[preorder] ( identifier[node] [ identifier[index] ]) identifier[finish] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) identifier[self] . identifier[set_pos_info] ( identifier[node] , identifier[start] , identifier[finish] ) identifier[arg] += literal[int] keyword[elif] identifier[typ] == literal[string] : identifier[p] = identifier[self] . identifier[prec] ( identifier[index] , identifier[self] . identifier[prec] )= identifier[entry] [ identifier[arg] ] identifier[node] [ identifier[index] ]. identifier[parent] = identifier[node] identifier[start] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) identifier[self] . identifier[preorder] ( identifier[node] [ identifier[index] ]) identifier[self] . identifier[set_pos_info] ( identifier[node] , identifier[start] , identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ())) identifier[self] . identifier[prec] = identifier[p] identifier[arg] += literal[int] keyword[elif] identifier[typ] == literal[string] : identifier[low] , identifier[high] , identifier[sep] = identifier[entry] [ identifier[arg] ] identifier[lastC] = identifier[remaining] = identifier[len] ( identifier[node] [ identifier[low] : identifier[high] ]) identifier[start] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) keyword[for] identifier[subnode] keyword[in] identifier[node] [ identifier[low] : identifier[high] ]: identifier[self] . identifier[preorder] ( identifier[subnode] ) identifier[remaining] -= literal[int] keyword[if] identifier[remaining] > literal[int] : identifier[self] . identifier[write] ( identifier[sep] ) identifier[self] . identifier[set_pos_info] ( identifier[node] , identifier[start] , identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ())) identifier[arg] += literal[int] keyword[elif] identifier[typ] == literal[string] : identifier[low] , identifier[high] , identifier[sep] = identifier[entry] [ identifier[arg] ] identifier[lastC] = identifier[remaining] = identifier[len] ( identifier[node] [ identifier[low] : identifier[high] ]) keyword[for] identifier[subnode] keyword[in] identifier[node] [ identifier[low] : identifier[high] ]: identifier[remaining] -= literal[int] keyword[if] identifier[len] ( identifier[subnode] )> literal[int] : identifier[self] . identifier[preorder] ( identifier[subnode] ) keyword[if] identifier[remaining] > literal[int] : identifier[self] . identifier[write] ( identifier[sep] ) keyword[pass] keyword[pass] keyword[pass] identifier[arg] += literal[int] keyword[elif] identifier[typ] == literal[string] : identifier[src] , identifier[dest] = identifier[entry] [ identifier[arg] ] keyword[for] identifier[d] keyword[in] identifier[dest] : identifier[self] . identifier[set_pos_info_recurse] ( identifier[node] [ identifier[d] ], identifier[node] [ identifier[src] ]. identifier[start] , identifier[node] [ identifier[src] ]. identifier[finish] ) keyword[pass] identifier[arg] += literal[int] keyword[elif] identifier[typ] == literal[string] : identifier[p] = identifier[self] . identifier[prec] identifier[low] , identifier[high] , identifier[sep] , identifier[self] . identifier[prec] = identifier[entry] [ identifier[arg] ] identifier[lastC] = identifier[remaining] = identifier[len] ( identifier[node] [ identifier[low] : identifier[high] ]) identifier[start] = identifier[self] . identifier[last_finish] keyword[for] identifier[subnode] keyword[in] identifier[node] [ identifier[low] : identifier[high] ]: identifier[self] . identifier[preorder] ( identifier[subnode] ) identifier[remaining] -= literal[int] keyword[if] identifier[remaining] > literal[int] : identifier[self] . identifier[write] ( identifier[sep] ) identifier[self] . identifier[prec] = identifier[p] identifier[arg] += literal[int] keyword[elif] identifier[typ] == literal[string] : identifier[d] = identifier[node] . identifier[__dict__] identifier[expr] = identifier[m] . identifier[group] ( literal[string] ) keyword[if] ( identifier[hasattr] ( identifier[node] , literal[string] ) keyword[and] identifier[node] . identifier[linestart] keyword[and] identifier[hasattr] ( identifier[node] , literal[string] )): identifier[self] . identifier[source_linemap] [ identifier[self] . identifier[current_line_number] ]= identifier[node] . identifier[linestart] keyword[try] : identifier[start] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) identifier[self] . identifier[write] ( identifier[eval] ( identifier[expr] , identifier[d] , identifier[d] )) identifier[self] . identifier[set_pos_info] ( identifier[node] , identifier[start] , identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ())) keyword[except] : identifier[print] ( identifier[node] ) keyword[raise] identifier[m] = identifier[escape] . identifier[search] ( identifier[fmt] , identifier[i] ) keyword[pass] identifier[self] . identifier[write] ( identifier[fmt] [ identifier[i] :]) identifier[fin] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ()) keyword[if] identifier[recurse_node] : identifier[self] . identifier[set_pos_info_recurse] ( identifier[startnode] , identifier[startnode_start] , identifier[fin] ) keyword[else] : identifier[self] . identifier[set_pos_info] ( identifier[startnode] , identifier[startnode_start] , identifier[fin] ) keyword[if] identifier[startnode] . identifier[kind] == literal[string] : identifier[last_node] = identifier[startnode] [- literal[int] ] identifier[self] . identifier[set_pos_info] ( identifier[last_node] , identifier[startnode_start] , identifier[self] . identifier[last_finish] ) keyword[return]
def template_engine(self, entry, startnode): """The format template interpetation engine. See the comment at the beginning of this module for the how we interpret format specifications such as %c, %C, and so on. """ # print("-----") # print(startnode) # print(entry[0]) # print('======') startnode_start = len(self.f.getvalue()) start = startnode_start fmt = entry[0] arg = 1 i = 0 lastC = -1 recurse_node = False m = escape.search(fmt) while m: i = m.end() self.write(m.group('prefix')) typ = m.group('type') or '{' node = startnode try: if m.group('child'): node = node[int(m.group('child'))] node.parent = startnode # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except: print(node.__dict__) raise # depends on [control=['except'], data=[]] if typ == '%': start = len(self.f.getvalue()) self.write('%') self.set_pos_info(node, start, len(self.f.getvalue())) # depends on [control=['if'], data=[]] elif typ == '+': self.indent_more() # depends on [control=['if'], data=[]] elif typ == '-': self.indent_less() # depends on [control=['if'], data=[]] elif typ == '|': self.write(self.indent) # depends on [control=['if'], data=[]] # no longer used, since BUILD_TUPLE_n is pretty printed: elif typ == 'r': recurse_node = True # depends on [control=['if'], data=[]] elif typ == ',': if lastC == 1: self.write(',') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif typ == 'b': finish = len(self.f.getvalue()) self.set_pos_info(node[entry[arg]], start, finish) arg += 1 # depends on [control=['if'], data=[]] elif typ == 'c': start = len(self.f.getvalue()) index = entry[arg] if isinstance(index, tuple): assert node[index[0]] == index[1], 'at %s[%d], expected %s node; got %s' % (node.kind, arg, node[index[0]].kind, index[1]) index = index[0] # depends on [control=['if'], data=[]] assert isinstance(index, int), 'at %s[%d], %s should be int or tuple' % (node.kind, arg, type(index)) self.preorder(node[index]) finish = len(self.f.getvalue()) self.set_pos_info(node, start, finish) arg += 1 # depends on [control=['if'], data=[]] elif typ == 'p': p = self.prec (index, self.prec) = entry[arg] node[index].parent = node start = len(self.f.getvalue()) self.preorder(node[index]) self.set_pos_info(node, start, len(self.f.getvalue())) self.prec = p arg += 1 # depends on [control=['if'], data=[]] elif typ == 'C': (low, high, sep) = entry[arg] lastC = remaining = len(node[low:high]) start = len(self.f.getvalue()) for subnode in node[low:high]: self.preorder(subnode) remaining -= 1 if remaining > 0: self.write(sep) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['subnode']] self.set_pos_info(node, start, len(self.f.getvalue())) arg += 1 # depends on [control=['if'], data=[]] elif typ == 'D': (low, high, sep) = entry[arg] lastC = remaining = len(node[low:high]) for subnode in node[low:high]: remaining -= 1 if len(subnode) > 0: self.preorder(subnode) if remaining > 0: self.write(sep) pass # depends on [control=['if'], data=[]] pass # depends on [control=['if'], data=[]] pass # depends on [control=['for'], data=['subnode']] arg += 1 # depends on [control=['if'], data=[]] elif typ == 'x': (src, dest) = entry[arg] for d in dest: self.set_pos_info_recurse(node[d], node[src].start, node[src].finish) pass # depends on [control=['for'], data=['d']] arg += 1 # depends on [control=['if'], data=[]] elif typ == 'P': p = self.prec (low, high, sep, self.prec) = entry[arg] lastC = remaining = len(node[low:high]) start = self.last_finish for subnode in node[low:high]: self.preorder(subnode) remaining -= 1 if remaining > 0: self.write(sep) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['subnode']] self.prec = p arg += 1 # depends on [control=['if'], data=[]] elif typ == '{': d = node.__dict__ expr = m.group('expr') # Line mapping stuff if hasattr(node, 'linestart') and node.linestart and hasattr(node, 'current_line_number'): self.source_linemap[self.current_line_number] = node.linestart # depends on [control=['if'], data=[]] # Additional fragment-position stuff try: start = len(self.f.getvalue()) self.write(eval(expr, d, d)) self.set_pos_info(node, start, len(self.f.getvalue())) # depends on [control=['try'], data=[]] except: print(node) raise # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] m = escape.search(fmt, i) pass # depends on [control=['while'], data=[]] self.write(fmt[i:]) fin = len(self.f.getvalue()) if recurse_node: self.set_pos_info_recurse(startnode, startnode_start, fin) # depends on [control=['if'], data=[]] else: self.set_pos_info(startnode, startnode_start, fin) # FIXME rocky: figure out how to get these casess to be table driven. # 2. subroutine calls. It the last op is the call and for purposes of printing # we don't need to print anything special there. However it encompases the # entire string of the node fn(...) if startnode.kind == 'call': last_node = startnode[-1] self.set_pos_info(last_node, startnode_start, self.last_finish) # depends on [control=['if'], data=[]] return
def _iterClass(cls, prefix=''): """ Descend a Klein()'s url_map, and generate ConvertedRule() for each one """ iterableRules = [(prefix, cls, cls.app.url_map.iter_rules())] for prefix, currentClass, i in iter(iterableRules): for rule in i: converted = dumpRule(currentClass, rule, prefix) if converted.branch: continue if converted.subKlein: clsDown = namedAny(converted.subKlein) iterableRules.append((converted.rulePath, clsDown, clsDown.app.url_map.iter_rules())) yield converted
def function[_iterClass, parameter[cls, prefix]]: constant[ Descend a Klein()'s url_map, and generate ConvertedRule() for each one ] variable[iterableRules] assign[=] list[[<ast.Tuple object at 0x7da204620100>]] for taget[tuple[[<ast.Name object at 0x7da204622da0>, <ast.Name object at 0x7da204621420>, <ast.Name object at 0x7da2046235e0>]]] in starred[call[name[iter], parameter[name[iterableRules]]]] begin[:] for taget[name[rule]] in starred[name[i]] begin[:] variable[converted] assign[=] call[name[dumpRule], parameter[name[currentClass], name[rule], name[prefix]]] if name[converted].branch begin[:] continue if name[converted].subKlein begin[:] variable[clsDown] assign[=] call[name[namedAny], parameter[name[converted].subKlein]] call[name[iterableRules].append, parameter[tuple[[<ast.Attribute object at 0x7da204621f90>, <ast.Name object at 0x7da204621ab0>, <ast.Call object at 0x7da204620070>]]]] <ast.Yield object at 0x7da204623a90>
keyword[def] identifier[_iterClass] ( identifier[cls] , identifier[prefix] = literal[string] ): literal[string] identifier[iterableRules] =[( identifier[prefix] , identifier[cls] , identifier[cls] . identifier[app] . identifier[url_map] . identifier[iter_rules] ())] keyword[for] identifier[prefix] , identifier[currentClass] , identifier[i] keyword[in] identifier[iter] ( identifier[iterableRules] ): keyword[for] identifier[rule] keyword[in] identifier[i] : identifier[converted] = identifier[dumpRule] ( identifier[currentClass] , identifier[rule] , identifier[prefix] ) keyword[if] identifier[converted] . identifier[branch] : keyword[continue] keyword[if] identifier[converted] . identifier[subKlein] : identifier[clsDown] = identifier[namedAny] ( identifier[converted] . identifier[subKlein] ) identifier[iterableRules] . identifier[append] (( identifier[converted] . identifier[rulePath] , identifier[clsDown] , identifier[clsDown] . identifier[app] . identifier[url_map] . identifier[iter_rules] ())) keyword[yield] identifier[converted]
def _iterClass(cls, prefix=''): """ Descend a Klein()'s url_map, and generate ConvertedRule() for each one """ iterableRules = [(prefix, cls, cls.app.url_map.iter_rules())] for (prefix, currentClass, i) in iter(iterableRules): for rule in i: converted = dumpRule(currentClass, rule, prefix) if converted.branch: continue # depends on [control=['if'], data=[]] if converted.subKlein: clsDown = namedAny(converted.subKlein) iterableRules.append((converted.rulePath, clsDown, clsDown.app.url_map.iter_rules())) # depends on [control=['if'], data=[]] yield converted # depends on [control=['for'], data=['rule']] # depends on [control=['for'], data=[]]
def find_by_attr(node, value, name="name", maxlevel=None): """ Search for *single* node with attribute `name` having `value` but stop at `maxlevel`. Return tuple with matching nodes. Args: node: top node, start searching. value: value which need to match Keyword Args: name (str): attribute name need to match maxlevel (int): maximum decending in the node hierarchy. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d, foo=4) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> find_by_attr(f, "d") Node('/f/b/d') >>> find_by_attr(f, name="foo", value=4) Node('/f/b/d/c', foo=4) >>> find_by_attr(f, name="foo", value=8) """ return _find(node, filter_=lambda n: _filter_by_name(n, name, value), maxlevel=maxlevel)
def function[find_by_attr, parameter[node, value, name, maxlevel]]: constant[ Search for *single* node with attribute `name` having `value` but stop at `maxlevel`. Return tuple with matching nodes. Args: node: top node, start searching. value: value which need to match Keyword Args: name (str): attribute name need to match maxlevel (int): maximum decending in the node hierarchy. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d, foo=4) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> find_by_attr(f, "d") Node('/f/b/d') >>> find_by_attr(f, name="foo", value=4) Node('/f/b/d/c', foo=4) >>> find_by_attr(f, name="foo", value=8) ] return[call[name[_find], parameter[name[node]]]]
keyword[def] identifier[find_by_attr] ( identifier[node] , identifier[value] , identifier[name] = literal[string] , identifier[maxlevel] = keyword[None] ): literal[string] keyword[return] identifier[_find] ( identifier[node] , identifier[filter_] = keyword[lambda] identifier[n] : identifier[_filter_by_name] ( identifier[n] , identifier[name] , identifier[value] ), identifier[maxlevel] = identifier[maxlevel] )
def find_by_attr(node, value, name='name', maxlevel=None): """ Search for *single* node with attribute `name` having `value` but stop at `maxlevel`. Return tuple with matching nodes. Args: node: top node, start searching. value: value which need to match Keyword Args: name (str): attribute name need to match maxlevel (int): maximum decending in the node hierarchy. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d, foo=4) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> find_by_attr(f, "d") Node('/f/b/d') >>> find_by_attr(f, name="foo", value=4) Node('/f/b/d/c', foo=4) >>> find_by_attr(f, name="foo", value=8) """ return _find(node, filter_=lambda n: _filter_by_name(n, name, value), maxlevel=maxlevel)
def _die(self, msg, lnum): """Raise an Exception if file read is unexpected.""" raise Exception("**FATAL {FILE}({LNUM}): {MSG}\n".format( FILE=self.obo_file, LNUM=lnum, MSG=msg))
def function[_die, parameter[self, msg, lnum]]: constant[Raise an Exception if file read is unexpected.] <ast.Raise object at 0x7da18f58d960>
keyword[def] identifier[_die] ( identifier[self] , identifier[msg] , identifier[lnum] ): literal[string] keyword[raise] identifier[Exception] ( literal[string] . identifier[format] ( identifier[FILE] = identifier[self] . identifier[obo_file] , identifier[LNUM] = identifier[lnum] , identifier[MSG] = identifier[msg] ))
def _die(self, msg, lnum): """Raise an Exception if file read is unexpected.""" raise Exception('**FATAL {FILE}({LNUM}): {MSG}\n'.format(FILE=self.obo_file, LNUM=lnum, MSG=msg))
def rebind(self, **params): """Rebind the parameters into the URI. :return: A new `CallAPI` instance with the new parameters. """ new_params = self.__params.copy() new_params.update(params) return self.__class__(new_params, self.__action)
def function[rebind, parameter[self]]: constant[Rebind the parameters into the URI. :return: A new `CallAPI` instance with the new parameters. ] variable[new_params] assign[=] call[name[self].__params.copy, parameter[]] call[name[new_params].update, parameter[name[params]]] return[call[name[self].__class__, parameter[name[new_params], name[self].__action]]]
keyword[def] identifier[rebind] ( identifier[self] ,** identifier[params] ): literal[string] identifier[new_params] = identifier[self] . identifier[__params] . identifier[copy] () identifier[new_params] . identifier[update] ( identifier[params] ) keyword[return] identifier[self] . identifier[__class__] ( identifier[new_params] , identifier[self] . identifier[__action] )
def rebind(self, **params): """Rebind the parameters into the URI. :return: A new `CallAPI` instance with the new parameters. """ new_params = self.__params.copy() new_params.update(params) return self.__class__(new_params, self.__action)
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout): """Send an RPC to a device. See :meth:`AbstractDeviceAdapter.send_rpc`. """ adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].send_rpc(conn_id, address, rpc_id, payload, timeout)
<ast.AsyncFunctionDef object at 0x7da2049639a0>
keyword[async] keyword[def] identifier[send_rpc] ( identifier[self] , identifier[conn_id] , identifier[address] , identifier[rpc_id] , identifier[payload] , identifier[timeout] ): literal[string] identifier[adapter_id] = identifier[self] . identifier[_get_property] ( identifier[conn_id] , literal[string] ) keyword[return] keyword[await] identifier[self] . identifier[adapters] [ identifier[adapter_id] ]. identifier[send_rpc] ( identifier[conn_id] , identifier[address] , identifier[rpc_id] , identifier[payload] , identifier[timeout] )
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout): """Send an RPC to a device. See :meth:`AbstractDeviceAdapter.send_rpc`. """ adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].send_rpc(conn_id, address, rpc_id, payload, timeout)
def isatty(self): # nocover """ Returns true of the redirect is a terminal. Notes: Needed for IPython.embed to work properly when this class is used to override stdout / stderr. """ return (self.redirect is not None and hasattr(self.redirect, 'isatty') and self.redirect.isatty())
def function[isatty, parameter[self]]: constant[ Returns true of the redirect is a terminal. Notes: Needed for IPython.embed to work properly when this class is used to override stdout / stderr. ] return[<ast.BoolOp object at 0x7da1b015aa70>]
keyword[def] identifier[isatty] ( identifier[self] ): literal[string] keyword[return] ( identifier[self] . identifier[redirect] keyword[is] keyword[not] keyword[None] keyword[and] identifier[hasattr] ( identifier[self] . identifier[redirect] , literal[string] ) keyword[and] identifier[self] . identifier[redirect] . identifier[isatty] ())
def isatty(self): # nocover '\n Returns true of the redirect is a terminal.\n\n Notes:\n Needed for IPython.embed to work properly when this class is used\n to override stdout / stderr.\n ' return self.redirect is not None and hasattr(self.redirect, 'isatty') and self.redirect.isatty()
def update_configuration(self, **kwargs): """ Update configuration using valid kwargs as defined in the enable constructor. :param dict kwargs: kwargs to satisfy valid args from `enable` :rtype: bool """ updated = False if 'announced_networks' in kwargs: kwargs.update(announced_ne_setting=kwargs.pop('announced_networks')) if 'bgp_profile' in kwargs: kwargs.update(bgp_profile_ref=kwargs.pop('bgp_profile')) if 'autonomous_system' in kwargs: kwargs.update(bgp_as_ref=kwargs.pop('autonomous_system')) announced_ne = kwargs.pop('announced_ne_setting', None) for name, value in kwargs.items(): _value = element_resolver(value) if self.data.get(name) != _value: self.data[name] = _value updated = True if announced_ne is not None: s = self.data.get('announced_ne_setting') ne = self._unwrap(announced_ne) if len(announced_ne) != len(s) or not self._equal(ne, s): self.data.update(announced_ne_setting=ne) updated = True return updated
def function[update_configuration, parameter[self]]: constant[ Update configuration using valid kwargs as defined in the enable constructor. :param dict kwargs: kwargs to satisfy valid args from `enable` :rtype: bool ] variable[updated] assign[=] constant[False] if compare[constant[announced_networks] in name[kwargs]] begin[:] call[name[kwargs].update, parameter[]] if compare[constant[bgp_profile] in name[kwargs]] begin[:] call[name[kwargs].update, parameter[]] if compare[constant[autonomous_system] in name[kwargs]] begin[:] call[name[kwargs].update, parameter[]] variable[announced_ne] assign[=] call[name[kwargs].pop, parameter[constant[announced_ne_setting], constant[None]]] for taget[tuple[[<ast.Name object at 0x7da1b1bc2ef0>, <ast.Name object at 0x7da1b1bc1270>]]] in starred[call[name[kwargs].items, parameter[]]] begin[:] variable[_value] assign[=] call[name[element_resolver], parameter[name[value]]] if compare[call[name[self].data.get, parameter[name[name]]] not_equal[!=] name[_value]] begin[:] call[name[self].data][name[name]] assign[=] name[_value] variable[updated] assign[=] constant[True] if compare[name[announced_ne] is_not constant[None]] begin[:] variable[s] assign[=] call[name[self].data.get, parameter[constant[announced_ne_setting]]] variable[ne] assign[=] call[name[self]._unwrap, parameter[name[announced_ne]]] if <ast.BoolOp object at 0x7da1b1bc1b40> begin[:] call[name[self].data.update, parameter[]] variable[updated] assign[=] constant[True] return[name[updated]]
keyword[def] identifier[update_configuration] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[updated] = keyword[False] keyword[if] literal[string] keyword[in] identifier[kwargs] : identifier[kwargs] . identifier[update] ( identifier[announced_ne_setting] = identifier[kwargs] . identifier[pop] ( literal[string] )) keyword[if] literal[string] keyword[in] identifier[kwargs] : identifier[kwargs] . identifier[update] ( identifier[bgp_profile_ref] = identifier[kwargs] . identifier[pop] ( literal[string] )) keyword[if] literal[string] keyword[in] identifier[kwargs] : identifier[kwargs] . identifier[update] ( identifier[bgp_as_ref] = identifier[kwargs] . identifier[pop] ( literal[string] )) identifier[announced_ne] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] ) keyword[for] identifier[name] , identifier[value] keyword[in] identifier[kwargs] . identifier[items] (): identifier[_value] = identifier[element_resolver] ( identifier[value] ) keyword[if] identifier[self] . identifier[data] . identifier[get] ( identifier[name] )!= identifier[_value] : identifier[self] . identifier[data] [ identifier[name] ]= identifier[_value] identifier[updated] = keyword[True] keyword[if] identifier[announced_ne] keyword[is] keyword[not] keyword[None] : identifier[s] = identifier[self] . identifier[data] . identifier[get] ( literal[string] ) identifier[ne] = identifier[self] . identifier[_unwrap] ( identifier[announced_ne] ) keyword[if] identifier[len] ( identifier[announced_ne] )!= identifier[len] ( identifier[s] ) keyword[or] keyword[not] identifier[self] . identifier[_equal] ( identifier[ne] , identifier[s] ): identifier[self] . identifier[data] . identifier[update] ( identifier[announced_ne_setting] = identifier[ne] ) identifier[updated] = keyword[True] keyword[return] identifier[updated]
def update_configuration(self, **kwargs): """ Update configuration using valid kwargs as defined in the enable constructor. :param dict kwargs: kwargs to satisfy valid args from `enable` :rtype: bool """ updated = False if 'announced_networks' in kwargs: kwargs.update(announced_ne_setting=kwargs.pop('announced_networks')) # depends on [control=['if'], data=['kwargs']] if 'bgp_profile' in kwargs: kwargs.update(bgp_profile_ref=kwargs.pop('bgp_profile')) # depends on [control=['if'], data=['kwargs']] if 'autonomous_system' in kwargs: kwargs.update(bgp_as_ref=kwargs.pop('autonomous_system')) # depends on [control=['if'], data=['kwargs']] announced_ne = kwargs.pop('announced_ne_setting', None) for (name, value) in kwargs.items(): _value = element_resolver(value) if self.data.get(name) != _value: self.data[name] = _value updated = True # depends on [control=['if'], data=['_value']] # depends on [control=['for'], data=[]] if announced_ne is not None: s = self.data.get('announced_ne_setting') ne = self._unwrap(announced_ne) if len(announced_ne) != len(s) or not self._equal(ne, s): self.data.update(announced_ne_setting=ne) updated = True # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['announced_ne']] return updated
def _create_node_matrix_from_coord_section(specs): """Transformed parsed data from NODE_COORD_SECTION into an upper triangular matrix Calculates distances between nodes 'MATRIX' key added to `specs` """ distances = specs['NODE_COORD_SECTION'] specs['MATRIX'] = {} for i in distances: origin = tuple(distances[i]) specs['MATRIX'][i] = {} for j in specs['NODE_COORD_SECTION']: destination = tuple(distances[j]) distance = calculate_euc_distance(origin, destination) # # Upper triangular matrix # if i > j, ij = 0 # #if i > j: # continue specs['MATRIX'][i][j] = distance
def function[_create_node_matrix_from_coord_section, parameter[specs]]: constant[Transformed parsed data from NODE_COORD_SECTION into an upper triangular matrix Calculates distances between nodes 'MATRIX' key added to `specs` ] variable[distances] assign[=] call[name[specs]][constant[NODE_COORD_SECTION]] call[name[specs]][constant[MATRIX]] assign[=] dictionary[[], []] for taget[name[i]] in starred[name[distances]] begin[:] variable[origin] assign[=] call[name[tuple], parameter[call[name[distances]][name[i]]]] call[call[name[specs]][constant[MATRIX]]][name[i]] assign[=] dictionary[[], []] for taget[name[j]] in starred[call[name[specs]][constant[NODE_COORD_SECTION]]] begin[:] variable[destination] assign[=] call[name[tuple], parameter[call[name[distances]][name[j]]]] variable[distance] assign[=] call[name[calculate_euc_distance], parameter[name[origin], name[destination]]] call[call[call[name[specs]][constant[MATRIX]]][name[i]]][name[j]] assign[=] name[distance]
keyword[def] identifier[_create_node_matrix_from_coord_section] ( identifier[specs] ): literal[string] identifier[distances] = identifier[specs] [ literal[string] ] identifier[specs] [ literal[string] ]={} keyword[for] identifier[i] keyword[in] identifier[distances] : identifier[origin] = identifier[tuple] ( identifier[distances] [ identifier[i] ]) identifier[specs] [ literal[string] ][ identifier[i] ]={} keyword[for] identifier[j] keyword[in] identifier[specs] [ literal[string] ]: identifier[destination] = identifier[tuple] ( identifier[distances] [ identifier[j] ]) identifier[distance] = identifier[calculate_euc_distance] ( identifier[origin] , identifier[destination] ) identifier[specs] [ literal[string] ][ identifier[i] ][ identifier[j] ]= identifier[distance]
def _create_node_matrix_from_coord_section(specs): """Transformed parsed data from NODE_COORD_SECTION into an upper triangular matrix Calculates distances between nodes 'MATRIX' key added to `specs` """ distances = specs['NODE_COORD_SECTION'] specs['MATRIX'] = {} for i in distances: origin = tuple(distances[i]) specs['MATRIX'][i] = {} for j in specs['NODE_COORD_SECTION']: destination = tuple(distances[j]) distance = calculate_euc_distance(origin, destination) # # Upper triangular matrix # if i > j, ij = 0 # #if i > j: # continue specs['MATRIX'][i][j] = distance # depends on [control=['for'], data=['j']] # depends on [control=['for'], data=['i']]
def _zforce(self,R,z,phi=0.,t=0.,v=None): """ NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time v= current velocity in cylindrical coordinates OUTPUT: the vertical force HISTORY: 2018-03-18 - Started - Bovy (UofT) """ new_hash= hashlib.md5(numpy.array([R,phi,z,v[0],v[1],v[2],t]))\ .hexdigest() if new_hash != self._force_hash: self._calc_force(R,phi,z,v,t) return self._cached_force*v[2]
def function[_zforce, parameter[self, R, z, phi, t, v]]: constant[ NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time v= current velocity in cylindrical coordinates OUTPUT: the vertical force HISTORY: 2018-03-18 - Started - Bovy (UofT) ] variable[new_hash] assign[=] call[call[name[hashlib].md5, parameter[call[name[numpy].array, parameter[list[[<ast.Name object at 0x7da1b0e9fa90>, <ast.Name object at 0x7da1b0e9d240>, <ast.Name object at 0x7da1b0e9edd0>, <ast.Subscript object at 0x7da1b0e9f910>, <ast.Subscript object at 0x7da1b0e9c6a0>, <ast.Subscript object at 0x7da1b0e9f1f0>, <ast.Name object at 0x7da1b0e9ceb0>]]]]]].hexdigest, parameter[]] if compare[name[new_hash] not_equal[!=] name[self]._force_hash] begin[:] call[name[self]._calc_force, parameter[name[R], name[phi], name[z], name[v], name[t]]] return[binary_operation[name[self]._cached_force * call[name[v]][constant[2]]]]
keyword[def] identifier[_zforce] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] , identifier[v] = keyword[None] ): literal[string] identifier[new_hash] = identifier[hashlib] . identifier[md5] ( identifier[numpy] . identifier[array] ([ identifier[R] , identifier[phi] , identifier[z] , identifier[v] [ literal[int] ], identifier[v] [ literal[int] ], identifier[v] [ literal[int] ], identifier[t] ])). identifier[hexdigest] () keyword[if] identifier[new_hash] != identifier[self] . identifier[_force_hash] : identifier[self] . identifier[_calc_force] ( identifier[R] , identifier[phi] , identifier[z] , identifier[v] , identifier[t] ) keyword[return] identifier[self] . identifier[_cached_force] * identifier[v] [ literal[int] ]
def _zforce(self, R, z, phi=0.0, t=0.0, v=None): """ NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time v= current velocity in cylindrical coordinates OUTPUT: the vertical force HISTORY: 2018-03-18 - Started - Bovy (UofT) """ new_hash = hashlib.md5(numpy.array([R, phi, z, v[0], v[1], v[2], t])).hexdigest() if new_hash != self._force_hash: self._calc_force(R, phi, z, v, t) # depends on [control=['if'], data=[]] return self._cached_force * v[2]
def _get_cct(x, y, z): """ Reference Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999). Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities. Applied Optics, 38(27), 5703-5709. """ x_e = 0.3320 y_e = 0.1858 n = ((x / (x + z + z)) - x_e) / ((y / (x + z + z)) - y_e) a_0 = -949.86315 a_1 = 6253.80338 a_2 = 28.70599 a_3 = 0.00004 t_1 = 0.92159 t_2 = 0.20039 t_3 = 0.07125 cct = a_0 + a_1 * numpy.exp(-n / t_1) + a_2 * numpy.exp(-n / t_2) + a_3 * numpy.exp(-n / t_3) return cct
def function[_get_cct, parameter[x, y, z]]: constant[ Reference Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999). Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities. Applied Optics, 38(27), 5703-5709. ] variable[x_e] assign[=] constant[0.332] variable[y_e] assign[=] constant[0.1858] variable[n] assign[=] binary_operation[binary_operation[binary_operation[name[x] / binary_operation[binary_operation[name[x] + name[z]] + name[z]]] - name[x_e]] / binary_operation[binary_operation[name[y] / binary_operation[binary_operation[name[x] + name[z]] + name[z]]] - name[y_e]]] variable[a_0] assign[=] <ast.UnaryOp object at 0x7da2041d9630> variable[a_1] assign[=] constant[6253.80338] variable[a_2] assign[=] constant[28.70599] variable[a_3] assign[=] constant[4e-05] variable[t_1] assign[=] constant[0.92159] variable[t_2] assign[=] constant[0.20039] variable[t_3] assign[=] constant[0.07125] variable[cct] assign[=] binary_operation[binary_operation[binary_operation[name[a_0] + binary_operation[name[a_1] * call[name[numpy].exp, parameter[binary_operation[<ast.UnaryOp object at 0x7da2041d9c30> / name[t_1]]]]]] + binary_operation[name[a_2] * call[name[numpy].exp, parameter[binary_operation[<ast.UnaryOp object at 0x7da2041da170> / name[t_2]]]]]] + binary_operation[name[a_3] * call[name[numpy].exp, parameter[binary_operation[<ast.UnaryOp object at 0x7da2041db4c0> / name[t_3]]]]]] return[name[cct]]
keyword[def] identifier[_get_cct] ( identifier[x] , identifier[y] , identifier[z] ): literal[string] identifier[x_e] = literal[int] identifier[y_e] = literal[int] identifier[n] =(( identifier[x] /( identifier[x] + identifier[z] + identifier[z] ))- identifier[x_e] )/(( identifier[y] /( identifier[x] + identifier[z] + identifier[z] ))- identifier[y_e] ) identifier[a_0] =- literal[int] identifier[a_1] = literal[int] identifier[a_2] = literal[int] identifier[a_3] = literal[int] identifier[t_1] = literal[int] identifier[t_2] = literal[int] identifier[t_3] = literal[int] identifier[cct] = identifier[a_0] + identifier[a_1] * identifier[numpy] . identifier[exp] (- identifier[n] / identifier[t_1] )+ identifier[a_2] * identifier[numpy] . identifier[exp] (- identifier[n] / identifier[t_2] )+ identifier[a_3] * identifier[numpy] . identifier[exp] (- identifier[n] / identifier[t_3] ) keyword[return] identifier[cct]
def _get_cct(x, y, z): """ Reference Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999). Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities. Applied Optics, 38(27), 5703-5709. """ x_e = 0.332 y_e = 0.1858 n = (x / (x + z + z) - x_e) / (y / (x + z + z) - y_e) a_0 = -949.86315 a_1 = 6253.80338 a_2 = 28.70599 a_3 = 4e-05 t_1 = 0.92159 t_2 = 0.20039 t_3 = 0.07125 cct = a_0 + a_1 * numpy.exp(-n / t_1) + a_2 * numpy.exp(-n / t_2) + a_3 * numpy.exp(-n / t_3) return cct
def to_auto(name, value, source='auto', convert_to_human=True): ''' Convert python value to zfs value ''' return _auto('to', name, value, source, convert_to_human)
def function[to_auto, parameter[name, value, source, convert_to_human]]: constant[ Convert python value to zfs value ] return[call[name[_auto], parameter[constant[to], name[name], name[value], name[source], name[convert_to_human]]]]
keyword[def] identifier[to_auto] ( identifier[name] , identifier[value] , identifier[source] = literal[string] , identifier[convert_to_human] = keyword[True] ): literal[string] keyword[return] identifier[_auto] ( literal[string] , identifier[name] , identifier[value] , identifier[source] , identifier[convert_to_human] )
def to_auto(name, value, source='auto', convert_to_human=True): """ Convert python value to zfs value """ return _auto('to', name, value, source, convert_to_human)
def disconnect(self, sock): """Handles socket disconnections""" self.log("Disconnect ", sock, lvl=debug) try: if sock in self._sockets: self.log("Getting socket", lvl=debug) sockobj = self._sockets[sock] self.log("Getting clientuuid", lvl=debug) clientuuid = sockobj.clientuuid self.log("getting useruuid", lvl=debug) useruuid = self._clients[clientuuid].useruuid self.log("Firing disconnect event", lvl=debug) self.fireEvent(clientdisconnect(clientuuid, self._clients[ clientuuid].useruuid)) self.log("Logging out relevant client", lvl=debug) if useruuid is not None: self.log("Client was logged in", lvl=debug) try: self._logoutclient(useruuid, clientuuid) self.log("Client logged out", useruuid, clientuuid) except Exception as e: self.log("Couldn't clean up logged in user! ", self._users[useruuid], e, type(e), lvl=critical) self.log("Deleting Client (", self._clients.keys, ")", lvl=debug) del self._clients[clientuuid] self.log("Deleting Socket", lvl=debug) del self._sockets[sock] except Exception as e: self.log("Error during disconnect handling: ", e, type(e), lvl=critical)
def function[disconnect, parameter[self, sock]]: constant[Handles socket disconnections] call[name[self].log, parameter[constant[Disconnect ], name[sock]]] <ast.Try object at 0x7da1b0e60340>
keyword[def] identifier[disconnect] ( identifier[self] , identifier[sock] ): literal[string] identifier[self] . identifier[log] ( literal[string] , identifier[sock] , identifier[lvl] = identifier[debug] ) keyword[try] : keyword[if] identifier[sock] keyword[in] identifier[self] . identifier[_sockets] : identifier[self] . identifier[log] ( literal[string] , identifier[lvl] = identifier[debug] ) identifier[sockobj] = identifier[self] . identifier[_sockets] [ identifier[sock] ] identifier[self] . identifier[log] ( literal[string] , identifier[lvl] = identifier[debug] ) identifier[clientuuid] = identifier[sockobj] . identifier[clientuuid] identifier[self] . identifier[log] ( literal[string] , identifier[lvl] = identifier[debug] ) identifier[useruuid] = identifier[self] . identifier[_clients] [ identifier[clientuuid] ]. identifier[useruuid] identifier[self] . identifier[log] ( literal[string] , identifier[lvl] = identifier[debug] ) identifier[self] . identifier[fireEvent] ( identifier[clientdisconnect] ( identifier[clientuuid] , identifier[self] . identifier[_clients] [ identifier[clientuuid] ]. identifier[useruuid] )) identifier[self] . identifier[log] ( literal[string] , identifier[lvl] = identifier[debug] ) keyword[if] identifier[useruuid] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[log] ( literal[string] , identifier[lvl] = identifier[debug] ) keyword[try] : identifier[self] . identifier[_logoutclient] ( identifier[useruuid] , identifier[clientuuid] ) identifier[self] . identifier[log] ( literal[string] , identifier[useruuid] , identifier[clientuuid] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[self] . identifier[log] ( literal[string] , identifier[self] . identifier[_users] [ identifier[useruuid] ], identifier[e] , identifier[type] ( identifier[e] ), identifier[lvl] = identifier[critical] ) identifier[self] . identifier[log] ( literal[string] , identifier[self] . identifier[_clients] . identifier[keys] , literal[string] , identifier[lvl] = identifier[debug] ) keyword[del] identifier[self] . identifier[_clients] [ identifier[clientuuid] ] identifier[self] . identifier[log] ( literal[string] , identifier[lvl] = identifier[debug] ) keyword[del] identifier[self] . identifier[_sockets] [ identifier[sock] ] keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[self] . identifier[log] ( literal[string] , identifier[e] , identifier[type] ( identifier[e] ), identifier[lvl] = identifier[critical] )
def disconnect(self, sock): """Handles socket disconnections""" self.log('Disconnect ', sock, lvl=debug) try: if sock in self._sockets: self.log('Getting socket', lvl=debug) sockobj = self._sockets[sock] self.log('Getting clientuuid', lvl=debug) clientuuid = sockobj.clientuuid self.log('getting useruuid', lvl=debug) useruuid = self._clients[clientuuid].useruuid self.log('Firing disconnect event', lvl=debug) self.fireEvent(clientdisconnect(clientuuid, self._clients[clientuuid].useruuid)) self.log('Logging out relevant client', lvl=debug) if useruuid is not None: self.log('Client was logged in', lvl=debug) try: self._logoutclient(useruuid, clientuuid) self.log('Client logged out', useruuid, clientuuid) # depends on [control=['try'], data=[]] except Exception as e: self.log("Couldn't clean up logged in user! ", self._users[useruuid], e, type(e), lvl=critical) # depends on [control=['except'], data=['e']] # depends on [control=['if'], data=['useruuid']] self.log('Deleting Client (', self._clients.keys, ')', lvl=debug) del self._clients[clientuuid] self.log('Deleting Socket', lvl=debug) del self._sockets[sock] # depends on [control=['if'], data=['sock']] # depends on [control=['try'], data=[]] except Exception as e: self.log('Error during disconnect handling: ', e, type(e), lvl=critical) # depends on [control=['except'], data=['e']]
def get_metadata_parser(metadata_container, **metadata_defaults): """ Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_content) for more on types of content that can be parsed """ parser_type = None if isinstance(metadata_container, MetadataParser): parser_type = type(metadata_container) elif isinstance(metadata_container, type): parser_type = metadata_container metadata_container = metadata_container().update(**metadata_defaults) xml_root, xml_tree = get_parsed_content(metadata_container) # The get_parsed_content method ensures only these roots will be returned parser = None if parser_type is not None: parser = parser_type(xml_tree, **metadata_defaults) elif xml_root in ISO_ROOTS: parser = IsoParser(xml_tree, **metadata_defaults) else: has_arcgis_data = any(element_exists(xml_tree, e) for e in ARCGIS_NODES) if xml_root == FGDC_ROOT and not has_arcgis_data: parser = FgdcParser(xml_tree, **metadata_defaults) elif xml_root in ARCGIS_ROOTS: parser = ArcGISParser(xml_tree, **metadata_defaults) return parser
def function[get_metadata_parser, parameter[metadata_container]]: constant[ Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_content) for more on types of content that can be parsed ] variable[parser_type] assign[=] constant[None] if call[name[isinstance], parameter[name[metadata_container], name[MetadataParser]]] begin[:] variable[parser_type] assign[=] call[name[type], parameter[name[metadata_container]]] <ast.Tuple object at 0x7da1b0e326b0> assign[=] call[name[get_parsed_content], parameter[name[metadata_container]]] variable[parser] assign[=] constant[None] if compare[name[parser_type] is_not constant[None]] begin[:] variable[parser] assign[=] call[name[parser_type], parameter[name[xml_tree]]] return[name[parser]]
keyword[def] identifier[get_metadata_parser] ( identifier[metadata_container] ,** identifier[metadata_defaults] ): literal[string] identifier[parser_type] = keyword[None] keyword[if] identifier[isinstance] ( identifier[metadata_container] , identifier[MetadataParser] ): identifier[parser_type] = identifier[type] ( identifier[metadata_container] ) keyword[elif] identifier[isinstance] ( identifier[metadata_container] , identifier[type] ): identifier[parser_type] = identifier[metadata_container] identifier[metadata_container] = identifier[metadata_container] (). identifier[update] (** identifier[metadata_defaults] ) identifier[xml_root] , identifier[xml_tree] = identifier[get_parsed_content] ( identifier[metadata_container] ) identifier[parser] = keyword[None] keyword[if] identifier[parser_type] keyword[is] keyword[not] keyword[None] : identifier[parser] = identifier[parser_type] ( identifier[xml_tree] ,** identifier[metadata_defaults] ) keyword[elif] identifier[xml_root] keyword[in] identifier[ISO_ROOTS] : identifier[parser] = identifier[IsoParser] ( identifier[xml_tree] ,** identifier[metadata_defaults] ) keyword[else] : identifier[has_arcgis_data] = identifier[any] ( identifier[element_exists] ( identifier[xml_tree] , identifier[e] ) keyword[for] identifier[e] keyword[in] identifier[ARCGIS_NODES] ) keyword[if] identifier[xml_root] == identifier[FGDC_ROOT] keyword[and] keyword[not] identifier[has_arcgis_data] : identifier[parser] = identifier[FgdcParser] ( identifier[xml_tree] ,** identifier[metadata_defaults] ) keyword[elif] identifier[xml_root] keyword[in] identifier[ARCGIS_ROOTS] : identifier[parser] = identifier[ArcGISParser] ( identifier[xml_tree] ,** identifier[metadata_defaults] ) keyword[return] identifier[parser]
def get_metadata_parser(metadata_container, **metadata_defaults): """ Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_content) for more on types of content that can be parsed """ parser_type = None if isinstance(metadata_container, MetadataParser): parser_type = type(metadata_container) # depends on [control=['if'], data=[]] elif isinstance(metadata_container, type): parser_type = metadata_container metadata_container = metadata_container().update(**metadata_defaults) # depends on [control=['if'], data=[]] (xml_root, xml_tree) = get_parsed_content(metadata_container) # The get_parsed_content method ensures only these roots will be returned parser = None if parser_type is not None: parser = parser_type(xml_tree, **metadata_defaults) # depends on [control=['if'], data=['parser_type']] elif xml_root in ISO_ROOTS: parser = IsoParser(xml_tree, **metadata_defaults) # depends on [control=['if'], data=[]] else: has_arcgis_data = any((element_exists(xml_tree, e) for e in ARCGIS_NODES)) if xml_root == FGDC_ROOT and (not has_arcgis_data): parser = FgdcParser(xml_tree, **metadata_defaults) # depends on [control=['if'], data=[]] elif xml_root in ARCGIS_ROOTS: parser = ArcGISParser(xml_tree, **metadata_defaults) # depends on [control=['if'], data=[]] return parser
def add_arguments(self, parser): """Adds the arguments for the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None`` """ group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-d', '--downgrade', action='store_true', help='downgrade the J-Link firmware') group.add_argument('-u', '--upgrade', action='store_true', help='upgrade the J-Link firmware') return self.add_common_arguments(parser, False)
def function[add_arguments, parameter[self, parser]]: constant[Adds the arguments for the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None`` ] variable[group] assign[=] call[name[parser].add_mutually_exclusive_group, parameter[]] call[name[group].add_argument, parameter[constant[-d], constant[--downgrade]]] call[name[group].add_argument, parameter[constant[-u], constant[--upgrade]]] return[call[name[self].add_common_arguments, parameter[name[parser], constant[False]]]]
keyword[def] identifier[add_arguments] ( identifier[self] , identifier[parser] ): literal[string] identifier[group] = identifier[parser] . identifier[add_mutually_exclusive_group] ( identifier[required] = keyword[True] ) identifier[group] . identifier[add_argument] ( literal[string] , literal[string] , identifier[action] = literal[string] , identifier[help] = literal[string] ) identifier[group] . identifier[add_argument] ( literal[string] , literal[string] , identifier[action] = literal[string] , identifier[help] = literal[string] ) keyword[return] identifier[self] . identifier[add_common_arguments] ( identifier[parser] , keyword[False] )
def add_arguments(self, parser): """Adds the arguments for the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None`` """ group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-d', '--downgrade', action='store_true', help='downgrade the J-Link firmware') group.add_argument('-u', '--upgrade', action='store_true', help='upgrade the J-Link firmware') return self.add_common_arguments(parser, False)
def detect_current_filename(): ''' Attempt to return the filename of the currently running Python process Returns None if the filename cannot be detected. ''' import inspect filename = None frame = inspect.currentframe() try: while frame.f_back and frame.f_globals.get('name') != '__main__': frame = frame.f_back filename = frame.f_globals.get('__file__') finally: del frame return filename
def function[detect_current_filename, parameter[]]: constant[ Attempt to return the filename of the currently running Python process Returns None if the filename cannot be detected. ] import module[inspect] variable[filename] assign[=] constant[None] variable[frame] assign[=] call[name[inspect].currentframe, parameter[]] <ast.Try object at 0x7da18f8113c0> return[name[filename]]
keyword[def] identifier[detect_current_filename] (): literal[string] keyword[import] identifier[inspect] identifier[filename] = keyword[None] identifier[frame] = identifier[inspect] . identifier[currentframe] () keyword[try] : keyword[while] identifier[frame] . identifier[f_back] keyword[and] identifier[frame] . identifier[f_globals] . identifier[get] ( literal[string] )!= literal[string] : identifier[frame] = identifier[frame] . identifier[f_back] identifier[filename] = identifier[frame] . identifier[f_globals] . identifier[get] ( literal[string] ) keyword[finally] : keyword[del] identifier[frame] keyword[return] identifier[filename]
def detect_current_filename(): """ Attempt to return the filename of the currently running Python process Returns None if the filename cannot be detected. """ import inspect filename = None frame = inspect.currentframe() try: while frame.f_back and frame.f_globals.get('name') != '__main__': frame = frame.f_back # depends on [control=['while'], data=[]] filename = frame.f_globals.get('__file__') # depends on [control=['try'], data=[]] finally: del frame return filename
def handle_event(self, raiden_event: RaidenEvent) -> Greenlet: """Spawn a new thread to handle a Raiden event. This will spawn a new greenlet to handle each event, which is important for two reasons: - Blockchain transactions can be queued without interfering with each other. - The calling thread is free to do more work. This is specially important for the AlarmTask thread, which will eventually cause the node to send transactions when a given Block is reached (e.g. registering a secret or settling a channel). Important: This is spawing a new greenlet for /each/ transaction. It's therefore /required/ that there is *NO* order among these. """ return gevent.spawn(self._handle_event, raiden_event)
def function[handle_event, parameter[self, raiden_event]]: constant[Spawn a new thread to handle a Raiden event. This will spawn a new greenlet to handle each event, which is important for two reasons: - Blockchain transactions can be queued without interfering with each other. - The calling thread is free to do more work. This is specially important for the AlarmTask thread, which will eventually cause the node to send transactions when a given Block is reached (e.g. registering a secret or settling a channel). Important: This is spawing a new greenlet for /each/ transaction. It's therefore /required/ that there is *NO* order among these. ] return[call[name[gevent].spawn, parameter[name[self]._handle_event, name[raiden_event]]]]
keyword[def] identifier[handle_event] ( identifier[self] , identifier[raiden_event] : identifier[RaidenEvent] )-> identifier[Greenlet] : literal[string] keyword[return] identifier[gevent] . identifier[spawn] ( identifier[self] . identifier[_handle_event] , identifier[raiden_event] )
def handle_event(self, raiden_event: RaidenEvent) -> Greenlet: """Spawn a new thread to handle a Raiden event. This will spawn a new greenlet to handle each event, which is important for two reasons: - Blockchain transactions can be queued without interfering with each other. - The calling thread is free to do more work. This is specially important for the AlarmTask thread, which will eventually cause the node to send transactions when a given Block is reached (e.g. registering a secret or settling a channel). Important: This is spawing a new greenlet for /each/ transaction. It's therefore /required/ that there is *NO* order among these. """ return gevent.spawn(self._handle_event, raiden_event)
def transaction_retry(max_retries=1): """Decorator for methods doing database operations. If the database operation fails, it will retry the operation at most ``max_retries`` times. """ def _outer(fun): @wraps(fun) def _inner(*args, **kwargs): _max_retries = kwargs.pop('exception_retry_count', max_retries) for retries in count(0): try: return fun(*args, **kwargs) except Exception: # pragma: no cover # Depending on the database backend used we can experience # various exceptions. E.g. psycopg2 raises an exception # if some operation breaks the transaction, so saving # the task result won't be possible until we rollback # the transaction. if retries >= _max_retries: raise try: rollback_unless_managed() except Exception: pass return _inner return _outer
def function[transaction_retry, parameter[max_retries]]: constant[Decorator for methods doing database operations. If the database operation fails, it will retry the operation at most ``max_retries`` times. ] def function[_outer, parameter[fun]]: def function[_inner, parameter[]]: variable[_max_retries] assign[=] call[name[kwargs].pop, parameter[constant[exception_retry_count], name[max_retries]]] for taget[name[retries]] in starred[call[name[count], parameter[constant[0]]]] begin[:] <ast.Try object at 0x7da18f09c550> return[name[_inner]] return[name[_outer]]
keyword[def] identifier[transaction_retry] ( identifier[max_retries] = literal[int] ): literal[string] keyword[def] identifier[_outer] ( identifier[fun] ): @ identifier[wraps] ( identifier[fun] ) keyword[def] identifier[_inner] (* identifier[args] ,** identifier[kwargs] ): identifier[_max_retries] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[max_retries] ) keyword[for] identifier[retries] keyword[in] identifier[count] ( literal[int] ): keyword[try] : keyword[return] identifier[fun] (* identifier[args] ,** identifier[kwargs] ) keyword[except] identifier[Exception] : keyword[if] identifier[retries] >= identifier[_max_retries] : keyword[raise] keyword[try] : identifier[rollback_unless_managed] () keyword[except] identifier[Exception] : keyword[pass] keyword[return] identifier[_inner] keyword[return] identifier[_outer]
def transaction_retry(max_retries=1): """Decorator for methods doing database operations. If the database operation fails, it will retry the operation at most ``max_retries`` times. """ def _outer(fun): @wraps(fun) def _inner(*args, **kwargs): _max_retries = kwargs.pop('exception_retry_count', max_retries) for retries in count(0): try: return fun(*args, **kwargs) # depends on [control=['try'], data=[]] except Exception: # pragma: no cover # Depending on the database backend used we can experience # various exceptions. E.g. psycopg2 raises an exception # if some operation breaks the transaction, so saving # the task result won't be possible until we rollback # the transaction. if retries >= _max_retries: raise # depends on [control=['if'], data=[]] try: rollback_unless_managed() # depends on [control=['try'], data=[]] except Exception: pass # depends on [control=['except'], data=[]] # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['retries']] return _inner return _outer
def visitShapeOr(self, ctx: ShExDocParser.ShapeOrContext): """ shapeOr: shapeAnd (KW_OR shapeAnd)* """ if len(ctx.shapeAnd()) > 1: self.expr = ShapeOr(id=self.label, shapeExprs=[]) for sa in ctx.shapeAnd(): sep = ShexShapeExpressionParser(self.context) sep.visit(sa) self.expr.shapeExprs.append(sep.expr) else: self.visit(ctx.shapeAnd(0))
def function[visitShapeOr, parameter[self, ctx]]: constant[ shapeOr: shapeAnd (KW_OR shapeAnd)* ] if compare[call[name[len], parameter[call[name[ctx].shapeAnd, parameter[]]]] greater[>] constant[1]] begin[:] name[self].expr assign[=] call[name[ShapeOr], parameter[]] for taget[name[sa]] in starred[call[name[ctx].shapeAnd, parameter[]]] begin[:] variable[sep] assign[=] call[name[ShexShapeExpressionParser], parameter[name[self].context]] call[name[sep].visit, parameter[name[sa]]] call[name[self].expr.shapeExprs.append, parameter[name[sep].expr]]
keyword[def] identifier[visitShapeOr] ( identifier[self] , identifier[ctx] : identifier[ShExDocParser] . identifier[ShapeOrContext] ): literal[string] keyword[if] identifier[len] ( identifier[ctx] . identifier[shapeAnd] ())> literal[int] : identifier[self] . identifier[expr] = identifier[ShapeOr] ( identifier[id] = identifier[self] . identifier[label] , identifier[shapeExprs] =[]) keyword[for] identifier[sa] keyword[in] identifier[ctx] . identifier[shapeAnd] (): identifier[sep] = identifier[ShexShapeExpressionParser] ( identifier[self] . identifier[context] ) identifier[sep] . identifier[visit] ( identifier[sa] ) identifier[self] . identifier[expr] . identifier[shapeExprs] . identifier[append] ( identifier[sep] . identifier[expr] ) keyword[else] : identifier[self] . identifier[visit] ( identifier[ctx] . identifier[shapeAnd] ( literal[int] ))
def visitShapeOr(self, ctx: ShExDocParser.ShapeOrContext): """ shapeOr: shapeAnd (KW_OR shapeAnd)* """ if len(ctx.shapeAnd()) > 1: self.expr = ShapeOr(id=self.label, shapeExprs=[]) for sa in ctx.shapeAnd(): sep = ShexShapeExpressionParser(self.context) sep.visit(sa) self.expr.shapeExprs.append(sep.expr) # depends on [control=['for'], data=['sa']] # depends on [control=['if'], data=[]] else: self.visit(ctx.shapeAnd(0))
def listen(self, once=False): """Listen for changes in all registered listeners. Use add_listener before calling this funcion to listen for desired events or set `once` to True to listen for initial room information """ if once: # we listen for time event and return false so our # run_queues function will be also falsy and break the loop self.add_listener("time", lambda _: False) return self.conn.listen()
def function[listen, parameter[self, once]]: constant[Listen for changes in all registered listeners. Use add_listener before calling this funcion to listen for desired events or set `once` to True to listen for initial room information ] if name[once] begin[:] call[name[self].add_listener, parameter[constant[time], <ast.Lambda object at 0x7da2046227a0>]] return[call[name[self].conn.listen, parameter[]]]
keyword[def] identifier[listen] ( identifier[self] , identifier[once] = keyword[False] ): literal[string] keyword[if] identifier[once] : identifier[self] . identifier[add_listener] ( literal[string] , keyword[lambda] identifier[_] : keyword[False] ) keyword[return] identifier[self] . identifier[conn] . identifier[listen] ()
def listen(self, once=False): """Listen for changes in all registered listeners. Use add_listener before calling this funcion to listen for desired events or set `once` to True to listen for initial room information """ if once: # we listen for time event and return false so our # run_queues function will be also falsy and break the loop self.add_listener('time', lambda _: False) # depends on [control=['if'], data=[]] return self.conn.listen()
def get_words(s, splitter_regex=rex.word_sep_except_external_appostrophe, preprocessor=strip_HTML, postprocessor=strip_edge_punc, min_len=None, max_len=None, blacklist=None, whitelist=None, lower=False, filter_fun=None, str_type=str): r"""Segment words (tokens), returning a list of all tokens Does not return any separating whitespace or punctuation marks. Attempts to return external apostrophes at the end of words. Comparable to `nltk.word_toeknize`. Arguments: splitter_regex (str or re): compiled or uncompiled regular expression Applied to the input string using `re.split()` preprocessor (function): defaults to a function that strips out all HTML tags postprocessor (function): a function to apply to each token before return it as an element in the word list Applied using the `map()` builtin min_len (int): delete all words shorter than this number of characters max_len (int): delete all words longer than this number of characters blacklist and whitelist (list of str): words to delete or preserve lower (bool): whether to convert all words to lowercase str_type (type): typically `str` or `unicode`, any type constructor that should can be applied to all words before returning the list Returns: list of str: list of tokens >>> get_words('He said, "She called me \'Hoss\'!". I didn\'t hear.') ['He', 'said', 'She', 'called', 'me', 'Hoss', 'I', "didn't", 'hear'] >>> get_words('The foxes\' oh-so-tiny den was 2empty!') ['The', 'foxes', 'oh-so-tiny', 'den', 'was', '2empty'] """ # TODO: Get rid of `lower` kwarg (and make sure code that uses it doesn't break) # That and other simple postprocessors can be done outside of get_words postprocessor = postprocessor or str_type preprocessor = preprocessor or str_type if min_len is None: min_len = get_words.min_len if max_len is None: max_len = get_words.max_len blacklist = blacklist or get_words.blacklist whitelist = whitelist or get_words.whitelist filter_fun = filter_fun or get_words.filter_fun lower = lower or get_words.lower try: s = open(s, 'r') except (IOError, FileNotFoundError): pass try: s = s.read() except (IOError, AttributeError, TypeError): pass if not isinstance(s, basestring): try: # flatten the list of lists of words from each obj (file or string) return [word for obj in s for word in get_words(obj)] except (IOError, IndexError, ValueError, AttributeError, TypeError): pass try: s = preprocessor(s) except (IndexError, ValueError, AttributeError, TypeError): pass if isinstance(splitter_regex, basestring): splitter_regex = re.compile(splitter_regex) s = list(map(postprocessor, splitter_regex.split(s))) s = list(map(str_type, s)) if not filter_fun: return s return [word for word in s if filter_fun(word, min_len=min_len, max_len=max_len, blacklist=blacklist, whitelist=whitelist, lower=lower)]
def function[get_words, parameter[s, splitter_regex, preprocessor, postprocessor, min_len, max_len, blacklist, whitelist, lower, filter_fun, str_type]]: constant[Segment words (tokens), returning a list of all tokens Does not return any separating whitespace or punctuation marks. Attempts to return external apostrophes at the end of words. Comparable to `nltk.word_toeknize`. Arguments: splitter_regex (str or re): compiled or uncompiled regular expression Applied to the input string using `re.split()` preprocessor (function): defaults to a function that strips out all HTML tags postprocessor (function): a function to apply to each token before return it as an element in the word list Applied using the `map()` builtin min_len (int): delete all words shorter than this number of characters max_len (int): delete all words longer than this number of characters blacklist and whitelist (list of str): words to delete or preserve lower (bool): whether to convert all words to lowercase str_type (type): typically `str` or `unicode`, any type constructor that should can be applied to all words before returning the list Returns: list of str: list of tokens >>> get_words('He said, "She called me \'Hoss\'!". I didn\'t hear.') ['He', 'said', 'She', 'called', 'me', 'Hoss', 'I', "didn't", 'hear'] >>> get_words('The foxes\' oh-so-tiny den was 2empty!') ['The', 'foxes', 'oh-so-tiny', 'den', 'was', '2empty'] ] variable[postprocessor] assign[=] <ast.BoolOp object at 0x7da18fe93250> variable[preprocessor] assign[=] <ast.BoolOp object at 0x7da18fe91c30> if compare[name[min_len] is constant[None]] begin[:] variable[min_len] assign[=] name[get_words].min_len if compare[name[max_len] is constant[None]] begin[:] variable[max_len] assign[=] name[get_words].max_len variable[blacklist] assign[=] <ast.BoolOp object at 0x7da18fe90a00> variable[whitelist] assign[=] <ast.BoolOp object at 0x7da18fe93b50> variable[filter_fun] assign[=] <ast.BoolOp object at 0x7da18fe933a0> variable[lower] assign[=] <ast.BoolOp object at 0x7da18fe91cc0> <ast.Try object at 0x7da18fe91840> <ast.Try object at 0x7da18fe90a30> if <ast.UnaryOp object at 0x7da18fe936d0> begin[:] <ast.Try object at 0x7da18fe93130> <ast.Try object at 0x7da18fe91fc0> if call[name[isinstance], parameter[name[splitter_regex], name[basestring]]] begin[:] variable[splitter_regex] assign[=] call[name[re].compile, parameter[name[splitter_regex]]] variable[s] assign[=] call[name[list], parameter[call[name[map], parameter[name[postprocessor], call[name[splitter_regex].split, parameter[name[s]]]]]]] variable[s] assign[=] call[name[list], parameter[call[name[map], parameter[name[str_type], name[s]]]]] if <ast.UnaryOp object at 0x7da18fe917e0> begin[:] return[name[s]] return[<ast.ListComp object at 0x7da18fe92590>]
keyword[def] identifier[get_words] ( identifier[s] , identifier[splitter_regex] = identifier[rex] . identifier[word_sep_except_external_appostrophe] , identifier[preprocessor] = identifier[strip_HTML] , identifier[postprocessor] = identifier[strip_edge_punc] , identifier[min_len] = keyword[None] , identifier[max_len] = keyword[None] , identifier[blacklist] = keyword[None] , identifier[whitelist] = keyword[None] , identifier[lower] = keyword[False] , identifier[filter_fun] = keyword[None] , identifier[str_type] = identifier[str] ): literal[string] identifier[postprocessor] = identifier[postprocessor] keyword[or] identifier[str_type] identifier[preprocessor] = identifier[preprocessor] keyword[or] identifier[str_type] keyword[if] identifier[min_len] keyword[is] keyword[None] : identifier[min_len] = identifier[get_words] . identifier[min_len] keyword[if] identifier[max_len] keyword[is] keyword[None] : identifier[max_len] = identifier[get_words] . identifier[max_len] identifier[blacklist] = identifier[blacklist] keyword[or] identifier[get_words] . identifier[blacklist] identifier[whitelist] = identifier[whitelist] keyword[or] identifier[get_words] . identifier[whitelist] identifier[filter_fun] = identifier[filter_fun] keyword[or] identifier[get_words] . identifier[filter_fun] identifier[lower] = identifier[lower] keyword[or] identifier[get_words] . identifier[lower] keyword[try] : identifier[s] = identifier[open] ( identifier[s] , literal[string] ) keyword[except] ( identifier[IOError] , identifier[FileNotFoundError] ): keyword[pass] keyword[try] : identifier[s] = identifier[s] . identifier[read] () keyword[except] ( identifier[IOError] , identifier[AttributeError] , identifier[TypeError] ): keyword[pass] keyword[if] keyword[not] identifier[isinstance] ( identifier[s] , identifier[basestring] ): keyword[try] : keyword[return] [ identifier[word] keyword[for] identifier[obj] keyword[in] identifier[s] keyword[for] identifier[word] keyword[in] identifier[get_words] ( identifier[obj] )] keyword[except] ( identifier[IOError] , identifier[IndexError] , identifier[ValueError] , identifier[AttributeError] , identifier[TypeError] ): keyword[pass] keyword[try] : identifier[s] = identifier[preprocessor] ( identifier[s] ) keyword[except] ( identifier[IndexError] , identifier[ValueError] , identifier[AttributeError] , identifier[TypeError] ): keyword[pass] keyword[if] identifier[isinstance] ( identifier[splitter_regex] , identifier[basestring] ): identifier[splitter_regex] = identifier[re] . identifier[compile] ( identifier[splitter_regex] ) identifier[s] = identifier[list] ( identifier[map] ( identifier[postprocessor] , identifier[splitter_regex] . identifier[split] ( identifier[s] ))) identifier[s] = identifier[list] ( identifier[map] ( identifier[str_type] , identifier[s] )) keyword[if] keyword[not] identifier[filter_fun] : keyword[return] identifier[s] keyword[return] [ identifier[word] keyword[for] identifier[word] keyword[in] identifier[s] keyword[if] identifier[filter_fun] ( identifier[word] , identifier[min_len] = identifier[min_len] , identifier[max_len] = identifier[max_len] , identifier[blacklist] = identifier[blacklist] , identifier[whitelist] = identifier[whitelist] , identifier[lower] = identifier[lower] )]
def get_words(s, splitter_regex=rex.word_sep_except_external_appostrophe, preprocessor=strip_HTML, postprocessor=strip_edge_punc, min_len=None, max_len=None, blacklist=None, whitelist=None, lower=False, filter_fun=None, str_type=str): """Segment words (tokens), returning a list of all tokens Does not return any separating whitespace or punctuation marks. Attempts to return external apostrophes at the end of words. Comparable to `nltk.word_toeknize`. Arguments: splitter_regex (str or re): compiled or uncompiled regular expression Applied to the input string using `re.split()` preprocessor (function): defaults to a function that strips out all HTML tags postprocessor (function): a function to apply to each token before return it as an element in the word list Applied using the `map()` builtin min_len (int): delete all words shorter than this number of characters max_len (int): delete all words longer than this number of characters blacklist and whitelist (list of str): words to delete or preserve lower (bool): whether to convert all words to lowercase str_type (type): typically `str` or `unicode`, any type constructor that should can be applied to all words before returning the list Returns: list of str: list of tokens >>> get_words('He said, "She called me \\'Hoss\\'!". I didn\\'t hear.') ['He', 'said', 'She', 'called', 'me', 'Hoss', 'I', "didn't", 'hear'] >>> get_words('The foxes\\' oh-so-tiny den was 2empty!') ['The', 'foxes', 'oh-so-tiny', 'den', 'was', '2empty'] """ # TODO: Get rid of `lower` kwarg (and make sure code that uses it doesn't break) # That and other simple postprocessors can be done outside of get_words postprocessor = postprocessor or str_type preprocessor = preprocessor or str_type if min_len is None: min_len = get_words.min_len # depends on [control=['if'], data=['min_len']] if max_len is None: max_len = get_words.max_len # depends on [control=['if'], data=['max_len']] blacklist = blacklist or get_words.blacklist whitelist = whitelist or get_words.whitelist filter_fun = filter_fun or get_words.filter_fun lower = lower or get_words.lower try: s = open(s, 'r') # depends on [control=['try'], data=[]] except (IOError, FileNotFoundError): pass # depends on [control=['except'], data=[]] try: s = s.read() # depends on [control=['try'], data=[]] except (IOError, AttributeError, TypeError): pass # depends on [control=['except'], data=[]] if not isinstance(s, basestring): try: # flatten the list of lists of words from each obj (file or string) return [word for obj in s for word in get_words(obj)] # depends on [control=['try'], data=[]] except (IOError, IndexError, ValueError, AttributeError, TypeError): pass # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] try: s = preprocessor(s) # depends on [control=['try'], data=[]] except (IndexError, ValueError, AttributeError, TypeError): pass # depends on [control=['except'], data=[]] if isinstance(splitter_regex, basestring): splitter_regex = re.compile(splitter_regex) # depends on [control=['if'], data=[]] s = list(map(postprocessor, splitter_regex.split(s))) s = list(map(str_type, s)) if not filter_fun: return s # depends on [control=['if'], data=[]] return [word for word in s if filter_fun(word, min_len=min_len, max_len=max_len, blacklist=blacklist, whitelist=whitelist, lower=lower)]
def _FormatInode(self, event): """Formats the inode. Args: event (EventObject): event. Returns: str: inode field. """ inode = event.inode if inode is None: if hasattr(event, 'pathspec') and hasattr(event.pathspec, 'image_inode'): inode = event.pathspec.image_inode if inode is None: inode = '-' return inode
def function[_FormatInode, parameter[self, event]]: constant[Formats the inode. Args: event (EventObject): event. Returns: str: inode field. ] variable[inode] assign[=] name[event].inode if compare[name[inode] is constant[None]] begin[:] if <ast.BoolOp object at 0x7da18ede5780> begin[:] variable[inode] assign[=] name[event].pathspec.image_inode if compare[name[inode] is constant[None]] begin[:] variable[inode] assign[=] constant[-] return[name[inode]]
keyword[def] identifier[_FormatInode] ( identifier[self] , identifier[event] ): literal[string] identifier[inode] = identifier[event] . identifier[inode] keyword[if] identifier[inode] keyword[is] keyword[None] : keyword[if] identifier[hasattr] ( identifier[event] , literal[string] ) keyword[and] identifier[hasattr] ( identifier[event] . identifier[pathspec] , literal[string] ): identifier[inode] = identifier[event] . identifier[pathspec] . identifier[image_inode] keyword[if] identifier[inode] keyword[is] keyword[None] : identifier[inode] = literal[string] keyword[return] identifier[inode]
def _FormatInode(self, event): """Formats the inode. Args: event (EventObject): event. Returns: str: inode field. """ inode = event.inode if inode is None: if hasattr(event, 'pathspec') and hasattr(event.pathspec, 'image_inode'): inode = event.pathspec.image_inode # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['inode']] if inode is None: inode = '-' # depends on [control=['if'], data=['inode']] return inode
def clustered_sortind(x, k=10, scorefunc=None): """ Uses MiniBatch k-means clustering to cluster matrix into groups. Each cluster of rows is then sorted by `scorefunc` -- by default, the max peak height when all rows in a cluster are averaged, or cluster.mean(axis=0).max(). Returns the index that will sort the rows of `x` and a list of "breaks". `breaks` is essentially a cumulative row count for each cluster boundary. In other words, after plotting the array you can use axhline on each "break" to plot the cluster boundary. If `k` is a list or tuple, iteratively try each one and select the best with the lowest mean distance from cluster centers. :param x: Matrix whose rows are to be clustered :param k: Number of clusters to create or a list of potential clusters; the optimum will be chosen from the list :param scorefunc: Optional function for sorting rows within clusters. Must accept a single argument of a NumPy array. """ try: from sklearn.cluster import MiniBatchKMeans except ImportError: raise ImportError('please install scikits.learn for ' 'clustering.') # If integer, do it once and we're done if isinstance(k, int): best_k = k else: mean_dists = {} for _k in k: mbk = MiniBatchKMeans(init='k-means++', n_clusters=_k) mbk.fit(x) mean_dists[_k] = mbk.transform(x).mean() best_k = sorted(mean_dists.items(), key=lambda x: x[1])[-1][0] mbk = MiniBatchKMeans(init='k-means++', n_clusters=best_k) mbk.fit(x) k = best_k labels = mbk.labels_ scores = np.zeros(labels.shape, dtype=float) if not scorefunc: def scorefunc(x): return x.mean(axis=0).max() for label in range(k): ind = labels == label score = scorefunc(x[ind, :]) scores[ind] = score pos = 0 breaks = [] ind = np.argsort(scores) for k, g in itertools.groupby(labels[ind]): pos += len(list(g)) breaks.append(pos) return ind, breaks
def function[clustered_sortind, parameter[x, k, scorefunc]]: constant[ Uses MiniBatch k-means clustering to cluster matrix into groups. Each cluster of rows is then sorted by `scorefunc` -- by default, the max peak height when all rows in a cluster are averaged, or cluster.mean(axis=0).max(). Returns the index that will sort the rows of `x` and a list of "breaks". `breaks` is essentially a cumulative row count for each cluster boundary. In other words, after plotting the array you can use axhline on each "break" to plot the cluster boundary. If `k` is a list or tuple, iteratively try each one and select the best with the lowest mean distance from cluster centers. :param x: Matrix whose rows are to be clustered :param k: Number of clusters to create or a list of potential clusters; the optimum will be chosen from the list :param scorefunc: Optional function for sorting rows within clusters. Must accept a single argument of a NumPy array. ] <ast.Try object at 0x7da20c6aa140> if call[name[isinstance], parameter[name[k], name[int]]] begin[:] variable[best_k] assign[=] name[k] variable[mbk] assign[=] call[name[MiniBatchKMeans], parameter[]] call[name[mbk].fit, parameter[name[x]]] variable[k] assign[=] name[best_k] variable[labels] assign[=] name[mbk].labels_ variable[scores] assign[=] call[name[np].zeros, parameter[name[labels].shape]] if <ast.UnaryOp object at 0x7da20c6a9f90> begin[:] def function[scorefunc, parameter[x]]: return[call[call[name[x].mean, parameter[]].max, parameter[]]] for taget[name[label]] in starred[call[name[range], parameter[name[k]]]] begin[:] variable[ind] assign[=] compare[name[labels] equal[==] name[label]] variable[score] assign[=] call[name[scorefunc], parameter[call[name[x]][tuple[[<ast.Name object at 0x7da1b27bb220>, <ast.Slice object at 0x7da1b27bb100>]]]]] call[name[scores]][name[ind]] assign[=] name[score] variable[pos] assign[=] constant[0] variable[breaks] assign[=] list[[]] variable[ind] assign[=] call[name[np].argsort, parameter[name[scores]]] for taget[tuple[[<ast.Name object at 0x7da1b27b9cc0>, <ast.Name object at 0x7da1b27b81c0>]]] in starred[call[name[itertools].groupby, parameter[call[name[labels]][name[ind]]]]] begin[:] <ast.AugAssign object at 0x7da1b27bb550> call[name[breaks].append, parameter[name[pos]]] return[tuple[[<ast.Name object at 0x7da1b27b9120>, <ast.Name object at 0x7da1b27bbdf0>]]]
keyword[def] identifier[clustered_sortind] ( identifier[x] , identifier[k] = literal[int] , identifier[scorefunc] = keyword[None] ): literal[string] keyword[try] : keyword[from] identifier[sklearn] . identifier[cluster] keyword[import] identifier[MiniBatchKMeans] keyword[except] identifier[ImportError] : keyword[raise] identifier[ImportError] ( literal[string] literal[string] ) keyword[if] identifier[isinstance] ( identifier[k] , identifier[int] ): identifier[best_k] = identifier[k] keyword[else] : identifier[mean_dists] ={} keyword[for] identifier[_k] keyword[in] identifier[k] : identifier[mbk] = identifier[MiniBatchKMeans] ( identifier[init] = literal[string] , identifier[n_clusters] = identifier[_k] ) identifier[mbk] . identifier[fit] ( identifier[x] ) identifier[mean_dists] [ identifier[_k] ]= identifier[mbk] . identifier[transform] ( identifier[x] ). identifier[mean] () identifier[best_k] = identifier[sorted] ( identifier[mean_dists] . identifier[items] (), identifier[key] = keyword[lambda] identifier[x] : identifier[x] [ literal[int] ])[- literal[int] ][ literal[int] ] identifier[mbk] = identifier[MiniBatchKMeans] ( identifier[init] = literal[string] , identifier[n_clusters] = identifier[best_k] ) identifier[mbk] . identifier[fit] ( identifier[x] ) identifier[k] = identifier[best_k] identifier[labels] = identifier[mbk] . identifier[labels_] identifier[scores] = identifier[np] . identifier[zeros] ( identifier[labels] . identifier[shape] , identifier[dtype] = identifier[float] ) keyword[if] keyword[not] identifier[scorefunc] : keyword[def] identifier[scorefunc] ( identifier[x] ): keyword[return] identifier[x] . identifier[mean] ( identifier[axis] = literal[int] ). identifier[max] () keyword[for] identifier[label] keyword[in] identifier[range] ( identifier[k] ): identifier[ind] = identifier[labels] == identifier[label] identifier[score] = identifier[scorefunc] ( identifier[x] [ identifier[ind] ,:]) identifier[scores] [ identifier[ind] ]= identifier[score] identifier[pos] = literal[int] identifier[breaks] =[] identifier[ind] = identifier[np] . identifier[argsort] ( identifier[scores] ) keyword[for] identifier[k] , identifier[g] keyword[in] identifier[itertools] . identifier[groupby] ( identifier[labels] [ identifier[ind] ]): identifier[pos] += identifier[len] ( identifier[list] ( identifier[g] )) identifier[breaks] . identifier[append] ( identifier[pos] ) keyword[return] identifier[ind] , identifier[breaks]
def clustered_sortind(x, k=10, scorefunc=None): """ Uses MiniBatch k-means clustering to cluster matrix into groups. Each cluster of rows is then sorted by `scorefunc` -- by default, the max peak height when all rows in a cluster are averaged, or cluster.mean(axis=0).max(). Returns the index that will sort the rows of `x` and a list of "breaks". `breaks` is essentially a cumulative row count for each cluster boundary. In other words, after plotting the array you can use axhline on each "break" to plot the cluster boundary. If `k` is a list or tuple, iteratively try each one and select the best with the lowest mean distance from cluster centers. :param x: Matrix whose rows are to be clustered :param k: Number of clusters to create or a list of potential clusters; the optimum will be chosen from the list :param scorefunc: Optional function for sorting rows within clusters. Must accept a single argument of a NumPy array. """ try: from sklearn.cluster import MiniBatchKMeans # depends on [control=['try'], data=[]] except ImportError: raise ImportError('please install scikits.learn for clustering.') # depends on [control=['except'], data=[]] # If integer, do it once and we're done if isinstance(k, int): best_k = k # depends on [control=['if'], data=[]] else: mean_dists = {} for _k in k: mbk = MiniBatchKMeans(init='k-means++', n_clusters=_k) mbk.fit(x) mean_dists[_k] = mbk.transform(x).mean() # depends on [control=['for'], data=['_k']] best_k = sorted(mean_dists.items(), key=lambda x: x[1])[-1][0] mbk = MiniBatchKMeans(init='k-means++', n_clusters=best_k) mbk.fit(x) k = best_k labels = mbk.labels_ scores = np.zeros(labels.shape, dtype=float) if not scorefunc: def scorefunc(x): return x.mean(axis=0).max() # depends on [control=['if'], data=[]] for label in range(k): ind = labels == label score = scorefunc(x[ind, :]) scores[ind] = score # depends on [control=['for'], data=['label']] pos = 0 breaks = [] ind = np.argsort(scores) for (k, g) in itertools.groupby(labels[ind]): pos += len(list(g)) breaks.append(pos) # depends on [control=['for'], data=[]] return (ind, breaks)
def calculate_etag(self, expected=None): """ calculates a multipart upload etag in the same way as amazon s3 args: source_path -- The file to calculate the etage for chunk_size -- The chunk size to calculate for. expected -- optional If passed a string, the string will be compared to the resulting etag and raise an exception if they don't match """ md5s = [] with open(self.filepath, 'rb') as fp: while True: data = fp.read(CHUNK_SIZE) if not data: break md5s.append(hashlib.md5(data)) digests = b"".join(m.digest() for m in md5s) new_md5 = hashlib.md5(digests) new_etag = '%s-%s' % (new_md5.hexdigest(),len(md5s)) self.etag = new_etag return new_etag
def function[calculate_etag, parameter[self, expected]]: constant[ calculates a multipart upload etag in the same way as amazon s3 args: source_path -- The file to calculate the etage for chunk_size -- The chunk size to calculate for. expected -- optional If passed a string, the string will be compared to the resulting etag and raise an exception if they don't match ] variable[md5s] assign[=] list[[]] with call[name[open], parameter[name[self].filepath, constant[rb]]] begin[:] while constant[True] begin[:] variable[data] assign[=] call[name[fp].read, parameter[name[CHUNK_SIZE]]] if <ast.UnaryOp object at 0x7da1b26afa00> begin[:] break call[name[md5s].append, parameter[call[name[hashlib].md5, parameter[name[data]]]]] variable[digests] assign[=] call[constant[b''].join, parameter[<ast.GeneratorExp object at 0x7da1b26ae4d0>]] variable[new_md5] assign[=] call[name[hashlib].md5, parameter[name[digests]]] variable[new_etag] assign[=] binary_operation[constant[%s-%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b1402ec0>, <ast.Call object at 0x7da1b1401510>]]] name[self].etag assign[=] name[new_etag] return[name[new_etag]]
keyword[def] identifier[calculate_etag] ( identifier[self] , identifier[expected] = keyword[None] ): literal[string] identifier[md5s] =[] keyword[with] identifier[open] ( identifier[self] . identifier[filepath] , literal[string] ) keyword[as] identifier[fp] : keyword[while] keyword[True] : identifier[data] = identifier[fp] . identifier[read] ( identifier[CHUNK_SIZE] ) keyword[if] keyword[not] identifier[data] : keyword[break] identifier[md5s] . identifier[append] ( identifier[hashlib] . identifier[md5] ( identifier[data] )) identifier[digests] = literal[string] . identifier[join] ( identifier[m] . identifier[digest] () keyword[for] identifier[m] keyword[in] identifier[md5s] ) identifier[new_md5] = identifier[hashlib] . identifier[md5] ( identifier[digests] ) identifier[new_etag] = literal[string] %( identifier[new_md5] . identifier[hexdigest] (), identifier[len] ( identifier[md5s] )) identifier[self] . identifier[etag] = identifier[new_etag] keyword[return] identifier[new_etag]
def calculate_etag(self, expected=None): """ calculates a multipart upload etag in the same way as amazon s3 args: source_path -- The file to calculate the etage for chunk_size -- The chunk size to calculate for. expected -- optional If passed a string, the string will be compared to the resulting etag and raise an exception if they don't match """ md5s = [] with open(self.filepath, 'rb') as fp: while True: data = fp.read(CHUNK_SIZE) if not data: break # depends on [control=['if'], data=[]] md5s.append(hashlib.md5(data)) # depends on [control=['while'], data=[]] # depends on [control=['with'], data=['fp']] digests = b''.join((m.digest() for m in md5s)) new_md5 = hashlib.md5(digests) new_etag = '%s-%s' % (new_md5.hexdigest(), len(md5s)) self.etag = new_etag return new_etag
def apply_cut(self, cm): """Return a modified connectivity matrix with all connections that are severed by this cut removed. Args: cm (np.ndarray): A connectivity matrix. """ # Invert the cut matrix, creating a matrix of preserved connections inverse = np.logical_not(self.cut_matrix(cm.shape[0])).astype(int) return cm * inverse
def function[apply_cut, parameter[self, cm]]: constant[Return a modified connectivity matrix with all connections that are severed by this cut removed. Args: cm (np.ndarray): A connectivity matrix. ] variable[inverse] assign[=] call[call[name[np].logical_not, parameter[call[name[self].cut_matrix, parameter[call[name[cm].shape][constant[0]]]]]].astype, parameter[name[int]]] return[binary_operation[name[cm] * name[inverse]]]
keyword[def] identifier[apply_cut] ( identifier[self] , identifier[cm] ): literal[string] identifier[inverse] = identifier[np] . identifier[logical_not] ( identifier[self] . identifier[cut_matrix] ( identifier[cm] . identifier[shape] [ literal[int] ])). identifier[astype] ( identifier[int] ) keyword[return] identifier[cm] * identifier[inverse]
def apply_cut(self, cm): """Return a modified connectivity matrix with all connections that are severed by this cut removed. Args: cm (np.ndarray): A connectivity matrix. """ # Invert the cut matrix, creating a matrix of preserved connections inverse = np.logical_not(self.cut_matrix(cm.shape[0])).astype(int) return cm * inverse
def pretty_plot(width=8, height=None, plt=None, dpi=None, color_cycle=("qualitative", "Set1_9")): """ Provides a publication quality plot, with nice defaults for font sizes etc. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in inches. Defaults to width * golden ratio. plt (matplotlib.pyplot): If plt is supplied, changes will be made to an existing plot. Otherwise, a new plot will be created. dpi (int): Sets dot per inch for figure. Defaults to 300. color_cycle (tuple): Set the color cycle for new plots to one of the color sets in palettable. Defaults to a qualitative Set1_9. Returns: Matplotlib plot object with properly sized fonts. """ ticksize = int(width * 2.5) golden_ratio = (math.sqrt(5) - 1) / 2 if not height: height = int(width * golden_ratio) if plt is None: import matplotlib.pyplot as plt import importlib mod = importlib.import_module("palettable.colorbrewer.%s" % color_cycle[0]) colors = getattr(mod, color_cycle[1]).mpl_colors from cycler import cycler plt.figure(figsize=(width, height), facecolor="w", dpi=dpi) ax = plt.gca() ax.set_prop_cycle(cycler('color', colors)) else: fig = plt.gcf() fig.set_size_inches(width, height) plt.xticks(fontsize=ticksize) plt.yticks(fontsize=ticksize) ax = plt.gca() ax.set_title(ax.get_title(), size=width * 4) labelsize = int(width * 3) ax.set_xlabel(ax.get_xlabel(), size=labelsize) ax.set_ylabel(ax.get_ylabel(), size=labelsize) return plt
def function[pretty_plot, parameter[width, height, plt, dpi, color_cycle]]: constant[ Provides a publication quality plot, with nice defaults for font sizes etc. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in inches. Defaults to width * golden ratio. plt (matplotlib.pyplot): If plt is supplied, changes will be made to an existing plot. Otherwise, a new plot will be created. dpi (int): Sets dot per inch for figure. Defaults to 300. color_cycle (tuple): Set the color cycle for new plots to one of the color sets in palettable. Defaults to a qualitative Set1_9. Returns: Matplotlib plot object with properly sized fonts. ] variable[ticksize] assign[=] call[name[int], parameter[binary_operation[name[width] * constant[2.5]]]] variable[golden_ratio] assign[=] binary_operation[binary_operation[call[name[math].sqrt, parameter[constant[5]]] - constant[1]] / constant[2]] if <ast.UnaryOp object at 0x7da1b1c7ff10> begin[:] variable[height] assign[=] call[name[int], parameter[binary_operation[name[width] * name[golden_ratio]]]] if compare[name[plt] is constant[None]] begin[:] import module[matplotlib.pyplot] as alias[plt] import module[importlib] variable[mod] assign[=] call[name[importlib].import_module, parameter[binary_operation[constant[palettable.colorbrewer.%s] <ast.Mod object at 0x7da2590d6920> call[name[color_cycle]][constant[0]]]]] variable[colors] assign[=] call[name[getattr], parameter[name[mod], call[name[color_cycle]][constant[1]]]].mpl_colors from relative_module[cycler] import module[cycler] call[name[plt].figure, parameter[]] variable[ax] assign[=] call[name[plt].gca, parameter[]] call[name[ax].set_prop_cycle, parameter[call[name[cycler], parameter[constant[color], name[colors]]]]] call[name[plt].xticks, parameter[]] call[name[plt].yticks, parameter[]] variable[ax] assign[=] call[name[plt].gca, parameter[]] call[name[ax].set_title, parameter[call[name[ax].get_title, parameter[]]]] variable[labelsize] assign[=] call[name[int], parameter[binary_operation[name[width] * constant[3]]]] call[name[ax].set_xlabel, parameter[call[name[ax].get_xlabel, parameter[]]]] call[name[ax].set_ylabel, parameter[call[name[ax].get_ylabel, parameter[]]]] return[name[plt]]
keyword[def] identifier[pretty_plot] ( identifier[width] = literal[int] , identifier[height] = keyword[None] , identifier[plt] = keyword[None] , identifier[dpi] = keyword[None] , identifier[color_cycle] =( literal[string] , literal[string] )): literal[string] identifier[ticksize] = identifier[int] ( identifier[width] * literal[int] ) identifier[golden_ratio] =( identifier[math] . identifier[sqrt] ( literal[int] )- literal[int] )/ literal[int] keyword[if] keyword[not] identifier[height] : identifier[height] = identifier[int] ( identifier[width] * identifier[golden_ratio] ) keyword[if] identifier[plt] keyword[is] keyword[None] : keyword[import] identifier[matplotlib] . identifier[pyplot] keyword[as] identifier[plt] keyword[import] identifier[importlib] identifier[mod] = identifier[importlib] . identifier[import_module] ( literal[string] % identifier[color_cycle] [ literal[int] ]) identifier[colors] = identifier[getattr] ( identifier[mod] , identifier[color_cycle] [ literal[int] ]). identifier[mpl_colors] keyword[from] identifier[cycler] keyword[import] identifier[cycler] identifier[plt] . identifier[figure] ( identifier[figsize] =( identifier[width] , identifier[height] ), identifier[facecolor] = literal[string] , identifier[dpi] = identifier[dpi] ) identifier[ax] = identifier[plt] . identifier[gca] () identifier[ax] . identifier[set_prop_cycle] ( identifier[cycler] ( literal[string] , identifier[colors] )) keyword[else] : identifier[fig] = identifier[plt] . identifier[gcf] () identifier[fig] . identifier[set_size_inches] ( identifier[width] , identifier[height] ) identifier[plt] . identifier[xticks] ( identifier[fontsize] = identifier[ticksize] ) identifier[plt] . identifier[yticks] ( identifier[fontsize] = identifier[ticksize] ) identifier[ax] = identifier[plt] . identifier[gca] () identifier[ax] . identifier[set_title] ( identifier[ax] . identifier[get_title] (), identifier[size] = identifier[width] * literal[int] ) identifier[labelsize] = identifier[int] ( identifier[width] * literal[int] ) identifier[ax] . identifier[set_xlabel] ( identifier[ax] . identifier[get_xlabel] (), identifier[size] = identifier[labelsize] ) identifier[ax] . identifier[set_ylabel] ( identifier[ax] . identifier[get_ylabel] (), identifier[size] = identifier[labelsize] ) keyword[return] identifier[plt]
def pretty_plot(width=8, height=None, plt=None, dpi=None, color_cycle=('qualitative', 'Set1_9')): """ Provides a publication quality plot, with nice defaults for font sizes etc. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in inches. Defaults to width * golden ratio. plt (matplotlib.pyplot): If plt is supplied, changes will be made to an existing plot. Otherwise, a new plot will be created. dpi (int): Sets dot per inch for figure. Defaults to 300. color_cycle (tuple): Set the color cycle for new plots to one of the color sets in palettable. Defaults to a qualitative Set1_9. Returns: Matplotlib plot object with properly sized fonts. """ ticksize = int(width * 2.5) golden_ratio = (math.sqrt(5) - 1) / 2 if not height: height = int(width * golden_ratio) # depends on [control=['if'], data=[]] if plt is None: import matplotlib.pyplot as plt import importlib mod = importlib.import_module('palettable.colorbrewer.%s' % color_cycle[0]) colors = getattr(mod, color_cycle[1]).mpl_colors from cycler import cycler plt.figure(figsize=(width, height), facecolor='w', dpi=dpi) ax = plt.gca() ax.set_prop_cycle(cycler('color', colors)) # depends on [control=['if'], data=['plt']] else: fig = plt.gcf() fig.set_size_inches(width, height) plt.xticks(fontsize=ticksize) plt.yticks(fontsize=ticksize) ax = plt.gca() ax.set_title(ax.get_title(), size=width * 4) labelsize = int(width * 3) ax.set_xlabel(ax.get_xlabel(), size=labelsize) ax.set_ylabel(ax.get_ylabel(), size=labelsize) return plt
async def _redirect(self, response_obj): ''' Calls the _check_redirect method of the supplied response object in order to determine if the http status code indicates a redirect. Returns: Response: May or may not be the result of recursive calls due to redirects! Notes: If it does redirect, it calls the appropriate method with the redirect location, returning the response object. Furthermore, if there is a redirect, this function is recursive in a roundabout way, storing the previous response object in `.history_objects`. ''' redirect, force_get, location = False, None, None if 300 <= response_obj.status_code < 400: if response_obj.status_code == 303: self.data, self.json, self.files = None, None, None if response_obj.status_code in [301, 305]: # redirect / force GET / location redirect = True force_get = False else: redirect = True force_get = True location = response_obj.headers['Location'] if redirect: allow_redirect = True redirect_uri = urlparse(location.strip()) # relative redirect if not redirect_uri.netloc: self.uri = urlunparse( (self.scheme, self.host, *redirect_uri[2:])) # absolute-redirect else: location = location.strip() if self.auth is not None: if not self.auth_off_domain: allow_redirect = self._location_auth_protect(location) self.uri = location l_scheme, l_netloc, *_ = urlparse(location) if l_scheme != self.scheme or l_netloc != self.host: await self._get_new_sock() # follow redirect with correct http method type if force_get: self.history_objects.append(response_obj) self.method = 'GET' else: self.history_objects.append(response_obj) self.max_redirects -= 1 try: if response_obj.headers['connection'].lower() == 'close': await self._get_new_sock() except KeyError: pass if allow_redirect: _, response_obj = await self.make_request() return response_obj
<ast.AsyncFunctionDef object at 0x7da1b07785b0>
keyword[async] keyword[def] identifier[_redirect] ( identifier[self] , identifier[response_obj] ): literal[string] identifier[redirect] , identifier[force_get] , identifier[location] = keyword[False] , keyword[None] , keyword[None] keyword[if] literal[int] <= identifier[response_obj] . identifier[status_code] < literal[int] : keyword[if] identifier[response_obj] . identifier[status_code] == literal[int] : identifier[self] . identifier[data] , identifier[self] . identifier[json] , identifier[self] . identifier[files] = keyword[None] , keyword[None] , keyword[None] keyword[if] identifier[response_obj] . identifier[status_code] keyword[in] [ literal[int] , literal[int] ]: identifier[redirect] = keyword[True] identifier[force_get] = keyword[False] keyword[else] : identifier[redirect] = keyword[True] identifier[force_get] = keyword[True] identifier[location] = identifier[response_obj] . identifier[headers] [ literal[string] ] keyword[if] identifier[redirect] : identifier[allow_redirect] = keyword[True] identifier[redirect_uri] = identifier[urlparse] ( identifier[location] . identifier[strip] ()) keyword[if] keyword[not] identifier[redirect_uri] . identifier[netloc] : identifier[self] . identifier[uri] = identifier[urlunparse] ( ( identifier[self] . identifier[scheme] , identifier[self] . identifier[host] ,* identifier[redirect_uri] [ literal[int] :])) keyword[else] : identifier[location] = identifier[location] . identifier[strip] () keyword[if] identifier[self] . identifier[auth] keyword[is] keyword[not] keyword[None] : keyword[if] keyword[not] identifier[self] . identifier[auth_off_domain] : identifier[allow_redirect] = identifier[self] . identifier[_location_auth_protect] ( identifier[location] ) identifier[self] . identifier[uri] = identifier[location] identifier[l_scheme] , identifier[l_netloc] ,* identifier[_] = identifier[urlparse] ( identifier[location] ) keyword[if] identifier[l_scheme] != identifier[self] . identifier[scheme] keyword[or] identifier[l_netloc] != identifier[self] . identifier[host] : keyword[await] identifier[self] . identifier[_get_new_sock] () keyword[if] identifier[force_get] : identifier[self] . identifier[history_objects] . identifier[append] ( identifier[response_obj] ) identifier[self] . identifier[method] = literal[string] keyword[else] : identifier[self] . identifier[history_objects] . identifier[append] ( identifier[response_obj] ) identifier[self] . identifier[max_redirects] -= literal[int] keyword[try] : keyword[if] identifier[response_obj] . identifier[headers] [ literal[string] ]. identifier[lower] ()== literal[string] : keyword[await] identifier[self] . identifier[_get_new_sock] () keyword[except] identifier[KeyError] : keyword[pass] keyword[if] identifier[allow_redirect] : identifier[_] , identifier[response_obj] = keyword[await] identifier[self] . identifier[make_request] () keyword[return] identifier[response_obj]
async def _redirect(self, response_obj): """ Calls the _check_redirect method of the supplied response object in order to determine if the http status code indicates a redirect. Returns: Response: May or may not be the result of recursive calls due to redirects! Notes: If it does redirect, it calls the appropriate method with the redirect location, returning the response object. Furthermore, if there is a redirect, this function is recursive in a roundabout way, storing the previous response object in `.history_objects`. """ (redirect, force_get, location) = (False, None, None) if 300 <= response_obj.status_code < 400: if response_obj.status_code == 303: (self.data, self.json, self.files) = (None, None, None) # depends on [control=['if'], data=[]] if response_obj.status_code in [301, 305]: # redirect / force GET / location redirect = True force_get = False # depends on [control=['if'], data=[]] else: redirect = True force_get = True location = response_obj.headers['Location'] # depends on [control=['if'], data=[]] if redirect: allow_redirect = True redirect_uri = urlparse(location.strip()) # relative redirect if not redirect_uri.netloc: self.uri = urlunparse((self.scheme, self.host, *redirect_uri[2:])) # depends on [control=['if'], data=[]] else: # absolute-redirect location = location.strip() if self.auth is not None: if not self.auth_off_domain: allow_redirect = self._location_auth_protect(location) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] self.uri = location (l_scheme, l_netloc, *_) = urlparse(location) if l_scheme != self.scheme or l_netloc != self.host: await self._get_new_sock() # depends on [control=['if'], data=[]] # follow redirect with correct http method type if force_get: self.history_objects.append(response_obj) self.method = 'GET' # depends on [control=['if'], data=[]] else: self.history_objects.append(response_obj) self.max_redirects -= 1 try: if response_obj.headers['connection'].lower() == 'close': await self._get_new_sock() # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except KeyError: pass # depends on [control=['except'], data=[]] if allow_redirect: (_, response_obj) = await self.make_request() # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return response_obj
def Deserialize(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ self.Magic = reader.ReadUInt32() self.Command = reader.ReadFixedString(12).decode('utf-8') self.Length = reader.ReadUInt32() if self.Length > self.PayloadMaxSizeInt: raise Exception("invalid format- payload too large") self.Checksum = reader.ReadUInt32() self.Payload = reader.ReadBytes(self.Length) checksum = Message.GetChecksum(self.Payload) if checksum != self.Checksum: raise ChecksumException("checksum mismatch")
def function[Deserialize, parameter[self, reader]]: constant[ Deserialize full object. Args: reader (neo.IO.BinaryReader): ] name[self].Magic assign[=] call[name[reader].ReadUInt32, parameter[]] name[self].Command assign[=] call[call[name[reader].ReadFixedString, parameter[constant[12]]].decode, parameter[constant[utf-8]]] name[self].Length assign[=] call[name[reader].ReadUInt32, parameter[]] if compare[name[self].Length greater[>] name[self].PayloadMaxSizeInt] begin[:] <ast.Raise object at 0x7da1b22bb0d0> name[self].Checksum assign[=] call[name[reader].ReadUInt32, parameter[]] name[self].Payload assign[=] call[name[reader].ReadBytes, parameter[name[self].Length]] variable[checksum] assign[=] call[name[Message].GetChecksum, parameter[name[self].Payload]] if compare[name[checksum] not_equal[!=] name[self].Checksum] begin[:] <ast.Raise object at 0x7da1b22bac50>
keyword[def] identifier[Deserialize] ( identifier[self] , identifier[reader] ): literal[string] identifier[self] . identifier[Magic] = identifier[reader] . identifier[ReadUInt32] () identifier[self] . identifier[Command] = identifier[reader] . identifier[ReadFixedString] ( literal[int] ). identifier[decode] ( literal[string] ) identifier[self] . identifier[Length] = identifier[reader] . identifier[ReadUInt32] () keyword[if] identifier[self] . identifier[Length] > identifier[self] . identifier[PayloadMaxSizeInt] : keyword[raise] identifier[Exception] ( literal[string] ) identifier[self] . identifier[Checksum] = identifier[reader] . identifier[ReadUInt32] () identifier[self] . identifier[Payload] = identifier[reader] . identifier[ReadBytes] ( identifier[self] . identifier[Length] ) identifier[checksum] = identifier[Message] . identifier[GetChecksum] ( identifier[self] . identifier[Payload] ) keyword[if] identifier[checksum] != identifier[self] . identifier[Checksum] : keyword[raise] identifier[ChecksumException] ( literal[string] )
def Deserialize(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ self.Magic = reader.ReadUInt32() self.Command = reader.ReadFixedString(12).decode('utf-8') self.Length = reader.ReadUInt32() if self.Length > self.PayloadMaxSizeInt: raise Exception('invalid format- payload too large') # depends on [control=['if'], data=[]] self.Checksum = reader.ReadUInt32() self.Payload = reader.ReadBytes(self.Length) checksum = Message.GetChecksum(self.Payload) if checksum != self.Checksum: raise ChecksumException('checksum mismatch') # depends on [control=['if'], data=[]]
def command(self): """Extract query pattern from operations.""" if not self._command_calculated: self._command_calculated = True if self.operation == 'command': try: command_idx = self.split_tokens.index('command:') command = self.split_tokens[command_idx + 1] if command == '{': # workaround for <= 2.2 log files, # where command was not listed separately command = self.split_tokens[command_idx + 2][:-1] self._command = command.lower() except ValueError: pass return self._command
def function[command, parameter[self]]: constant[Extract query pattern from operations.] if <ast.UnaryOp object at 0x7da1b17b6950> begin[:] name[self]._command_calculated assign[=] constant[True] if compare[name[self].operation equal[==] constant[command]] begin[:] <ast.Try object at 0x7da1b17b6440> return[name[self]._command]
keyword[def] identifier[command] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[_command_calculated] : identifier[self] . identifier[_command_calculated] = keyword[True] keyword[if] identifier[self] . identifier[operation] == literal[string] : keyword[try] : identifier[command_idx] = identifier[self] . identifier[split_tokens] . identifier[index] ( literal[string] ) identifier[command] = identifier[self] . identifier[split_tokens] [ identifier[command_idx] + literal[int] ] keyword[if] identifier[command] == literal[string] : identifier[command] = identifier[self] . identifier[split_tokens] [ identifier[command_idx] + literal[int] ][:- literal[int] ] identifier[self] . identifier[_command] = identifier[command] . identifier[lower] () keyword[except] identifier[ValueError] : keyword[pass] keyword[return] identifier[self] . identifier[_command]
def command(self): """Extract query pattern from operations.""" if not self._command_calculated: self._command_calculated = True if self.operation == 'command': try: command_idx = self.split_tokens.index('command:') command = self.split_tokens[command_idx + 1] if command == '{': # workaround for <= 2.2 log files, # where command was not listed separately command = self.split_tokens[command_idx + 2][:-1] # depends on [control=['if'], data=['command']] self._command = command.lower() # depends on [control=['try'], data=[]] except ValueError: pass # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return self._command
def _rpc(self, get, child=None, **kwargs): """ This allows you to construct an arbitrary RPC call to retreive common stuff. For example: Configuration: get: "<get-configuration/>" Interface information: get: "<get-interface-information/>" A particular interfacece information: get: "<get-interface-information/>" child: "<interface-name>ge-0/0/0</interface-name>" """ rpc = etree.fromstring(get) if child: rpc.append(etree.fromstring(child)) response = self.device.execute(rpc) return etree.tostring(response)
def function[_rpc, parameter[self, get, child]]: constant[ This allows you to construct an arbitrary RPC call to retreive common stuff. For example: Configuration: get: "<get-configuration/>" Interface information: get: "<get-interface-information/>" A particular interfacece information: get: "<get-interface-information/>" child: "<interface-name>ge-0/0/0</interface-name>" ] variable[rpc] assign[=] call[name[etree].fromstring, parameter[name[get]]] if name[child] begin[:] call[name[rpc].append, parameter[call[name[etree].fromstring, parameter[name[child]]]]] variable[response] assign[=] call[name[self].device.execute, parameter[name[rpc]]] return[call[name[etree].tostring, parameter[name[response]]]]
keyword[def] identifier[_rpc] ( identifier[self] , identifier[get] , identifier[child] = keyword[None] ,** identifier[kwargs] ): literal[string] identifier[rpc] = identifier[etree] . identifier[fromstring] ( identifier[get] ) keyword[if] identifier[child] : identifier[rpc] . identifier[append] ( identifier[etree] . identifier[fromstring] ( identifier[child] )) identifier[response] = identifier[self] . identifier[device] . identifier[execute] ( identifier[rpc] ) keyword[return] identifier[etree] . identifier[tostring] ( identifier[response] )
def _rpc(self, get, child=None, **kwargs): """ This allows you to construct an arbitrary RPC call to retreive common stuff. For example: Configuration: get: "<get-configuration/>" Interface information: get: "<get-interface-information/>" A particular interfacece information: get: "<get-interface-information/>" child: "<interface-name>ge-0/0/0</interface-name>" """ rpc = etree.fromstring(get) if child: rpc.append(etree.fromstring(child)) # depends on [control=['if'], data=[]] response = self.device.execute(rpc) return etree.tostring(response)
def on_validation_batch_end(self): """ Finalize batch processing """ for callback in self.callbacks: callback.on_validation_batch_end(self) # Even with all the experience replay, we count the single rollout as a single batch self.epoch_info.result_accumulator.calculate(self)
def function[on_validation_batch_end, parameter[self]]: constant[ Finalize batch processing ] for taget[name[callback]] in starred[name[self].callbacks] begin[:] call[name[callback].on_validation_batch_end, parameter[name[self]]] call[name[self].epoch_info.result_accumulator.calculate, parameter[name[self]]]
keyword[def] identifier[on_validation_batch_end] ( identifier[self] ): literal[string] keyword[for] identifier[callback] keyword[in] identifier[self] . identifier[callbacks] : identifier[callback] . identifier[on_validation_batch_end] ( identifier[self] ) identifier[self] . identifier[epoch_info] . identifier[result_accumulator] . identifier[calculate] ( identifier[self] )
def on_validation_batch_end(self): """ Finalize batch processing """ for callback in self.callbacks: callback.on_validation_batch_end(self) # depends on [control=['for'], data=['callback']] # Even with all the experience replay, we count the single rollout as a single batch self.epoch_info.result_accumulator.calculate(self)
def set_frameworkcontroller_config(experiment_config, port, config_file_name): '''set kubeflow configuration''' frameworkcontroller_config_data = dict() frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig'] response = rest_put(cluster_metadata_url(port), json.dumps(frameworkcontroller_config_data), REST_TIME_OUT) err_message = None if not response or not response.status_code == 200: if response is not None: err_message = response.text _, stderr_full_path = get_log_path(config_file_name) with open(stderr_full_path, 'a+') as fout: fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':'))) return False, err_message result, message = setNNIManagerIp(experiment_config, port, config_file_name) if not result: return result, message #set trial_config return set_trial_config(experiment_config, port, config_file_name), err_message
def function[set_frameworkcontroller_config, parameter[experiment_config, port, config_file_name]]: constant[set kubeflow configuration] variable[frameworkcontroller_config_data] assign[=] call[name[dict], parameter[]] call[name[frameworkcontroller_config_data]][constant[frameworkcontroller_config]] assign[=] call[name[experiment_config]][constant[frameworkcontrollerConfig]] variable[response] assign[=] call[name[rest_put], parameter[call[name[cluster_metadata_url], parameter[name[port]]], call[name[json].dumps, parameter[name[frameworkcontroller_config_data]]], name[REST_TIME_OUT]]] variable[err_message] assign[=] constant[None] if <ast.BoolOp object at 0x7da2054a61d0> begin[:] if compare[name[response] is_not constant[None]] begin[:] variable[err_message] assign[=] name[response].text <ast.Tuple object at 0x7da2054a52a0> assign[=] call[name[get_log_path], parameter[name[config_file_name]]] with call[name[open], parameter[name[stderr_full_path], constant[a+]]] begin[:] call[name[fout].write, parameter[call[name[json].dumps, parameter[call[name[json].loads, parameter[name[err_message]]]]]]] return[tuple[[<ast.Constant object at 0x7da2054a4400>, <ast.Name object at 0x7da2054a4370>]]] <ast.Tuple object at 0x7da2054a6e30> assign[=] call[name[setNNIManagerIp], parameter[name[experiment_config], name[port], name[config_file_name]]] if <ast.UnaryOp object at 0x7da2054a7d90> begin[:] return[tuple[[<ast.Name object at 0x7da2054a5ae0>, <ast.Name object at 0x7da2054a5b10>]]] return[tuple[[<ast.Call object at 0x7da2054a49d0>, <ast.Name object at 0x7da1b1f382e0>]]]
keyword[def] identifier[set_frameworkcontroller_config] ( identifier[experiment_config] , identifier[port] , identifier[config_file_name] ): literal[string] identifier[frameworkcontroller_config_data] = identifier[dict] () identifier[frameworkcontroller_config_data] [ literal[string] ]= identifier[experiment_config] [ literal[string] ] identifier[response] = identifier[rest_put] ( identifier[cluster_metadata_url] ( identifier[port] ), identifier[json] . identifier[dumps] ( identifier[frameworkcontroller_config_data] ), identifier[REST_TIME_OUT] ) identifier[err_message] = keyword[None] keyword[if] keyword[not] identifier[response] keyword[or] keyword[not] identifier[response] . identifier[status_code] == literal[int] : keyword[if] identifier[response] keyword[is] keyword[not] keyword[None] : identifier[err_message] = identifier[response] . identifier[text] identifier[_] , identifier[stderr_full_path] = identifier[get_log_path] ( identifier[config_file_name] ) keyword[with] identifier[open] ( identifier[stderr_full_path] , literal[string] ) keyword[as] identifier[fout] : identifier[fout] . identifier[write] ( identifier[json] . identifier[dumps] ( identifier[json] . identifier[loads] ( identifier[err_message] ), identifier[indent] = literal[int] , identifier[sort_keys] = keyword[True] , identifier[separators] =( literal[string] , literal[string] ))) keyword[return] keyword[False] , identifier[err_message] identifier[result] , identifier[message] = identifier[setNNIManagerIp] ( identifier[experiment_config] , identifier[port] , identifier[config_file_name] ) keyword[if] keyword[not] identifier[result] : keyword[return] identifier[result] , identifier[message] keyword[return] identifier[set_trial_config] ( identifier[experiment_config] , identifier[port] , identifier[config_file_name] ), identifier[err_message]
def set_frameworkcontroller_config(experiment_config, port, config_file_name): """set kubeflow configuration""" frameworkcontroller_config_data = dict() frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig'] response = rest_put(cluster_metadata_url(port), json.dumps(frameworkcontroller_config_data), REST_TIME_OUT) err_message = None if not response or not response.status_code == 200: if response is not None: err_message = response.text (_, stderr_full_path) = get_log_path(config_file_name) with open(stderr_full_path, 'a+') as fout: fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':'))) # depends on [control=['with'], data=['fout']] # depends on [control=['if'], data=['response']] return (False, err_message) # depends on [control=['if'], data=[]] (result, message) = setNNIManagerIp(experiment_config, port, config_file_name) if not result: return (result, message) # depends on [control=['if'], data=[]] #set trial_config return (set_trial_config(experiment_config, port, config_file_name), err_message)
def __universal_read(file_path, file_type): """ Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type. :param str file_path: Path to file :param str file_type: One of approved file types: xls, xlsx, txt, lpd :return none: """ global files, cwd, settings # check that we are using the correct function to load this file type. (i.e. readNoaa for a .txt file) correct_ext = load_fn_matches_ext(file_path, file_type) # Check that this path references a file valid_path = path_type(file_path, "file") # is the path a file? if valid_path and correct_ext: # get file metadata for one file file_meta = collect_metadata_file(file_path) # append to global files, then load in D if file_type == ".lpd": # add meta to global file meta files[".lpd"].append(file_meta) # append to global files elif file_type in [".xls", ".xlsx"]: print("reading: {}".format(print_filename(file_meta["full_path"]))) files[".xls"].append(file_meta) # append to global files elif file_type == ".txt": print("reading: {}".format(print_filename(file_meta["full_path"]))) files[".txt"].append(file_meta) # we want to move around with the files we load # change dir into the dir of the target file cwd = file_meta["dir"] if cwd: os.chdir(cwd) return
def function[__universal_read, parameter[file_path, file_type]]: constant[ Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type. :param str file_path: Path to file :param str file_type: One of approved file types: xls, xlsx, txt, lpd :return none: ] <ast.Global object at 0x7da18f00dc60> variable[correct_ext] assign[=] call[name[load_fn_matches_ext], parameter[name[file_path], name[file_type]]] variable[valid_path] assign[=] call[name[path_type], parameter[name[file_path], constant[file]]] if <ast.BoolOp object at 0x7da2044c3160> begin[:] variable[file_meta] assign[=] call[name[collect_metadata_file], parameter[name[file_path]]] if compare[name[file_type] equal[==] constant[.lpd]] begin[:] call[call[name[files]][constant[.lpd]].append, parameter[name[file_meta]]] variable[cwd] assign[=] call[name[file_meta]][constant[dir]] if name[cwd] begin[:] call[name[os].chdir, parameter[name[cwd]]] return[None]
keyword[def] identifier[__universal_read] ( identifier[file_path] , identifier[file_type] ): literal[string] keyword[global] identifier[files] , identifier[cwd] , identifier[settings] identifier[correct_ext] = identifier[load_fn_matches_ext] ( identifier[file_path] , identifier[file_type] ) identifier[valid_path] = identifier[path_type] ( identifier[file_path] , literal[string] ) keyword[if] identifier[valid_path] keyword[and] identifier[correct_ext] : identifier[file_meta] = identifier[collect_metadata_file] ( identifier[file_path] ) keyword[if] identifier[file_type] == literal[string] : identifier[files] [ literal[string] ]. identifier[append] ( identifier[file_meta] ) keyword[elif] identifier[file_type] keyword[in] [ literal[string] , literal[string] ]: identifier[print] ( literal[string] . identifier[format] ( identifier[print_filename] ( identifier[file_meta] [ literal[string] ]))) identifier[files] [ literal[string] ]. identifier[append] ( identifier[file_meta] ) keyword[elif] identifier[file_type] == literal[string] : identifier[print] ( literal[string] . identifier[format] ( identifier[print_filename] ( identifier[file_meta] [ literal[string] ]))) identifier[files] [ literal[string] ]. identifier[append] ( identifier[file_meta] ) identifier[cwd] = identifier[file_meta] [ literal[string] ] keyword[if] identifier[cwd] : identifier[os] . identifier[chdir] ( identifier[cwd] ) keyword[return]
def __universal_read(file_path, file_type): """ Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type. :param str file_path: Path to file :param str file_type: One of approved file types: xls, xlsx, txt, lpd :return none: """ global files, cwd, settings # check that we are using the correct function to load this file type. (i.e. readNoaa for a .txt file) correct_ext = load_fn_matches_ext(file_path, file_type) # Check that this path references a file valid_path = path_type(file_path, 'file') # is the path a file? if valid_path and correct_ext: # get file metadata for one file file_meta = collect_metadata_file(file_path) # append to global files, then load in D if file_type == '.lpd': # add meta to global file meta files['.lpd'].append(file_meta) # depends on [control=['if'], data=[]] # append to global files elif file_type in ['.xls', '.xlsx']: print('reading: {}'.format(print_filename(file_meta['full_path']))) files['.xls'].append(file_meta) # depends on [control=['if'], data=[]] # append to global files elif file_type == '.txt': print('reading: {}'.format(print_filename(file_meta['full_path']))) files['.txt'].append(file_meta) # depends on [control=['if'], data=[]] # we want to move around with the files we load # change dir into the dir of the target file cwd = file_meta['dir'] if cwd: os.chdir(cwd) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return
def register_key_binding(self, keydef, callback_or_cmd, mode='force'): """Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python callback function. See ``MPV.key_binding`` for details. """ if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef): raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n' '<key> is either the literal character the key produces (ASCII or Unicode character), or a ' 'symbolic name (as printed by --input-keylist') binding_name = MPV._binding_name(keydef) if callable(callback_or_cmd): self._key_binding_handlers[binding_name] = callback_or_cmd self.register_message_handler('key-binding', self._handle_key_binding_message) self.command('define-section', binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode) elif isinstance(callback_or_cmd, str): self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode) else: raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.') self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def function[register_key_binding, parameter[self, keydef, callback_or_cmd, mode]]: constant[Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python callback function. See ``MPV.key_binding`` for details. ] if <ast.UnaryOp object at 0x7da204347ca0> begin[:] <ast.Raise object at 0x7da204344d30> variable[binding_name] assign[=] call[name[MPV]._binding_name, parameter[name[keydef]]] if call[name[callable], parameter[name[callback_or_cmd]]] begin[:] call[name[self]._key_binding_handlers][name[binding_name]] assign[=] name[callback_or_cmd] call[name[self].register_message_handler, parameter[constant[key-binding], name[self]._handle_key_binding_message]] call[name[self].command, parameter[constant[define-section], name[binding_name], call[constant[{} script-binding py_event_handler/{}].format, parameter[name[keydef], name[binding_name]]], name[mode]]] call[name[self].command, parameter[constant[enable-section], name[binding_name], constant[allow-hide-cursor+allow-vo-dragging]]]
keyword[def] identifier[register_key_binding] ( identifier[self] , identifier[keydef] , identifier[callback_or_cmd] , identifier[mode] = literal[string] ): literal[string] keyword[if] keyword[not] identifier[re] . identifier[match] ( literal[string] , identifier[keydef] ): keyword[raise] identifier[ValueError] ( literal[string] literal[string] literal[string] ) identifier[binding_name] = identifier[MPV] . identifier[_binding_name] ( identifier[keydef] ) keyword[if] identifier[callable] ( identifier[callback_or_cmd] ): identifier[self] . identifier[_key_binding_handlers] [ identifier[binding_name] ]= identifier[callback_or_cmd] identifier[self] . identifier[register_message_handler] ( literal[string] , identifier[self] . identifier[_handle_key_binding_message] ) identifier[self] . identifier[command] ( literal[string] , identifier[binding_name] , literal[string] . identifier[format] ( identifier[keydef] , identifier[binding_name] ), identifier[mode] ) keyword[elif] identifier[isinstance] ( identifier[callback_or_cmd] , identifier[str] ): identifier[self] . identifier[command] ( literal[string] , identifier[binding_name] , literal[string] . identifier[format] ( identifier[keydef] , identifier[callback_or_cmd] ), identifier[mode] ) keyword[else] : keyword[raise] identifier[TypeError] ( literal[string] ) identifier[self] . identifier[command] ( literal[string] , identifier[binding_name] , literal[string] )
def register_key_binding(self, keydef, callback_or_cmd, mode='force'): """Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python callback function. See ``MPV.key_binding`` for details. """ if not re.match('(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\\w+)', keydef): raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n<key> is either the literal character the key produces (ASCII or Unicode character), or a symbolic name (as printed by --input-keylist') # depends on [control=['if'], data=[]] binding_name = MPV._binding_name(keydef) if callable(callback_or_cmd): self._key_binding_handlers[binding_name] = callback_or_cmd self.register_message_handler('key-binding', self._handle_key_binding_message) self.command('define-section', binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode) # depends on [control=['if'], data=[]] elif isinstance(callback_or_cmd, str): self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode) # depends on [control=['if'], data=[]] else: raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.') self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def check(self, line): """ Find first occurrence of 'line' in file. This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep() If found, return the line; this makes it easier to chain methods. :param line: String; whole line to find. :return: String or False. """ if not isinstance(line, str): raise TypeError("Parameter 'line' not a 'string', is {0}".format(type(line))) if line in self.contents: return line return False
def function[check, parameter[self, line]]: constant[ Find first occurrence of 'line' in file. This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep() If found, return the line; this makes it easier to chain methods. :param line: String; whole line to find. :return: String or False. ] if <ast.UnaryOp object at 0x7da1b16019c0> begin[:] <ast.Raise object at 0x7da1b1601e70> if compare[name[line] in name[self].contents] begin[:] return[name[line]] return[constant[False]]
keyword[def] identifier[check] ( identifier[self] , identifier[line] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[line] , identifier[str] ): keyword[raise] identifier[TypeError] ( literal[string] . identifier[format] ( identifier[type] ( identifier[line] ))) keyword[if] identifier[line] keyword[in] identifier[self] . identifier[contents] : keyword[return] identifier[line] keyword[return] keyword[False]
def check(self, line): """ Find first occurrence of 'line' in file. This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep() If found, return the line; this makes it easier to chain methods. :param line: String; whole line to find. :return: String or False. """ if not isinstance(line, str): raise TypeError("Parameter 'line' not a 'string', is {0}".format(type(line))) # depends on [control=['if'], data=[]] if line in self.contents: return line # depends on [control=['if'], data=['line']] return False
def tryForwarding(self, request: Request): """ Try to forward the request if the required conditions are met. See the method `canForward` for the conditions to check before forwarding a request. """ cannot_reason_msg = self.canForward(request) if cannot_reason_msg is None: # If haven't got the client request(REQUEST) for the corresponding # propagate request(PROPAGATE) but have enough propagate requests # to move ahead self.forward(request) else: logger.trace("{} not forwarding request {} to its replicas " "since {}".format(self, request, cannot_reason_msg))
def function[tryForwarding, parameter[self, request]]: constant[ Try to forward the request if the required conditions are met. See the method `canForward` for the conditions to check before forwarding a request. ] variable[cannot_reason_msg] assign[=] call[name[self].canForward, parameter[name[request]]] if compare[name[cannot_reason_msg] is constant[None]] begin[:] call[name[self].forward, parameter[name[request]]]
keyword[def] identifier[tryForwarding] ( identifier[self] , identifier[request] : identifier[Request] ): literal[string] identifier[cannot_reason_msg] = identifier[self] . identifier[canForward] ( identifier[request] ) keyword[if] identifier[cannot_reason_msg] keyword[is] keyword[None] : identifier[self] . identifier[forward] ( identifier[request] ) keyword[else] : identifier[logger] . identifier[trace] ( literal[string] literal[string] . identifier[format] ( identifier[self] , identifier[request] , identifier[cannot_reason_msg] ))
def tryForwarding(self, request: Request): """ Try to forward the request if the required conditions are met. See the method `canForward` for the conditions to check before forwarding a request. """ cannot_reason_msg = self.canForward(request) if cannot_reason_msg is None: # If haven't got the client request(REQUEST) for the corresponding # propagate request(PROPAGATE) but have enough propagate requests # to move ahead self.forward(request) # depends on [control=['if'], data=[]] else: logger.trace('{} not forwarding request {} to its replicas since {}'.format(self, request, cannot_reason_msg))
def check_info(info): """ Validate info dict. Raise ValueError if validation fails. """ if not isinstance(info, dict): raise ValueError("bad metainfo - not a dictionary") pieces = info.get("pieces") if not isinstance(pieces, basestring) or len(pieces) % 20 != 0: raise ValueError("bad metainfo - bad pieces key") piece_size = info.get("piece length") if not isinstance(piece_size, (int, long)) or piece_size <= 0: raise ValueError("bad metainfo - illegal piece length") name = info.get("name") if not isinstance(name, basestring): raise ValueError("bad metainfo - bad name (type is %r)" % type(name).__name__) if not ALLOWED_ROOT_NAME.match(name): raise ValueError("name %s disallowed for security reasons" % name) if ("files" in info) == ("length" in info): raise ValueError("single/multiple file mix") if "length" in info: length = info.get("length") if not isinstance(length, (int, long)) or length < 0: raise ValueError("bad metainfo - bad length") else: files = info.get("files") if not isinstance(files, (list, tuple)): raise ValueError("bad metainfo - bad file list") for item in files: if not isinstance(item, dict): raise ValueError("bad metainfo - bad file value") length = item.get("length") if not isinstance(length, (int, long)) or length < 0: raise ValueError("bad metainfo - bad length") path = item.get("path") if not isinstance(path, (list, tuple)) or not path: raise ValueError("bad metainfo - bad path") for part in path: if not isinstance(part, basestring): raise ValueError("bad metainfo - bad path dir") part = fmt.to_unicode(part) if part == '..': raise ValueError("relative path in %s disallowed for security reasons" % '/'.join(path)) if part and not ALLOWED_PATH_NAME.match(part): raise ValueError("path %s disallowed for security reasons" % part) file_paths = [os.sep.join(item["path"]) for item in files] if len(set(file_paths)) != len(file_paths): raise ValueError("bad metainfo - duplicate path") return info
def function[check_info, parameter[info]]: constant[ Validate info dict. Raise ValueError if validation fails. ] if <ast.UnaryOp object at 0x7da2044c3070> begin[:] <ast.Raise object at 0x7da2044c1de0> variable[pieces] assign[=] call[name[info].get, parameter[constant[pieces]]] if <ast.BoolOp object at 0x7da2044c3640> begin[:] <ast.Raise object at 0x7da2044c3d90> variable[piece_size] assign[=] call[name[info].get, parameter[constant[piece length]]] if <ast.BoolOp object at 0x7da2044c29b0> begin[:] <ast.Raise object at 0x7da2044c2710> variable[name] assign[=] call[name[info].get, parameter[constant[name]]] if <ast.UnaryOp object at 0x7da2044c0370> begin[:] <ast.Raise object at 0x7da2044c2320> if <ast.UnaryOp object at 0x7da2044c04c0> begin[:] <ast.Raise object at 0x7da2044c3310> if compare[compare[constant[files] in name[info]] equal[==] compare[constant[length] in name[info]]] begin[:] <ast.Raise object at 0x7da2044c0b20> if compare[constant[length] in name[info]] begin[:] variable[length] assign[=] call[name[info].get, parameter[constant[length]]] if <ast.BoolOp object at 0x7da2054a52a0> begin[:] <ast.Raise object at 0x7da2054a58d0> return[name[info]]
keyword[def] identifier[check_info] ( identifier[info] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[info] , identifier[dict] ): keyword[raise] identifier[ValueError] ( literal[string] ) identifier[pieces] = identifier[info] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[pieces] , identifier[basestring] ) keyword[or] identifier[len] ( identifier[pieces] )% literal[int] != literal[int] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[piece_size] = identifier[info] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[piece_size] ,( identifier[int] , identifier[long] )) keyword[or] identifier[piece_size] <= literal[int] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[name] = identifier[info] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[name] , identifier[basestring] ): keyword[raise] identifier[ValueError] ( literal[string] % identifier[type] ( identifier[name] ). identifier[__name__] ) keyword[if] keyword[not] identifier[ALLOWED_ROOT_NAME] . identifier[match] ( identifier[name] ): keyword[raise] identifier[ValueError] ( literal[string] % identifier[name] ) keyword[if] ( literal[string] keyword[in] identifier[info] )==( literal[string] keyword[in] identifier[info] ): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] literal[string] keyword[in] identifier[info] : identifier[length] = identifier[info] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[length] ,( identifier[int] , identifier[long] )) keyword[or] identifier[length] < literal[int] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[else] : identifier[files] = identifier[info] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[files] ,( identifier[list] , identifier[tuple] )): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[for] identifier[item] keyword[in] identifier[files] : keyword[if] keyword[not] identifier[isinstance] ( identifier[item] , identifier[dict] ): keyword[raise] identifier[ValueError] ( literal[string] ) identifier[length] = identifier[item] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[length] ,( identifier[int] , identifier[long] )) keyword[or] identifier[length] < literal[int] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[path] = identifier[item] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[path] ,( identifier[list] , identifier[tuple] )) keyword[or] keyword[not] identifier[path] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[for] identifier[part] keyword[in] identifier[path] : keyword[if] keyword[not] identifier[isinstance] ( identifier[part] , identifier[basestring] ): keyword[raise] identifier[ValueError] ( literal[string] ) identifier[part] = identifier[fmt] . identifier[to_unicode] ( identifier[part] ) keyword[if] identifier[part] == literal[string] : keyword[raise] identifier[ValueError] ( literal[string] % literal[string] . identifier[join] ( identifier[path] )) keyword[if] identifier[part] keyword[and] keyword[not] identifier[ALLOWED_PATH_NAME] . identifier[match] ( identifier[part] ): keyword[raise] identifier[ValueError] ( literal[string] % identifier[part] ) identifier[file_paths] =[ identifier[os] . identifier[sep] . identifier[join] ( identifier[item] [ literal[string] ]) keyword[for] identifier[item] keyword[in] identifier[files] ] keyword[if] identifier[len] ( identifier[set] ( identifier[file_paths] ))!= identifier[len] ( identifier[file_paths] ): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[return] identifier[info]
def check_info(info): """ Validate info dict. Raise ValueError if validation fails. """ if not isinstance(info, dict): raise ValueError('bad metainfo - not a dictionary') # depends on [control=['if'], data=[]] pieces = info.get('pieces') if not isinstance(pieces, basestring) or len(pieces) % 20 != 0: raise ValueError('bad metainfo - bad pieces key') # depends on [control=['if'], data=[]] piece_size = info.get('piece length') if not isinstance(piece_size, (int, long)) or piece_size <= 0: raise ValueError('bad metainfo - illegal piece length') # depends on [control=['if'], data=[]] name = info.get('name') if not isinstance(name, basestring): raise ValueError('bad metainfo - bad name (type is %r)' % type(name).__name__) # depends on [control=['if'], data=[]] if not ALLOWED_ROOT_NAME.match(name): raise ValueError('name %s disallowed for security reasons' % name) # depends on [control=['if'], data=[]] if ('files' in info) == ('length' in info): raise ValueError('single/multiple file mix') # depends on [control=['if'], data=[]] if 'length' in info: length = info.get('length') if not isinstance(length, (int, long)) or length < 0: raise ValueError('bad metainfo - bad length') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['info']] else: files = info.get('files') if not isinstance(files, (list, tuple)): raise ValueError('bad metainfo - bad file list') # depends on [control=['if'], data=[]] for item in files: if not isinstance(item, dict): raise ValueError('bad metainfo - bad file value') # depends on [control=['if'], data=[]] length = item.get('length') if not isinstance(length, (int, long)) or length < 0: raise ValueError('bad metainfo - bad length') # depends on [control=['if'], data=[]] path = item.get('path') if not isinstance(path, (list, tuple)) or not path: raise ValueError('bad metainfo - bad path') # depends on [control=['if'], data=[]] for part in path: if not isinstance(part, basestring): raise ValueError('bad metainfo - bad path dir') # depends on [control=['if'], data=[]] part = fmt.to_unicode(part) if part == '..': raise ValueError('relative path in %s disallowed for security reasons' % '/'.join(path)) # depends on [control=['if'], data=[]] if part and (not ALLOWED_PATH_NAME.match(part)): raise ValueError('path %s disallowed for security reasons' % part) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['part']] # depends on [control=['for'], data=['item']] file_paths = [os.sep.join(item['path']) for item in files] if len(set(file_paths)) != len(file_paths): raise ValueError('bad metainfo - duplicate path') # depends on [control=['if'], data=[]] return info
def get_epoch_namespace_receive_fees_period( block_height, namespace_id ): """ how long can a namespace receive register/renewal fees? """ epoch_config = get_epoch_config( block_height ) if epoch_config['namespaces'].has_key(namespace_id): return epoch_config['namespaces'][namespace_id]['NAMESPACE_RECEIVE_FEES_PERIOD'] else: return epoch_config['namespaces']['*']['NAMESPACE_RECEIVE_FEES_PERIOD']
def function[get_epoch_namespace_receive_fees_period, parameter[block_height, namespace_id]]: constant[ how long can a namespace receive register/renewal fees? ] variable[epoch_config] assign[=] call[name[get_epoch_config], parameter[name[block_height]]] if call[call[name[epoch_config]][constant[namespaces]].has_key, parameter[name[namespace_id]]] begin[:] return[call[call[call[name[epoch_config]][constant[namespaces]]][name[namespace_id]]][constant[NAMESPACE_RECEIVE_FEES_PERIOD]]]
keyword[def] identifier[get_epoch_namespace_receive_fees_period] ( identifier[block_height] , identifier[namespace_id] ): literal[string] identifier[epoch_config] = identifier[get_epoch_config] ( identifier[block_height] ) keyword[if] identifier[epoch_config] [ literal[string] ]. identifier[has_key] ( identifier[namespace_id] ): keyword[return] identifier[epoch_config] [ literal[string] ][ identifier[namespace_id] ][ literal[string] ] keyword[else] : keyword[return] identifier[epoch_config] [ literal[string] ][ literal[string] ][ literal[string] ]
def get_epoch_namespace_receive_fees_period(block_height, namespace_id): """ how long can a namespace receive register/renewal fees? """ epoch_config = get_epoch_config(block_height) if epoch_config['namespaces'].has_key(namespace_id): return epoch_config['namespaces'][namespace_id]['NAMESPACE_RECEIVE_FEES_PERIOD'] # depends on [control=['if'], data=[]] else: return epoch_config['namespaces']['*']['NAMESPACE_RECEIVE_FEES_PERIOD']
def infer_getattr(node, context=None): """Understand getattr calls If one of the arguments is an Uninferable object, then the result will be an Uninferable object. Otherwise, the normal attribute lookup will be done. """ obj, attr = _infer_getattr_args(node, context) if ( obj is util.Uninferable or attr is util.Uninferable or not hasattr(obj, "igetattr") ): return util.Uninferable try: return next(obj.igetattr(attr, context=context)) except (StopIteration, InferenceError, AttributeInferenceError): if len(node.args) == 3: # Try to infer the default and return it instead. try: return next(node.args[2].infer(context=context)) except InferenceError: raise UseInferenceDefault raise UseInferenceDefault
def function[infer_getattr, parameter[node, context]]: constant[Understand getattr calls If one of the arguments is an Uninferable object, then the result will be an Uninferable object. Otherwise, the normal attribute lookup will be done. ] <ast.Tuple object at 0x7da1b1da16f0> assign[=] call[name[_infer_getattr_args], parameter[name[node], name[context]]] if <ast.BoolOp object at 0x7da1b1da3280> begin[:] return[name[util].Uninferable] <ast.Try object at 0x7da1b1da37f0> <ast.Raise object at 0x7da1b1ec29b0>
keyword[def] identifier[infer_getattr] ( identifier[node] , identifier[context] = keyword[None] ): literal[string] identifier[obj] , identifier[attr] = identifier[_infer_getattr_args] ( identifier[node] , identifier[context] ) keyword[if] ( identifier[obj] keyword[is] identifier[util] . identifier[Uninferable] keyword[or] identifier[attr] keyword[is] identifier[util] . identifier[Uninferable] keyword[or] keyword[not] identifier[hasattr] ( identifier[obj] , literal[string] ) ): keyword[return] identifier[util] . identifier[Uninferable] keyword[try] : keyword[return] identifier[next] ( identifier[obj] . identifier[igetattr] ( identifier[attr] , identifier[context] = identifier[context] )) keyword[except] ( identifier[StopIteration] , identifier[InferenceError] , identifier[AttributeInferenceError] ): keyword[if] identifier[len] ( identifier[node] . identifier[args] )== literal[int] : keyword[try] : keyword[return] identifier[next] ( identifier[node] . identifier[args] [ literal[int] ]. identifier[infer] ( identifier[context] = identifier[context] )) keyword[except] identifier[InferenceError] : keyword[raise] identifier[UseInferenceDefault] keyword[raise] identifier[UseInferenceDefault]
def infer_getattr(node, context=None): """Understand getattr calls If one of the arguments is an Uninferable object, then the result will be an Uninferable object. Otherwise, the normal attribute lookup will be done. """ (obj, attr) = _infer_getattr_args(node, context) if obj is util.Uninferable or attr is util.Uninferable or (not hasattr(obj, 'igetattr')): return util.Uninferable # depends on [control=['if'], data=[]] try: return next(obj.igetattr(attr, context=context)) # depends on [control=['try'], data=[]] except (StopIteration, InferenceError, AttributeInferenceError): if len(node.args) == 3: # Try to infer the default and return it instead. try: return next(node.args[2].infer(context=context)) # depends on [control=['try'], data=[]] except InferenceError: raise UseInferenceDefault # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['except'], data=[]] raise UseInferenceDefault
def insert_markers(asm_lines, start_line, end_line): """Insert IACA marker into list of ASM instructions at given indices.""" asm_lines = (asm_lines[:start_line] + START_MARKER + asm_lines[start_line:end_line + 1] + END_MARKER + asm_lines[end_line + 1:]) return asm_lines
def function[insert_markers, parameter[asm_lines, start_line, end_line]]: constant[Insert IACA marker into list of ASM instructions at given indices.] variable[asm_lines] assign[=] binary_operation[binary_operation[binary_operation[binary_operation[call[name[asm_lines]][<ast.Slice object at 0x7da2054a50c0>] + name[START_MARKER]] + call[name[asm_lines]][<ast.Slice object at 0x7da2054a6e30>]] + name[END_MARKER]] + call[name[asm_lines]][<ast.Slice object at 0x7da2054a5510>]] return[name[asm_lines]]
keyword[def] identifier[insert_markers] ( identifier[asm_lines] , identifier[start_line] , identifier[end_line] ): literal[string] identifier[asm_lines] =( identifier[asm_lines] [: identifier[start_line] ]+ identifier[START_MARKER] + identifier[asm_lines] [ identifier[start_line] : identifier[end_line] + literal[int] ]+ identifier[END_MARKER] + identifier[asm_lines] [ identifier[end_line] + literal[int] :]) keyword[return] identifier[asm_lines]
def insert_markers(asm_lines, start_line, end_line): """Insert IACA marker into list of ASM instructions at given indices.""" asm_lines = asm_lines[:start_line] + START_MARKER + asm_lines[start_line:end_line + 1] + END_MARKER + asm_lines[end_line + 1:] return asm_lines
def tz_path(name): """ Return the path to a timezone file. :param name: The name of the timezone. :type name: str :rtype: str """ if not name: raise ValueError('Invalid timezone') name_parts = name.lstrip('/').split('/') for part in name_parts: if part == os.path.pardir or os.path.sep in part: raise ValueError('Bad path segment: %r' % part) filepath = os.path.join(_DIRECTORY, *name_parts) if not os.path.exists(filepath): raise TimezoneNotFound('Timezone {} not found at {}'.format(name, filepath)) return filepath
def function[tz_path, parameter[name]]: constant[ Return the path to a timezone file. :param name: The name of the timezone. :type name: str :rtype: str ] if <ast.UnaryOp object at 0x7da1b191dde0> begin[:] <ast.Raise object at 0x7da1b191d8d0> variable[name_parts] assign[=] call[call[name[name].lstrip, parameter[constant[/]]].split, parameter[constant[/]]] for taget[name[part]] in starred[name[name_parts]] begin[:] if <ast.BoolOp object at 0x7da1b191f820> begin[:] <ast.Raise object at 0x7da1b191e7a0> variable[filepath] assign[=] call[name[os].path.join, parameter[name[_DIRECTORY], <ast.Starred object at 0x7da1b191cee0>]] if <ast.UnaryOp object at 0x7da1b191e620> begin[:] <ast.Raise object at 0x7da1b191e5c0> return[name[filepath]]
keyword[def] identifier[tz_path] ( identifier[name] ): literal[string] keyword[if] keyword[not] identifier[name] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[name_parts] = identifier[name] . identifier[lstrip] ( literal[string] ). identifier[split] ( literal[string] ) keyword[for] identifier[part] keyword[in] identifier[name_parts] : keyword[if] identifier[part] == identifier[os] . identifier[path] . identifier[pardir] keyword[or] identifier[os] . identifier[path] . identifier[sep] keyword[in] identifier[part] : keyword[raise] identifier[ValueError] ( literal[string] % identifier[part] ) identifier[filepath] = identifier[os] . identifier[path] . identifier[join] ( identifier[_DIRECTORY] ,* identifier[name_parts] ) keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[filepath] ): keyword[raise] identifier[TimezoneNotFound] ( literal[string] . identifier[format] ( identifier[name] , identifier[filepath] )) keyword[return] identifier[filepath]
def tz_path(name): """ Return the path to a timezone file. :param name: The name of the timezone. :type name: str :rtype: str """ if not name: raise ValueError('Invalid timezone') # depends on [control=['if'], data=[]] name_parts = name.lstrip('/').split('/') for part in name_parts: if part == os.path.pardir or os.path.sep in part: raise ValueError('Bad path segment: %r' % part) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['part']] filepath = os.path.join(_DIRECTORY, *name_parts) if not os.path.exists(filepath): raise TimezoneNotFound('Timezone {} not found at {}'.format(name, filepath)) # depends on [control=['if'], data=[]] return filepath
def submatrix(dmat, indices_col, n_neighbors): """Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consists of the indices of the columns. n_neighbors: int Number of neighbors. Returns ------- submat: array, shape (n_samples, n_neighbors) The corresponding submatrix. """ n_samples_transform, n_samples_fit = dmat.shape submat = np.zeros((n_samples_transform, n_neighbors), dtype=dmat.dtype) for i in numba.prange(n_samples_transform): for j in numba.prange(n_neighbors): submat[i, j] = dmat[i, indices_col[i, j]] return submat
def function[submatrix, parameter[dmat, indices_col, n_neighbors]]: constant[Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consists of the indices of the columns. n_neighbors: int Number of neighbors. Returns ------- submat: array, shape (n_samples, n_neighbors) The corresponding submatrix. ] <ast.Tuple object at 0x7da18f00ea40> assign[=] name[dmat].shape variable[submat] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Name object at 0x7da18f00eb00>, <ast.Name object at 0x7da18f00de40>]]]] for taget[name[i]] in starred[call[name[numba].prange, parameter[name[n_samples_transform]]]] begin[:] for taget[name[j]] in starred[call[name[numba].prange, parameter[name[n_neighbors]]]] begin[:] call[name[submat]][tuple[[<ast.Name object at 0x7da18f00c940>, <ast.Name object at 0x7da18f00c910>]]] assign[=] call[name[dmat]][tuple[[<ast.Name object at 0x7da18f00d5d0>, <ast.Subscript object at 0x7da18f00fd00>]]] return[name[submat]]
keyword[def] identifier[submatrix] ( identifier[dmat] , identifier[indices_col] , identifier[n_neighbors] ): literal[string] identifier[n_samples_transform] , identifier[n_samples_fit] = identifier[dmat] . identifier[shape] identifier[submat] = identifier[np] . identifier[zeros] (( identifier[n_samples_transform] , identifier[n_neighbors] ), identifier[dtype] = identifier[dmat] . identifier[dtype] ) keyword[for] identifier[i] keyword[in] identifier[numba] . identifier[prange] ( identifier[n_samples_transform] ): keyword[for] identifier[j] keyword[in] identifier[numba] . identifier[prange] ( identifier[n_neighbors] ): identifier[submat] [ identifier[i] , identifier[j] ]= identifier[dmat] [ identifier[i] , identifier[indices_col] [ identifier[i] , identifier[j] ]] keyword[return] identifier[submat]
def submatrix(dmat, indices_col, n_neighbors): """Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consists of the indices of the columns. n_neighbors: int Number of neighbors. Returns ------- submat: array, shape (n_samples, n_neighbors) The corresponding submatrix. """ (n_samples_transform, n_samples_fit) = dmat.shape submat = np.zeros((n_samples_transform, n_neighbors), dtype=dmat.dtype) for i in numba.prange(n_samples_transform): for j in numba.prange(n_neighbors): submat[i, j] = dmat[i, indices_col[i, j]] # depends on [control=['for'], data=['j']] # depends on [control=['for'], data=['i']] return submat
def map_exception_codes(): '''Helper function to intialise CODES_TO_EXCEPTIONS.''' werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None)) return {e.code: e for _, e in werkex}
def function[map_exception_codes, parameter[]]: constant[Helper function to intialise CODES_TO_EXCEPTIONS.] variable[werkex] assign[=] call[name[inspect].getmembers, parameter[name[exceptions], <ast.Lambda object at 0x7da1b15a1b70>]] return[<ast.DictComp object at 0x7da1b15a17b0>]
keyword[def] identifier[map_exception_codes] (): literal[string] identifier[werkex] = identifier[inspect] . identifier[getmembers] ( identifier[exceptions] , keyword[lambda] identifier[x] : identifier[getattr] ( identifier[x] , literal[string] , keyword[None] )) keyword[return] { identifier[e] . identifier[code] : identifier[e] keyword[for] identifier[_] , identifier[e] keyword[in] identifier[werkex] }
def map_exception_codes(): """Helper function to intialise CODES_TO_EXCEPTIONS.""" werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None)) return {e.code: e for (_, e) in werkex}
def config_oauth(app): " Configure oauth support. " for name in PROVIDERS: config = app.config.get('OAUTH_%s' % name.upper()) if not config: continue if not name in oauth.remote_apps: remote_app = oauth.remote_app(name, **config) else: remote_app = oauth.remote_apps[name] client_class = CLIENTS.get(name) client_class(app, remote_app)
def function[config_oauth, parameter[app]]: constant[ Configure oauth support. ] for taget[name[name]] in starred[name[PROVIDERS]] begin[:] variable[config] assign[=] call[name[app].config.get, parameter[binary_operation[constant[OAUTH_%s] <ast.Mod object at 0x7da2590d6920> call[name[name].upper, parameter[]]]]] if <ast.UnaryOp object at 0x7da1b0aa4e50> begin[:] continue if <ast.UnaryOp object at 0x7da1b0aa4d60> begin[:] variable[remote_app] assign[=] call[name[oauth].remote_app, parameter[name[name]]] variable[client_class] assign[=] call[name[CLIENTS].get, parameter[name[name]]] call[name[client_class], parameter[name[app], name[remote_app]]]
keyword[def] identifier[config_oauth] ( identifier[app] ): literal[string] keyword[for] identifier[name] keyword[in] identifier[PROVIDERS] : identifier[config] = identifier[app] . identifier[config] . identifier[get] ( literal[string] % identifier[name] . identifier[upper] ()) keyword[if] keyword[not] identifier[config] : keyword[continue] keyword[if] keyword[not] identifier[name] keyword[in] identifier[oauth] . identifier[remote_apps] : identifier[remote_app] = identifier[oauth] . identifier[remote_app] ( identifier[name] ,** identifier[config] ) keyword[else] : identifier[remote_app] = identifier[oauth] . identifier[remote_apps] [ identifier[name] ] identifier[client_class] = identifier[CLIENTS] . identifier[get] ( identifier[name] ) identifier[client_class] ( identifier[app] , identifier[remote_app] )
def config_oauth(app): """ Configure oauth support. """ for name in PROVIDERS: config = app.config.get('OAUTH_%s' % name.upper()) if not config: continue # depends on [control=['if'], data=[]] if not name in oauth.remote_apps: remote_app = oauth.remote_app(name, **config) # depends on [control=['if'], data=[]] else: remote_app = oauth.remote_apps[name] client_class = CLIENTS.get(name) client_class(app, remote_app) # depends on [control=['for'], data=['name']]
def space(self): """Get system disk space usage. :return: :class:`system.Space <system.Space>` object :rtype: system.Space """ schema = SpaceSchema() resp = self.service.get(self.base+'space/') return self.service.decode(schema, resp)
def function[space, parameter[self]]: constant[Get system disk space usage. :return: :class:`system.Space <system.Space>` object :rtype: system.Space ] variable[schema] assign[=] call[name[SpaceSchema], parameter[]] variable[resp] assign[=] call[name[self].service.get, parameter[binary_operation[name[self].base + constant[space/]]]] return[call[name[self].service.decode, parameter[name[schema], name[resp]]]]
keyword[def] identifier[space] ( identifier[self] ): literal[string] identifier[schema] = identifier[SpaceSchema] () identifier[resp] = identifier[self] . identifier[service] . identifier[get] ( identifier[self] . identifier[base] + literal[string] ) keyword[return] identifier[self] . identifier[service] . identifier[decode] ( identifier[schema] , identifier[resp] )
def space(self): """Get system disk space usage. :return: :class:`system.Space <system.Space>` object :rtype: system.Space """ schema = SpaceSchema() resp = self.service.get(self.base + 'space/') return self.service.decode(schema, resp)
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser( description='Validates dtFabric format definitions.') argument_parser.add_argument( 'source', nargs='?', action='store', metavar='PATH', default=None, help=( 'path of the file or directory containing the dtFabric format ' 'definitions.')) options = argument_parser.parse_args() if not options.source: print('Source value is missing.') print('') argument_parser.print_help() print('') return False if not os.path.exists(options.source): print('No such file: {0:s}'.format(options.source)) print('') return False logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(message)s') source_is_directory = os.path.isdir(options.source) validator = DefinitionsValidator() if source_is_directory: source_description = os.path.join(options.source, '*.yaml') else: source_description = options.source print('Validating dtFabric definitions in: {0:s}'.format(source_description)) if source_is_directory: result = validator.CheckDirectory(options.source) else: result = validator.CheckFile(options.source) if not result: print('FAILURE') else: print('SUCCESS') return result
def function[Main, parameter[]]: constant[The main program function. Returns: bool: True if successful or False if not. ] variable[argument_parser] assign[=] call[name[argparse].ArgumentParser, parameter[]] call[name[argument_parser].add_argument, parameter[constant[source]]] variable[options] assign[=] call[name[argument_parser].parse_args, parameter[]] if <ast.UnaryOp object at 0x7da1b0fc68f0> begin[:] call[name[print], parameter[constant[Source value is missing.]]] call[name[print], parameter[constant[]]] call[name[argument_parser].print_help, parameter[]] call[name[print], parameter[constant[]]] return[constant[False]] if <ast.UnaryOp object at 0x7da1b0ff0220> begin[:] call[name[print], parameter[call[constant[No such file: {0:s}].format, parameter[name[options].source]]]] call[name[print], parameter[constant[]]] return[constant[False]] call[name[logging].basicConfig, parameter[]] variable[source_is_directory] assign[=] call[name[os].path.isdir, parameter[name[options].source]] variable[validator] assign[=] call[name[DefinitionsValidator], parameter[]] if name[source_is_directory] begin[:] variable[source_description] assign[=] call[name[os].path.join, parameter[name[options].source, constant[*.yaml]]] call[name[print], parameter[call[constant[Validating dtFabric definitions in: {0:s}].format, parameter[name[source_description]]]]] if name[source_is_directory] begin[:] variable[result] assign[=] call[name[validator].CheckDirectory, parameter[name[options].source]] if <ast.UnaryOp object at 0x7da1b0d1e860> begin[:] call[name[print], parameter[constant[FAILURE]]] return[name[result]]
keyword[def] identifier[Main] (): literal[string] identifier[argument_parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = literal[string] ) identifier[argument_parser] . identifier[add_argument] ( literal[string] , identifier[nargs] = literal[string] , identifier[action] = literal[string] , identifier[metavar] = literal[string] , identifier[default] = keyword[None] , identifier[help] =( literal[string] literal[string] )) identifier[options] = identifier[argument_parser] . identifier[parse_args] () keyword[if] keyword[not] identifier[options] . identifier[source] : identifier[print] ( literal[string] ) identifier[print] ( literal[string] ) identifier[argument_parser] . identifier[print_help] () identifier[print] ( literal[string] ) keyword[return] keyword[False] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[options] . identifier[source] ): identifier[print] ( literal[string] . identifier[format] ( identifier[options] . identifier[source] )) identifier[print] ( literal[string] ) keyword[return] keyword[False] identifier[logging] . identifier[basicConfig] ( identifier[level] = identifier[logging] . identifier[INFO] , identifier[format] = literal[string] ) identifier[source_is_directory] = identifier[os] . identifier[path] . identifier[isdir] ( identifier[options] . identifier[source] ) identifier[validator] = identifier[DefinitionsValidator] () keyword[if] identifier[source_is_directory] : identifier[source_description] = identifier[os] . identifier[path] . identifier[join] ( identifier[options] . identifier[source] , literal[string] ) keyword[else] : identifier[source_description] = identifier[options] . identifier[source] identifier[print] ( literal[string] . identifier[format] ( identifier[source_description] )) keyword[if] identifier[source_is_directory] : identifier[result] = identifier[validator] . identifier[CheckDirectory] ( identifier[options] . identifier[source] ) keyword[else] : identifier[result] = identifier[validator] . identifier[CheckFile] ( identifier[options] . identifier[source] ) keyword[if] keyword[not] identifier[result] : identifier[print] ( literal[string] ) keyword[else] : identifier[print] ( literal[string] ) keyword[return] identifier[result]
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description='Validates dtFabric format definitions.') argument_parser.add_argument('source', nargs='?', action='store', metavar='PATH', default=None, help='path of the file or directory containing the dtFabric format definitions.') options = argument_parser.parse_args() if not options.source: print('Source value is missing.') print('') argument_parser.print_help() print('') return False # depends on [control=['if'], data=[]] if not os.path.exists(options.source): print('No such file: {0:s}'.format(options.source)) print('') return False # depends on [control=['if'], data=[]] logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s') source_is_directory = os.path.isdir(options.source) validator = DefinitionsValidator() if source_is_directory: source_description = os.path.join(options.source, '*.yaml') # depends on [control=['if'], data=[]] else: source_description = options.source print('Validating dtFabric definitions in: {0:s}'.format(source_description)) if source_is_directory: result = validator.CheckDirectory(options.source) # depends on [control=['if'], data=[]] else: result = validator.CheckFile(options.source) if not result: print('FAILURE') # depends on [control=['if'], data=[]] else: print('SUCCESS') return result
def get_data_path(self, filename, env_prefix=None): """ Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note: WTF_DATA_MANAGER is a provided global instance of DataManager """ if env_prefix == None: target_file = filename else: target_file = os.path.join(env_prefix, filename) if os.path.exists(os.path.join(self._data_path, target_file)): return os.path.join(self._data_path, target_file) else: raise DataNotFoundError( u("Cannot find data file: {0}").format(target_file))
def function[get_data_path, parameter[self, filename, env_prefix]]: constant[ Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note: WTF_DATA_MANAGER is a provided global instance of DataManager ] if compare[name[env_prefix] equal[==] constant[None]] begin[:] variable[target_file] assign[=] name[filename] if call[name[os].path.exists, parameter[call[name[os].path.join, parameter[name[self]._data_path, name[target_file]]]]] begin[:] return[call[name[os].path.join, parameter[name[self]._data_path, name[target_file]]]]
keyword[def] identifier[get_data_path] ( identifier[self] , identifier[filename] , identifier[env_prefix] = keyword[None] ): literal[string] keyword[if] identifier[env_prefix] == keyword[None] : identifier[target_file] = identifier[filename] keyword[else] : identifier[target_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[env_prefix] , identifier[filename] ) keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[_data_path] , identifier[target_file] )): keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[_data_path] , identifier[target_file] ) keyword[else] : keyword[raise] identifier[DataNotFoundError] ( identifier[u] ( literal[string] ). identifier[format] ( identifier[target_file] ))
def get_data_path(self, filename, env_prefix=None): """ Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note: WTF_DATA_MANAGER is a provided global instance of DataManager """ if env_prefix == None: target_file = filename # depends on [control=['if'], data=[]] else: target_file = os.path.join(env_prefix, filename) if os.path.exists(os.path.join(self._data_path, target_file)): return os.path.join(self._data_path, target_file) # depends on [control=['if'], data=[]] else: raise DataNotFoundError(u('Cannot find data file: {0}').format(target_file))
def _read_country_names(self, countries_file=None): """Read list of countries from specified country file or default file.""" if not countries_file: countries_file = os.path.join(os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT) with open(countries_file) as f: countries_json = f.read() return json.loads(countries_json)
def function[_read_country_names, parameter[self, countries_file]]: constant[Read list of countries from specified country file or default file.] if <ast.UnaryOp object at 0x7da18dc052d0> begin[:] variable[countries_file] assign[=] call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[name[__file__]]], name[self].COUNTRY_FILE_DEFAULT]] with call[name[open], parameter[name[countries_file]]] begin[:] variable[countries_json] assign[=] call[name[f].read, parameter[]] return[call[name[json].loads, parameter[name[countries_json]]]]
keyword[def] identifier[_read_country_names] ( identifier[self] , identifier[countries_file] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[countries_file] : identifier[countries_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ), identifier[self] . identifier[COUNTRY_FILE_DEFAULT] ) keyword[with] identifier[open] ( identifier[countries_file] ) keyword[as] identifier[f] : identifier[countries_json] = identifier[f] . identifier[read] () keyword[return] identifier[json] . identifier[loads] ( identifier[countries_json] )
def _read_country_names(self, countries_file=None): """Read list of countries from specified country file or default file.""" if not countries_file: countries_file = os.path.join(os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT) # depends on [control=['if'], data=[]] with open(countries_file) as f: countries_json = f.read() # depends on [control=['with'], data=['f']] return json.loads(countries_json)
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: add_subscriptions /hosts/<id>/add_subscriptions remove_subscriptions /hosts/<id>/remove_subscriptions ``super`` is called otherwise. """ if which in ( 'add_subscriptions', 'remove_subscriptions'): return '{0}/{1}'.format( super(HostSubscription, self).path(which='base'), which ) return super(HostSubscription, self).path(which)
def function[path, parameter[self, which]]: constant[Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: add_subscriptions /hosts/<id>/add_subscriptions remove_subscriptions /hosts/<id>/remove_subscriptions ``super`` is called otherwise. ] if compare[name[which] in tuple[[<ast.Constant object at 0x7da20cabfb20>, <ast.Constant object at 0x7da20cabf5e0>]]] begin[:] return[call[constant[{0}/{1}].format, parameter[call[call[name[super], parameter[name[HostSubscription], name[self]]].path, parameter[]], name[which]]]] return[call[call[name[super], parameter[name[HostSubscription], name[self]]].path, parameter[name[which]]]]
keyword[def] identifier[path] ( identifier[self] , identifier[which] = keyword[None] ): literal[string] keyword[if] identifier[which] keyword[in] ( literal[string] , literal[string] ): keyword[return] literal[string] . identifier[format] ( identifier[super] ( identifier[HostSubscription] , identifier[self] ). identifier[path] ( identifier[which] = literal[string] ), identifier[which] ) keyword[return] identifier[super] ( identifier[HostSubscription] , identifier[self] ). identifier[path] ( identifier[which] )
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: add_subscriptions /hosts/<id>/add_subscriptions remove_subscriptions /hosts/<id>/remove_subscriptions ``super`` is called otherwise. """ if which in ('add_subscriptions', 'remove_subscriptions'): return '{0}/{1}'.format(super(HostSubscription, self).path(which='base'), which) # depends on [control=['if'], data=['which']] return super(HostSubscription, self).path(which)
def add_children(self, children): """Adds new children nodes after filtering for duplicates Args: children (list): list of OmniTree nodes to add as children """ self._children += [c for c in children if c not in self._children]
def function[add_children, parameter[self, children]]: constant[Adds new children nodes after filtering for duplicates Args: children (list): list of OmniTree nodes to add as children ] <ast.AugAssign object at 0x7da1b14d0460>
keyword[def] identifier[add_children] ( identifier[self] , identifier[children] ): literal[string] identifier[self] . identifier[_children] +=[ identifier[c] keyword[for] identifier[c] keyword[in] identifier[children] keyword[if] identifier[c] keyword[not] keyword[in] identifier[self] . identifier[_children] ]
def add_children(self, children): """Adds new children nodes after filtering for duplicates Args: children (list): list of OmniTree nodes to add as children """ self._children += [c for c in children if c not in self._children]
def _every(times, step_size, index): """ Given a loop over batches of an iterable and an operation that should be performed every few elements. Determine whether the operation should be called for the current index. """ current = index * step_size step = current // times * times reached = current >= step overshot = current >= step + step_size return current and reached and not overshot
def function[_every, parameter[times, step_size, index]]: constant[ Given a loop over batches of an iterable and an operation that should be performed every few elements. Determine whether the operation should be called for the current index. ] variable[current] assign[=] binary_operation[name[index] * name[step_size]] variable[step] assign[=] binary_operation[binary_operation[name[current] <ast.FloorDiv object at 0x7da2590d6bc0> name[times]] * name[times]] variable[reached] assign[=] compare[name[current] greater_or_equal[>=] name[step]] variable[overshot] assign[=] compare[name[current] greater_or_equal[>=] binary_operation[name[step] + name[step_size]]] return[<ast.BoolOp object at 0x7da18ede43a0>]
keyword[def] identifier[_every] ( identifier[times] , identifier[step_size] , identifier[index] ): literal[string] identifier[current] = identifier[index] * identifier[step_size] identifier[step] = identifier[current] // identifier[times] * identifier[times] identifier[reached] = identifier[current] >= identifier[step] identifier[overshot] = identifier[current] >= identifier[step] + identifier[step_size] keyword[return] identifier[current] keyword[and] identifier[reached] keyword[and] keyword[not] identifier[overshot]
def _every(times, step_size, index): """ Given a loop over batches of an iterable and an operation that should be performed every few elements. Determine whether the operation should be called for the current index. """ current = index * step_size step = current // times * times reached = current >= step overshot = current >= step + step_size return current and reached and (not overshot)
def target_partname(self): """ |PackURI| instance containing partname targeted by this relationship. Raises ``ValueError`` on reference if target_mode is ``'External'``. Use :attr:`target_mode` to check before referencing. """ if self.is_external: msg = ('target_partname attribute on Relationship is undefined w' 'here TargetMode == "External"') raise ValueError(msg) # lazy-load _target_partname attribute if not hasattr(self, '_target_partname'): self._target_partname = PackURI.from_rel_ref(self._baseURI, self.target_ref) return self._target_partname
def function[target_partname, parameter[self]]: constant[ |PackURI| instance containing partname targeted by this relationship. Raises ``ValueError`` on reference if target_mode is ``'External'``. Use :attr:`target_mode` to check before referencing. ] if name[self].is_external begin[:] variable[msg] assign[=] constant[target_partname attribute on Relationship is undefined where TargetMode == "External"] <ast.Raise object at 0x7da18eb56800> if <ast.UnaryOp object at 0x7da18eb55de0> begin[:] name[self]._target_partname assign[=] call[name[PackURI].from_rel_ref, parameter[name[self]._baseURI, name[self].target_ref]] return[name[self]._target_partname]
keyword[def] identifier[target_partname] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[is_external] : identifier[msg] =( literal[string] literal[string] ) keyword[raise] identifier[ValueError] ( identifier[msg] ) keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ): identifier[self] . identifier[_target_partname] = identifier[PackURI] . identifier[from_rel_ref] ( identifier[self] . identifier[_baseURI] , identifier[self] . identifier[target_ref] ) keyword[return] identifier[self] . identifier[_target_partname]
def target_partname(self): """ |PackURI| instance containing partname targeted by this relationship. Raises ``ValueError`` on reference if target_mode is ``'External'``. Use :attr:`target_mode` to check before referencing. """ if self.is_external: msg = 'target_partname attribute on Relationship is undefined where TargetMode == "External"' raise ValueError(msg) # depends on [control=['if'], data=[]] # lazy-load _target_partname attribute if not hasattr(self, '_target_partname'): self._target_partname = PackURI.from_rel_ref(self._baseURI, self.target_ref) # depends on [control=['if'], data=[]] return self._target_partname
def get_causal_out_edges( graph: BELGraph, nbunch: Union[BaseEntity, Iterable[BaseEntity]], ) -> Set[Tuple[BaseEntity, BaseEntity]]: """Get the out-edges to the given node that are causal. :return: A set of (source, target) pairs where the source is the given node """ return { (u, v) for u, v, k, d in graph.out_edges(nbunch, keys=True, data=True) if is_causal_relation(graph, u, v, k, d) }
def function[get_causal_out_edges, parameter[graph, nbunch]]: constant[Get the out-edges to the given node that are causal. :return: A set of (source, target) pairs where the source is the given node ] return[<ast.SetComp object at 0x7da1afeb4bb0>]
keyword[def] identifier[get_causal_out_edges] ( identifier[graph] : identifier[BELGraph] , identifier[nbunch] : identifier[Union] [ identifier[BaseEntity] , identifier[Iterable] [ identifier[BaseEntity] ]], )-> identifier[Set] [ identifier[Tuple] [ identifier[BaseEntity] , identifier[BaseEntity] ]]: literal[string] keyword[return] { ( identifier[u] , identifier[v] ) keyword[for] identifier[u] , identifier[v] , identifier[k] , identifier[d] keyword[in] identifier[graph] . identifier[out_edges] ( identifier[nbunch] , identifier[keys] = keyword[True] , identifier[data] = keyword[True] ) keyword[if] identifier[is_causal_relation] ( identifier[graph] , identifier[u] , identifier[v] , identifier[k] , identifier[d] ) }
def get_causal_out_edges(graph: BELGraph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]) -> Set[Tuple[BaseEntity, BaseEntity]]: """Get the out-edges to the given node that are causal. :return: A set of (source, target) pairs where the source is the given node """ return {(u, v) for (u, v, k, d) in graph.out_edges(nbunch, keys=True, data=True) if is_causal_relation(graph, u, v, k, d)}
def get_fermi_interextrapolated(self, c, T, warn=True, c_ref=1e10, **kwargs): """ Similar to get_fermi except that when get_fermi fails to converge, an interpolated or extrapolated fermi (depending on c) is returned with the assumption that the fermi level changes linearly with log(abs(c)). Args: c (float): doping concentration in 1/cm3. c<0 represents n-type doping and c>0 p-type doping (i.e. majority carriers are holes) T (float): absolute temperature in Kelvin warn (bool): whether to warn for the first time when no fermi can be found. c_ref (float): a doping concentration where get_fermi returns a value without error for both c_ref and -c_ref **kwargs: see keyword arguments of the get_fermi function Returns (float): the fermi level that is possibly interapolated or extrapolated and must be used with caution. """ try: return self.get_fermi(c, T, **kwargs) except ValueError as e: if warn: warnings.warn(str(e)) if abs(c) < c_ref: if abs(c) < 1e-10: c = 1e-10 # max(10, ) is to avoid log(0<x<1) and log(1+x) both of which are slow f2 = self.get_fermi_interextrapolated(max(10, abs(c) * 10.), T, warn=False, **kwargs) f1 = self.get_fermi_interextrapolated(-max(10, abs(c) * 10.), T, warn=False, **kwargs) c2 = np.log(abs(1 + self.get_doping(f2, T))) c1 = -np.log(abs(1 + self.get_doping(f1, T))) slope = (f2 - f1) / (c2 - c1) return f2 + slope * (np.sign(c) * np.log(abs(1 + c)) - c2) else: f_ref = self.get_fermi_interextrapolated(np.sign(c) * c_ref, T, warn=False, **kwargs) f_new = self.get_fermi_interextrapolated(c / 10., T, warn=False, **kwargs) clog = np.sign(c) * np.log(abs(c)) c_newlog = np.sign(c) * np.log(abs(self.get_doping(f_new, T))) slope = (f_new - f_ref) / (c_newlog - np.sign(c) * 10.) return f_new + slope * (clog - c_newlog)
def function[get_fermi_interextrapolated, parameter[self, c, T, warn, c_ref]]: constant[ Similar to get_fermi except that when get_fermi fails to converge, an interpolated or extrapolated fermi (depending on c) is returned with the assumption that the fermi level changes linearly with log(abs(c)). Args: c (float): doping concentration in 1/cm3. c<0 represents n-type doping and c>0 p-type doping (i.e. majority carriers are holes) T (float): absolute temperature in Kelvin warn (bool): whether to warn for the first time when no fermi can be found. c_ref (float): a doping concentration where get_fermi returns a value without error for both c_ref and -c_ref **kwargs: see keyword arguments of the get_fermi function Returns (float): the fermi level that is possibly interapolated or extrapolated and must be used with caution. ] <ast.Try object at 0x7da18dc04b20>
keyword[def] identifier[get_fermi_interextrapolated] ( identifier[self] , identifier[c] , identifier[T] , identifier[warn] = keyword[True] , identifier[c_ref] = literal[int] ,** identifier[kwargs] ): literal[string] keyword[try] : keyword[return] identifier[self] . identifier[get_fermi] ( identifier[c] , identifier[T] ,** identifier[kwargs] ) keyword[except] identifier[ValueError] keyword[as] identifier[e] : keyword[if] identifier[warn] : identifier[warnings] . identifier[warn] ( identifier[str] ( identifier[e] )) keyword[if] identifier[abs] ( identifier[c] )< identifier[c_ref] : keyword[if] identifier[abs] ( identifier[c] )< literal[int] : identifier[c] = literal[int] identifier[f2] = identifier[self] . identifier[get_fermi_interextrapolated] ( identifier[max] ( literal[int] , identifier[abs] ( identifier[c] )* literal[int] ), identifier[T] , identifier[warn] = keyword[False] ,** identifier[kwargs] ) identifier[f1] = identifier[self] . identifier[get_fermi_interextrapolated] (- identifier[max] ( literal[int] , identifier[abs] ( identifier[c] )* literal[int] ), identifier[T] , identifier[warn] = keyword[False] ,** identifier[kwargs] ) identifier[c2] = identifier[np] . identifier[log] ( identifier[abs] ( literal[int] + identifier[self] . identifier[get_doping] ( identifier[f2] , identifier[T] ))) identifier[c1] =- identifier[np] . identifier[log] ( identifier[abs] ( literal[int] + identifier[self] . identifier[get_doping] ( identifier[f1] , identifier[T] ))) identifier[slope] =( identifier[f2] - identifier[f1] )/( identifier[c2] - identifier[c1] ) keyword[return] identifier[f2] + identifier[slope] *( identifier[np] . identifier[sign] ( identifier[c] )* identifier[np] . identifier[log] ( identifier[abs] ( literal[int] + identifier[c] ))- identifier[c2] ) keyword[else] : identifier[f_ref] = identifier[self] . identifier[get_fermi_interextrapolated] ( identifier[np] . identifier[sign] ( identifier[c] )* identifier[c_ref] , identifier[T] , identifier[warn] = keyword[False] ,** identifier[kwargs] ) identifier[f_new] = identifier[self] . identifier[get_fermi_interextrapolated] ( identifier[c] / literal[int] , identifier[T] , identifier[warn] = keyword[False] ,** identifier[kwargs] ) identifier[clog] = identifier[np] . identifier[sign] ( identifier[c] )* identifier[np] . identifier[log] ( identifier[abs] ( identifier[c] )) identifier[c_newlog] = identifier[np] . identifier[sign] ( identifier[c] )* identifier[np] . identifier[log] ( identifier[abs] ( identifier[self] . identifier[get_doping] ( identifier[f_new] , identifier[T] ))) identifier[slope] =( identifier[f_new] - identifier[f_ref] )/( identifier[c_newlog] - identifier[np] . identifier[sign] ( identifier[c] )* literal[int] ) keyword[return] identifier[f_new] + identifier[slope] *( identifier[clog] - identifier[c_newlog] )
def get_fermi_interextrapolated(self, c, T, warn=True, c_ref=10000000000.0, **kwargs): """ Similar to get_fermi except that when get_fermi fails to converge, an interpolated or extrapolated fermi (depending on c) is returned with the assumption that the fermi level changes linearly with log(abs(c)). Args: c (float): doping concentration in 1/cm3. c<0 represents n-type doping and c>0 p-type doping (i.e. majority carriers are holes) T (float): absolute temperature in Kelvin warn (bool): whether to warn for the first time when no fermi can be found. c_ref (float): a doping concentration where get_fermi returns a value without error for both c_ref and -c_ref **kwargs: see keyword arguments of the get_fermi function Returns (float): the fermi level that is possibly interapolated or extrapolated and must be used with caution. """ try: return self.get_fermi(c, T, **kwargs) # depends on [control=['try'], data=[]] except ValueError as e: if warn: warnings.warn(str(e)) # depends on [control=['if'], data=[]] if abs(c) < c_ref: if abs(c) < 1e-10: c = 1e-10 # depends on [control=['if'], data=[]] # max(10, ) is to avoid log(0<x<1) and log(1+x) both of which are slow f2 = self.get_fermi_interextrapolated(max(10, abs(c) * 10.0), T, warn=False, **kwargs) f1 = self.get_fermi_interextrapolated(-max(10, abs(c) * 10.0), T, warn=False, **kwargs) c2 = np.log(abs(1 + self.get_doping(f2, T))) c1 = -np.log(abs(1 + self.get_doping(f1, T))) slope = (f2 - f1) / (c2 - c1) return f2 + slope * (np.sign(c) * np.log(abs(1 + c)) - c2) # depends on [control=['if'], data=[]] else: f_ref = self.get_fermi_interextrapolated(np.sign(c) * c_ref, T, warn=False, **kwargs) f_new = self.get_fermi_interextrapolated(c / 10.0, T, warn=False, **kwargs) clog = np.sign(c) * np.log(abs(c)) c_newlog = np.sign(c) * np.log(abs(self.get_doping(f_new, T))) slope = (f_new - f_ref) / (c_newlog - np.sign(c) * 10.0) return f_new + slope * (clog - c_newlog) # depends on [control=['except'], data=['e']]
def download_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs): # type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict] """Download multicolumn csv from url and return dictionary where keys are first column and values are dictionaries with keys from column headers and values from columns beneath Args: url (str): URL to download headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers. Defaults to 1. keycolumn (int): Number of column to be used for key. Defaults to 1. **kwargs: file_type (Optional[str]): Type of file. Defaults to inferring. delimiter (Optional[str]): Delimiter used for values in each row. Defaults to inferring. Returns: Dict[Dict]: Dictionary where keys are first column and values are dictionaries with keys from column headers and values from columns beneath """ kwargs['headers'] = headers stream = self.get_tabular_stream(url, **kwargs) output_dict = dict() headers = stream.headers key_header = headers[keycolumn - 1] for row in stream.iter(keyed=True): first_val = row[key_header] output_dict[first_val] = dict() for header in row: if header == key_header: continue else: output_dict[first_val][header] = row[header] return output_dict
def function[download_tabular_rows_as_dicts, parameter[self, url, headers, keycolumn]]: constant[Download multicolumn csv from url and return dictionary where keys are first column and values are dictionaries with keys from column headers and values from columns beneath Args: url (str): URL to download headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers. Defaults to 1. keycolumn (int): Number of column to be used for key. Defaults to 1. **kwargs: file_type (Optional[str]): Type of file. Defaults to inferring. delimiter (Optional[str]): Delimiter used for values in each row. Defaults to inferring. Returns: Dict[Dict]: Dictionary where keys are first column and values are dictionaries with keys from column headers and values from columns beneath ] call[name[kwargs]][constant[headers]] assign[=] name[headers] variable[stream] assign[=] call[name[self].get_tabular_stream, parameter[name[url]]] variable[output_dict] assign[=] call[name[dict], parameter[]] variable[headers] assign[=] name[stream].headers variable[key_header] assign[=] call[name[headers]][binary_operation[name[keycolumn] - constant[1]]] for taget[name[row]] in starred[call[name[stream].iter, parameter[]]] begin[:] variable[first_val] assign[=] call[name[row]][name[key_header]] call[name[output_dict]][name[first_val]] assign[=] call[name[dict], parameter[]] for taget[name[header]] in starred[name[row]] begin[:] if compare[name[header] equal[==] name[key_header]] begin[:] continue return[name[output_dict]]
keyword[def] identifier[download_tabular_rows_as_dicts] ( identifier[self] , identifier[url] , identifier[headers] = literal[int] , identifier[keycolumn] = literal[int] ,** identifier[kwargs] ): literal[string] identifier[kwargs] [ literal[string] ]= identifier[headers] identifier[stream] = identifier[self] . identifier[get_tabular_stream] ( identifier[url] ,** identifier[kwargs] ) identifier[output_dict] = identifier[dict] () identifier[headers] = identifier[stream] . identifier[headers] identifier[key_header] = identifier[headers] [ identifier[keycolumn] - literal[int] ] keyword[for] identifier[row] keyword[in] identifier[stream] . identifier[iter] ( identifier[keyed] = keyword[True] ): identifier[first_val] = identifier[row] [ identifier[key_header] ] identifier[output_dict] [ identifier[first_val] ]= identifier[dict] () keyword[for] identifier[header] keyword[in] identifier[row] : keyword[if] identifier[header] == identifier[key_header] : keyword[continue] keyword[else] : identifier[output_dict] [ identifier[first_val] ][ identifier[header] ]= identifier[row] [ identifier[header] ] keyword[return] identifier[output_dict]
def download_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs): # type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict] 'Download multicolumn csv from url and return dictionary where keys are first column and values are\n dictionaries with keys from column headers and values from columns beneath\n\n Args:\n url (str): URL to download\n headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers. Defaults to 1.\n keycolumn (int): Number of column to be used for key. Defaults to 1.\n **kwargs:\n file_type (Optional[str]): Type of file. Defaults to inferring.\n delimiter (Optional[str]): Delimiter used for values in each row. Defaults to inferring.\n\n Returns:\n Dict[Dict]: Dictionary where keys are first column and values are dictionaries with keys from column\n headers and values from columns beneath\n\n ' kwargs['headers'] = headers stream = self.get_tabular_stream(url, **kwargs) output_dict = dict() headers = stream.headers key_header = headers[keycolumn - 1] for row in stream.iter(keyed=True): first_val = row[key_header] output_dict[first_val] = dict() for header in row: if header == key_header: continue # depends on [control=['if'], data=[]] else: output_dict[first_val][header] = row[header] # depends on [control=['for'], data=['header']] # depends on [control=['for'], data=['row']] return output_dict
def isalive(self): '''This tests if the child process is running or not. This is non-blocking. If the child was terminated then this will read the exitstatus or signalstatus of the child. This returns True if the child process appears to be running or False if not. It can take literally SECONDS for Solaris to return the right status. ''' if self.terminated: return False if self.flag_eof: # This is for Linux, which requires the blocking form # of waitpid to get the status of a defunct process. # This is super-lame. The flag_eof would have been set # in read_nonblocking(), so this should be safe. waitpid_options = 0 else: waitpid_options = os.WNOHANG try: pid, status = os.waitpid(self.pid, waitpid_options) except OSError as e: # No child processes if e.errno == errno.ECHILD: raise PtyProcessError('isalive() encountered condition ' + 'where "terminated" is 0, but there was no child ' + 'process. Did someone else call waitpid() ' + 'on our process?') else: raise # I have to do this twice for Solaris. # I can't even believe that I figured this out... # If waitpid() returns 0 it means that no child process # wishes to report, and the value of status is undefined. if pid == 0: try: ### os.WNOHANG) # Solaris! pid, status = os.waitpid(self.pid, waitpid_options) except OSError as e: # pragma: no cover # This should never happen... if e.errno == errno.ECHILD: raise PtyProcessError('isalive() encountered condition ' + 'that should never happen. There was no child ' + 'process. Did someone else call waitpid() ' + 'on our process?') else: raise # If pid is still 0 after two calls to waitpid() then the process # really is alive. This seems to work on all platforms, except for # Irix which seems to require a blocking call on waitpid or select, # so I let read_nonblocking take care of this situation # (unfortunately, this requires waiting through the timeout). if pid == 0: return True if pid == 0: return True if os.WIFEXITED(status): self.status = status self.exitstatus = os.WEXITSTATUS(status) self.signalstatus = None self.terminated = True elif os.WIFSIGNALED(status): self.status = status self.exitstatus = None self.signalstatus = os.WTERMSIG(status) self.terminated = True elif os.WIFSTOPPED(status): raise PtyProcessError('isalive() encountered condition ' + 'where child process is stopped. This is not ' + 'supported. Is some other process attempting ' + 'job control with our child pid?') return False
def function[isalive, parameter[self]]: constant[This tests if the child process is running or not. This is non-blocking. If the child was terminated then this will read the exitstatus or signalstatus of the child. This returns True if the child process appears to be running or False if not. It can take literally SECONDS for Solaris to return the right status. ] if name[self].terminated begin[:] return[constant[False]] if name[self].flag_eof begin[:] variable[waitpid_options] assign[=] constant[0] <ast.Try object at 0x7da2054a6590> if compare[name[pid] equal[==] constant[0]] begin[:] <ast.Try object at 0x7da2054a5c00> if compare[name[pid] equal[==] constant[0]] begin[:] return[constant[True]] if compare[name[pid] equal[==] constant[0]] begin[:] return[constant[True]] if call[name[os].WIFEXITED, parameter[name[status]]] begin[:] name[self].status assign[=] name[status] name[self].exitstatus assign[=] call[name[os].WEXITSTATUS, parameter[name[status]]] name[self].signalstatus assign[=] constant[None] name[self].terminated assign[=] constant[True] return[constant[False]]
keyword[def] identifier[isalive] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[terminated] : keyword[return] keyword[False] keyword[if] identifier[self] . identifier[flag_eof] : identifier[waitpid_options] = literal[int] keyword[else] : identifier[waitpid_options] = identifier[os] . identifier[WNOHANG] keyword[try] : identifier[pid] , identifier[status] = identifier[os] . identifier[waitpid] ( identifier[self] . identifier[pid] , identifier[waitpid_options] ) keyword[except] identifier[OSError] keyword[as] identifier[e] : keyword[if] identifier[e] . identifier[errno] == identifier[errno] . identifier[ECHILD] : keyword[raise] identifier[PtyProcessError] ( literal[string] + literal[string] + literal[string] + literal[string] ) keyword[else] : keyword[raise] keyword[if] identifier[pid] == literal[int] : keyword[try] : identifier[pid] , identifier[status] = identifier[os] . identifier[waitpid] ( identifier[self] . identifier[pid] , identifier[waitpid_options] ) keyword[except] identifier[OSError] keyword[as] identifier[e] : keyword[if] identifier[e] . identifier[errno] == identifier[errno] . identifier[ECHILD] : keyword[raise] identifier[PtyProcessError] ( literal[string] + literal[string] + literal[string] + literal[string] ) keyword[else] : keyword[raise] keyword[if] identifier[pid] == literal[int] : keyword[return] keyword[True] keyword[if] identifier[pid] == literal[int] : keyword[return] keyword[True] keyword[if] identifier[os] . identifier[WIFEXITED] ( identifier[status] ): identifier[self] . identifier[status] = identifier[status] identifier[self] . identifier[exitstatus] = identifier[os] . identifier[WEXITSTATUS] ( identifier[status] ) identifier[self] . identifier[signalstatus] = keyword[None] identifier[self] . identifier[terminated] = keyword[True] keyword[elif] identifier[os] . identifier[WIFSIGNALED] ( identifier[status] ): identifier[self] . identifier[status] = identifier[status] identifier[self] . identifier[exitstatus] = keyword[None] identifier[self] . identifier[signalstatus] = identifier[os] . identifier[WTERMSIG] ( identifier[status] ) identifier[self] . identifier[terminated] = keyword[True] keyword[elif] identifier[os] . identifier[WIFSTOPPED] ( identifier[status] ): keyword[raise] identifier[PtyProcessError] ( literal[string] + literal[string] + literal[string] + literal[string] ) keyword[return] keyword[False]
def isalive(self): """This tests if the child process is running or not. This is non-blocking. If the child was terminated then this will read the exitstatus or signalstatus of the child. This returns True if the child process appears to be running or False if not. It can take literally SECONDS for Solaris to return the right status. """ if self.terminated: return False # depends on [control=['if'], data=[]] if self.flag_eof: # This is for Linux, which requires the blocking form # of waitpid to get the status of a defunct process. # This is super-lame. The flag_eof would have been set # in read_nonblocking(), so this should be safe. waitpid_options = 0 # depends on [control=['if'], data=[]] else: waitpid_options = os.WNOHANG try: (pid, status) = os.waitpid(self.pid, waitpid_options) # depends on [control=['try'], data=[]] except OSError as e: # No child processes if e.errno == errno.ECHILD: raise PtyProcessError('isalive() encountered condition ' + 'where "terminated" is 0, but there was no child ' + 'process. Did someone else call waitpid() ' + 'on our process?') # depends on [control=['if'], data=[]] else: raise # depends on [control=['except'], data=['e']] # I have to do this twice for Solaris. # I can't even believe that I figured this out... # If waitpid() returns 0 it means that no child process # wishes to report, and the value of status is undefined. if pid == 0: try: ### os.WNOHANG) # Solaris! (pid, status) = os.waitpid(self.pid, waitpid_options) # depends on [control=['try'], data=[]] except OSError as e: # pragma: no cover # This should never happen... if e.errno == errno.ECHILD: raise PtyProcessError('isalive() encountered condition ' + 'that should never happen. There was no child ' + 'process. Did someone else call waitpid() ' + 'on our process?') # depends on [control=['if'], data=[]] else: raise # depends on [control=['except'], data=['e']] # If pid is still 0 after two calls to waitpid() then the process # really is alive. This seems to work on all platforms, except for # Irix which seems to require a blocking call on waitpid or select, # so I let read_nonblocking take care of this situation # (unfortunately, this requires waiting through the timeout). if pid == 0: return True # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['pid']] if pid == 0: return True # depends on [control=['if'], data=[]] if os.WIFEXITED(status): self.status = status self.exitstatus = os.WEXITSTATUS(status) self.signalstatus = None self.terminated = True # depends on [control=['if'], data=[]] elif os.WIFSIGNALED(status): self.status = status self.exitstatus = None self.signalstatus = os.WTERMSIG(status) self.terminated = True # depends on [control=['if'], data=[]] elif os.WIFSTOPPED(status): raise PtyProcessError('isalive() encountered condition ' + 'where child process is stopped. This is not ' + 'supported. Is some other process attempting ' + 'job control with our child pid?') # depends on [control=['if'], data=[]] return False
def fetchall(self): """ returns the remainder of records from the query. This is guaranteed by locking, so that no other thread can grab a few records while the set is fetched. This has the side effect that other threads may have to wait for an arbitrary long time until this query is done before they can return (obviously with None). """ self._cursorLock.acquire() recs = [] while True: rec = self.fetchone() if rec is None: break recs.append(rec) self._cursorLock.release() return recs
def function[fetchall, parameter[self]]: constant[ returns the remainder of records from the query. This is guaranteed by locking, so that no other thread can grab a few records while the set is fetched. This has the side effect that other threads may have to wait for an arbitrary long time until this query is done before they can return (obviously with None). ] call[name[self]._cursorLock.acquire, parameter[]] variable[recs] assign[=] list[[]] while constant[True] begin[:] variable[rec] assign[=] call[name[self].fetchone, parameter[]] if compare[name[rec] is constant[None]] begin[:] break call[name[recs].append, parameter[name[rec]]] call[name[self]._cursorLock.release, parameter[]] return[name[recs]]
keyword[def] identifier[fetchall] ( identifier[self] ): literal[string] identifier[self] . identifier[_cursorLock] . identifier[acquire] () identifier[recs] =[] keyword[while] keyword[True] : identifier[rec] = identifier[self] . identifier[fetchone] () keyword[if] identifier[rec] keyword[is] keyword[None] : keyword[break] identifier[recs] . identifier[append] ( identifier[rec] ) identifier[self] . identifier[_cursorLock] . identifier[release] () keyword[return] identifier[recs]
def fetchall(self): """ returns the remainder of records from the query. This is guaranteed by locking, so that no other thread can grab a few records while the set is fetched. This has the side effect that other threads may have to wait for an arbitrary long time until this query is done before they can return (obviously with None). """ self._cursorLock.acquire() recs = [] while True: rec = self.fetchone() if rec is None: break # depends on [control=['if'], data=[]] recs.append(rec) # depends on [control=['while'], data=[]] self._cursorLock.release() return recs
def load_data(self, path, *args, **kwargs): """see print instance.doc, e.g. cat=LoadFile(kind='excel') read how to use cat.load_data, exec: print (cat.doc)""" self.df = self._load(path,*args, **kwargs) self.series = self.df.iloc[:,0] print ("Success! file length: " +str(self.df.shape[0]))
def function[load_data, parameter[self, path]]: constant[see print instance.doc, e.g. cat=LoadFile(kind='excel') read how to use cat.load_data, exec: print (cat.doc)] name[self].df assign[=] call[name[self]._load, parameter[name[path], <ast.Starred object at 0x7da1b09676d0>]] name[self].series assign[=] call[name[self].df.iloc][tuple[[<ast.Slice object at 0x7da1b09675b0>, <ast.Constant object at 0x7da1b09670d0>]]] call[name[print], parameter[binary_operation[constant[Success! file length: ] + call[name[str], parameter[call[name[self].df.shape][constant[0]]]]]]]
keyword[def] identifier[load_data] ( identifier[self] , identifier[path] ,* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[self] . identifier[df] = identifier[self] . identifier[_load] ( identifier[path] ,* identifier[args] ,** identifier[kwargs] ) identifier[self] . identifier[series] = identifier[self] . identifier[df] . identifier[iloc] [:, literal[int] ] identifier[print] ( literal[string] + identifier[str] ( identifier[self] . identifier[df] . identifier[shape] [ literal[int] ]))
def load_data(self, path, *args, **kwargs): """see print instance.doc, e.g. cat=LoadFile(kind='excel') read how to use cat.load_data, exec: print (cat.doc)""" self.df = self._load(path, *args, **kwargs) self.series = self.df.iloc[:, 0] print('Success! file length: ' + str(self.df.shape[0]))
def _change_channel(self, fcid, tcid): """ 这个貌似没啥用 :params fcid, tcid: string """ url = 'https://douban.fm/j/change_channel' options = { 'fcid': fcid, 'tcid': tcid, 'area': 'system_chis' } requests.get(url, params=options, cookies=self._cookies, headers=HEADERS)
def function[_change_channel, parameter[self, fcid, tcid]]: constant[ 这个貌似没啥用 :params fcid, tcid: string ] variable[url] assign[=] constant[https://douban.fm/j/change_channel] variable[options] assign[=] dictionary[[<ast.Constant object at 0x7da18fe93400>, <ast.Constant object at 0x7da18fe92620>, <ast.Constant object at 0x7da18fe92770>], [<ast.Name object at 0x7da18fe92e30>, <ast.Name object at 0x7da18fe92f50>, <ast.Constant object at 0x7da18fe930a0>]] call[name[requests].get, parameter[name[url]]]
keyword[def] identifier[_change_channel] ( identifier[self] , identifier[fcid] , identifier[tcid] ): literal[string] identifier[url] = literal[string] identifier[options] ={ literal[string] : identifier[fcid] , literal[string] : identifier[tcid] , literal[string] : literal[string] } identifier[requests] . identifier[get] ( identifier[url] , identifier[params] = identifier[options] , identifier[cookies] = identifier[self] . identifier[_cookies] , identifier[headers] = identifier[HEADERS] )
def _change_channel(self, fcid, tcid): """ 这个貌似没啥用 :params fcid, tcid: string """ url = 'https://douban.fm/j/change_channel' options = {'fcid': fcid, 'tcid': tcid, 'area': 'system_chis'} requests.get(url, params=options, cookies=self._cookies, headers=HEADERS)
def is_modified(self): """ Returns whether list is modified or not """ if self.__modified_data__ is not None: return True for value in self.__original_data__: try: if value.is_modified(): return True except AttributeError: pass return False
def function[is_modified, parameter[self]]: constant[ Returns whether list is modified or not ] if compare[name[self].__modified_data__ is_not constant[None]] begin[:] return[constant[True]] for taget[name[value]] in starred[name[self].__original_data__] begin[:] <ast.Try object at 0x7da1b0aa3b50> return[constant[False]]
keyword[def] identifier[is_modified] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[__modified_data__] keyword[is] keyword[not] keyword[None] : keyword[return] keyword[True] keyword[for] identifier[value] keyword[in] identifier[self] . identifier[__original_data__] : keyword[try] : keyword[if] identifier[value] . identifier[is_modified] (): keyword[return] keyword[True] keyword[except] identifier[AttributeError] : keyword[pass] keyword[return] keyword[False]
def is_modified(self): """ Returns whether list is modified or not """ if self.__modified_data__ is not None: return True # depends on [control=['if'], data=[]] for value in self.__original_data__: try: if value.is_modified(): return True # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except AttributeError: pass # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['value']] return False
def remove_plugin(self, name, force=False): """ Remove an installed plugin. Args: name (string): Name of the plugin to remove. The ``:latest`` tag is optional, and is the default if omitted. force (bool): Disable the plugin before removing. This may result in issues if the plugin is in use by a container. Returns: ``True`` if successful """ url = self._url('/plugins/{0}', name) res = self._delete(url, params={'force': force}) self._raise_for_status(res) return True
def function[remove_plugin, parameter[self, name, force]]: constant[ Remove an installed plugin. Args: name (string): Name of the plugin to remove. The ``:latest`` tag is optional, and is the default if omitted. force (bool): Disable the plugin before removing. This may result in issues if the plugin is in use by a container. Returns: ``True`` if successful ] variable[url] assign[=] call[name[self]._url, parameter[constant[/plugins/{0}], name[name]]] variable[res] assign[=] call[name[self]._delete, parameter[name[url]]] call[name[self]._raise_for_status, parameter[name[res]]] return[constant[True]]
keyword[def] identifier[remove_plugin] ( identifier[self] , identifier[name] , identifier[force] = keyword[False] ): literal[string] identifier[url] = identifier[self] . identifier[_url] ( literal[string] , identifier[name] ) identifier[res] = identifier[self] . identifier[_delete] ( identifier[url] , identifier[params] ={ literal[string] : identifier[force] }) identifier[self] . identifier[_raise_for_status] ( identifier[res] ) keyword[return] keyword[True]
def remove_plugin(self, name, force=False): """ Remove an installed plugin. Args: name (string): Name of the plugin to remove. The ``:latest`` tag is optional, and is the default if omitted. force (bool): Disable the plugin before removing. This may result in issues if the plugin is in use by a container. Returns: ``True`` if successful """ url = self._url('/plugins/{0}', name) res = self._delete(url, params={'force': force}) self._raise_for_status(res) return True
def get_rendition_size(self, spec, output_scale, crop): """ Wrapper to determine the overall rendition size and cropping box Returns tuple of (size,box) """ if crop: # Use the cropping rectangle size _, _, width, height = crop else: # Use the original image size width = self._record.width height = self._record.height mode = spec.get('resize', 'fit') if mode == 'fit': return self.get_rendition_fit_size(spec, width, height, output_scale) if mode == 'fill': return self.get_rendition_fill_size(spec, width, height, output_scale) if mode == 'stretch': return self.get_rendition_stretch_size(spec, width, height, output_scale) raise ValueError("Unknown resize mode {}".format(mode))
def function[get_rendition_size, parameter[self, spec, output_scale, crop]]: constant[ Wrapper to determine the overall rendition size and cropping box Returns tuple of (size,box) ] if name[crop] begin[:] <ast.Tuple object at 0x7da1b2344100> assign[=] name[crop] variable[mode] assign[=] call[name[spec].get, parameter[constant[resize], constant[fit]]] if compare[name[mode] equal[==] constant[fit]] begin[:] return[call[name[self].get_rendition_fit_size, parameter[name[spec], name[width], name[height], name[output_scale]]]] if compare[name[mode] equal[==] constant[fill]] begin[:] return[call[name[self].get_rendition_fill_size, parameter[name[spec], name[width], name[height], name[output_scale]]]] if compare[name[mode] equal[==] constant[stretch]] begin[:] return[call[name[self].get_rendition_stretch_size, parameter[name[spec], name[width], name[height], name[output_scale]]]] <ast.Raise object at 0x7da1b2347ca0>
keyword[def] identifier[get_rendition_size] ( identifier[self] , identifier[spec] , identifier[output_scale] , identifier[crop] ): literal[string] keyword[if] identifier[crop] : identifier[_] , identifier[_] , identifier[width] , identifier[height] = identifier[crop] keyword[else] : identifier[width] = identifier[self] . identifier[_record] . identifier[width] identifier[height] = identifier[self] . identifier[_record] . identifier[height] identifier[mode] = identifier[spec] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[mode] == literal[string] : keyword[return] identifier[self] . identifier[get_rendition_fit_size] ( identifier[spec] , identifier[width] , identifier[height] , identifier[output_scale] ) keyword[if] identifier[mode] == literal[string] : keyword[return] identifier[self] . identifier[get_rendition_fill_size] ( identifier[spec] , identifier[width] , identifier[height] , identifier[output_scale] ) keyword[if] identifier[mode] == literal[string] : keyword[return] identifier[self] . identifier[get_rendition_stretch_size] ( identifier[spec] , identifier[width] , identifier[height] , identifier[output_scale] ) keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[mode] ))
def get_rendition_size(self, spec, output_scale, crop): """ Wrapper to determine the overall rendition size and cropping box Returns tuple of (size,box) """ if crop: # Use the cropping rectangle size (_, _, width, height) = crop # depends on [control=['if'], data=[]] else: # Use the original image size width = self._record.width height = self._record.height mode = spec.get('resize', 'fit') if mode == 'fit': return self.get_rendition_fit_size(spec, width, height, output_scale) # depends on [control=['if'], data=[]] if mode == 'fill': return self.get_rendition_fill_size(spec, width, height, output_scale) # depends on [control=['if'], data=[]] if mode == 'stretch': return self.get_rendition_stretch_size(spec, width, height, output_scale) # depends on [control=['if'], data=[]] raise ValueError('Unknown resize mode {}'.format(mode))
def get_artist(self): """ :returns: the :mod:`Artist <deezer.resources.Artist>` of the resource :raises AssertionError: if the object is not album or track """ # pylint: disable=E1101 assert isinstance(self, (Album, Track)) return self.client.get_artist(self.artist.id)
def function[get_artist, parameter[self]]: constant[ :returns: the :mod:`Artist <deezer.resources.Artist>` of the resource :raises AssertionError: if the object is not album or track ] assert[call[name[isinstance], parameter[name[self], tuple[[<ast.Name object at 0x7da1b11a3940>, <ast.Name object at 0x7da1b11a2200>]]]]] return[call[name[self].client.get_artist, parameter[name[self].artist.id]]]
keyword[def] identifier[get_artist] ( identifier[self] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[self] ,( identifier[Album] , identifier[Track] )) keyword[return] identifier[self] . identifier[client] . identifier[get_artist] ( identifier[self] . identifier[artist] . identifier[id] )
def get_artist(self): """ :returns: the :mod:`Artist <deezer.resources.Artist>` of the resource :raises AssertionError: if the object is not album or track """ # pylint: disable=E1101 assert isinstance(self, (Album, Track)) return self.client.get_artist(self.artist.id)
def fit(self, X, y, sample_weight=None): """ Fit a binary classifier with sample weights to data. Note ---- Examples at each sample are accepted with probability = weight/Z, where Z = max(weight) + extra_rej_const. Larger values for extra_rej_const ensure that no example gets selected in every single sample, but results in smaller sample sizes as more examples are rejected. Parameters ---------- X : array (n_samples, n_features) Data on which to fit the model. y : array (n_samples,) or (n_samples, 1) Class of each observation. sample_weight : array (n_samples,) or (n_samples, 1) Weights indicating how important is each observation in the loss function. """ assert self.extra_rej_const >= 0 if sample_weight is None: sample_weight = np.ones(y.shape[0]) else: if isinstance(sample_weight, list): sample_weight = np.array(sample_weight) if len(sample_weight.shape): sample_weight = sample_weight.reshape(-1) assert sample_weight.shape[0] == X.shape[0] assert sample_weight.min() > 0 Z = sample_weight.max() + self.extra_rej_const sample_weight = sample_weight / Z # sample weight is now acceptance prob self.classifiers = [deepcopy(self.base_classifier) for c in range(self.n_samples)] ### Note: don't parallelize random number generation, as it's not always thread-safe take_all = np.random.random(size = (self.n_samples, X.shape[0])) Parallel(n_jobs=self.njobs, verbose=0, require="sharedmem")(delayed(self._fit)(c, take_all, X, y, sample_weight) for c in range(self.n_samples)) return self
def function[fit, parameter[self, X, y, sample_weight]]: constant[ Fit a binary classifier with sample weights to data. Note ---- Examples at each sample are accepted with probability = weight/Z, where Z = max(weight) + extra_rej_const. Larger values for extra_rej_const ensure that no example gets selected in every single sample, but results in smaller sample sizes as more examples are rejected. Parameters ---------- X : array (n_samples, n_features) Data on which to fit the model. y : array (n_samples,) or (n_samples, 1) Class of each observation. sample_weight : array (n_samples,) or (n_samples, 1) Weights indicating how important is each observation in the loss function. ] assert[compare[name[self].extra_rej_const greater_or_equal[>=] constant[0]]] if compare[name[sample_weight] is constant[None]] begin[:] variable[sample_weight] assign[=] call[name[np].ones, parameter[call[name[y].shape][constant[0]]]] assert[compare[call[name[sample_weight].shape][constant[0]] equal[==] call[name[X].shape][constant[0]]]] assert[compare[call[name[sample_weight].min, parameter[]] greater[>] constant[0]]] variable[Z] assign[=] binary_operation[call[name[sample_weight].max, parameter[]] + name[self].extra_rej_const] variable[sample_weight] assign[=] binary_operation[name[sample_weight] / name[Z]] name[self].classifiers assign[=] <ast.ListComp object at 0x7da207f03a00> variable[take_all] assign[=] call[name[np].random.random, parameter[]] call[call[name[Parallel], parameter[]], parameter[<ast.GeneratorExp object at 0x7da18bccba90>]] return[name[self]]
keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[y] , identifier[sample_weight] = keyword[None] ): literal[string] keyword[assert] identifier[self] . identifier[extra_rej_const] >= literal[int] keyword[if] identifier[sample_weight] keyword[is] keyword[None] : identifier[sample_weight] = identifier[np] . identifier[ones] ( identifier[y] . identifier[shape] [ literal[int] ]) keyword[else] : keyword[if] identifier[isinstance] ( identifier[sample_weight] , identifier[list] ): identifier[sample_weight] = identifier[np] . identifier[array] ( identifier[sample_weight] ) keyword[if] identifier[len] ( identifier[sample_weight] . identifier[shape] ): identifier[sample_weight] = identifier[sample_weight] . identifier[reshape] (- literal[int] ) keyword[assert] identifier[sample_weight] . identifier[shape] [ literal[int] ]== identifier[X] . identifier[shape] [ literal[int] ] keyword[assert] identifier[sample_weight] . identifier[min] ()> literal[int] identifier[Z] = identifier[sample_weight] . identifier[max] ()+ identifier[self] . identifier[extra_rej_const] identifier[sample_weight] = identifier[sample_weight] / identifier[Z] identifier[self] . identifier[classifiers] =[ identifier[deepcopy] ( identifier[self] . identifier[base_classifier] ) keyword[for] identifier[c] keyword[in] identifier[range] ( identifier[self] . identifier[n_samples] )] identifier[take_all] = identifier[np] . identifier[random] . identifier[random] ( identifier[size] =( identifier[self] . identifier[n_samples] , identifier[X] . identifier[shape] [ literal[int] ])) identifier[Parallel] ( identifier[n_jobs] = identifier[self] . identifier[njobs] , identifier[verbose] = literal[int] , identifier[require] = literal[string] )( identifier[delayed] ( identifier[self] . identifier[_fit] )( identifier[c] , identifier[take_all] , identifier[X] , identifier[y] , identifier[sample_weight] ) keyword[for] identifier[c] keyword[in] identifier[range] ( identifier[self] . identifier[n_samples] )) keyword[return] identifier[self]
def fit(self, X, y, sample_weight=None): """ Fit a binary classifier with sample weights to data. Note ---- Examples at each sample are accepted with probability = weight/Z, where Z = max(weight) + extra_rej_const. Larger values for extra_rej_const ensure that no example gets selected in every single sample, but results in smaller sample sizes as more examples are rejected. Parameters ---------- X : array (n_samples, n_features) Data on which to fit the model. y : array (n_samples,) or (n_samples, 1) Class of each observation. sample_weight : array (n_samples,) or (n_samples, 1) Weights indicating how important is each observation in the loss function. """ assert self.extra_rej_const >= 0 if sample_weight is None: sample_weight = np.ones(y.shape[0]) # depends on [control=['if'], data=['sample_weight']] else: if isinstance(sample_weight, list): sample_weight = np.array(sample_weight) # depends on [control=['if'], data=[]] if len(sample_weight.shape): sample_weight = sample_weight.reshape(-1) # depends on [control=['if'], data=[]] assert sample_weight.shape[0] == X.shape[0] assert sample_weight.min() > 0 Z = sample_weight.max() + self.extra_rej_const sample_weight = sample_weight / Z # sample weight is now acceptance prob self.classifiers = [deepcopy(self.base_classifier) for c in range(self.n_samples)] ### Note: don't parallelize random number generation, as it's not always thread-safe take_all = np.random.random(size=(self.n_samples, X.shape[0])) Parallel(n_jobs=self.njobs, verbose=0, require='sharedmem')((delayed(self._fit)(c, take_all, X, y, sample_weight) for c in range(self.n_samples))) return self
def get_handler(progname, address=None, proto=None, facility=None, fmt=None, datefmt=None, **_): """Helper function to create a Syslog handler. See `ulogger.syslog.SyslogHandlerBuilder` for arguments and supported keyword arguments. Returns: (obj): Instance of `logging.SysLogHandler` """ builder = SyslogHandlerBuilder( progname, address=address, proto=proto, facility=facility, fmt=fmt, datefmt=datefmt) return builder.get_handler()
def function[get_handler, parameter[progname, address, proto, facility, fmt, datefmt]]: constant[Helper function to create a Syslog handler. See `ulogger.syslog.SyslogHandlerBuilder` for arguments and supported keyword arguments. Returns: (obj): Instance of `logging.SysLogHandler` ] variable[builder] assign[=] call[name[SyslogHandlerBuilder], parameter[name[progname]]] return[call[name[builder].get_handler, parameter[]]]
keyword[def] identifier[get_handler] ( identifier[progname] , identifier[address] = keyword[None] , identifier[proto] = keyword[None] , identifier[facility] = keyword[None] , identifier[fmt] = keyword[None] , identifier[datefmt] = keyword[None] ,** identifier[_] ): literal[string] identifier[builder] = identifier[SyslogHandlerBuilder] ( identifier[progname] , identifier[address] = identifier[address] , identifier[proto] = identifier[proto] , identifier[facility] = identifier[facility] , identifier[fmt] = identifier[fmt] , identifier[datefmt] = identifier[datefmt] ) keyword[return] identifier[builder] . identifier[get_handler] ()
def get_handler(progname, address=None, proto=None, facility=None, fmt=None, datefmt=None, **_): """Helper function to create a Syslog handler. See `ulogger.syslog.SyslogHandlerBuilder` for arguments and supported keyword arguments. Returns: (obj): Instance of `logging.SysLogHandler` """ builder = SyslogHandlerBuilder(progname, address=address, proto=proto, facility=facility, fmt=fmt, datefmt=datefmt) return builder.get_handler()
def _add_y(self, variable, prior=None, family='gaussian', link=None, *args, **kwargs): '''Add a dependent (or outcome) variable to the model. Args: variable (str): the name of the dataset column containing the y values. prior (Prior, int, float, str): Optional specification of prior. Can be an instance of class Prior, a numeric value, or a string describing the width. In the numeric case, the distribution specified in the defaults will be used, and the passed value will be used to scale the appropriate variance parameter. For strings (e.g., 'wide', 'narrow', 'medium', or 'superwide'), predefined values will be used. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. args, kwargs: Optional positional and keyword arguments to pass onto Term initializer. ''' if isinstance(family, string_types): family = self.default_priors.get(family=family) self.family = family # Override family's link if another is explicitly passed if link is not None: self.family.link = link if prior is None: prior = self.family.prior # implement default Uniform [0, sd(Y)] prior for residual SD if self.family.name == 'gaussian': prior.update(sd=Prior('Uniform', lower=0, upper=self.clean_data[variable].std())) data = kwargs.pop('data', self.clean_data[variable]) term = Term(variable, data, prior=prior, *args, **kwargs) self.y = term self.built = False
def function[_add_y, parameter[self, variable, prior, family, link]]: constant[Add a dependent (or outcome) variable to the model. Args: variable (str): the name of the dataset column containing the y values. prior (Prior, int, float, str): Optional specification of prior. Can be an instance of class Prior, a numeric value, or a string describing the width. In the numeric case, the distribution specified in the defaults will be used, and the passed value will be used to scale the appropriate variance parameter. For strings (e.g., 'wide', 'narrow', 'medium', or 'superwide'), predefined values will be used. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. args, kwargs: Optional positional and keyword arguments to pass onto Term initializer. ] if call[name[isinstance], parameter[name[family], name[string_types]]] begin[:] variable[family] assign[=] call[name[self].default_priors.get, parameter[]] name[self].family assign[=] name[family] if compare[name[link] is_not constant[None]] begin[:] name[self].family.link assign[=] name[link] if compare[name[prior] is constant[None]] begin[:] variable[prior] assign[=] name[self].family.prior if compare[name[self].family.name equal[==] constant[gaussian]] begin[:] call[name[prior].update, parameter[]] variable[data] assign[=] call[name[kwargs].pop, parameter[constant[data], call[name[self].clean_data][name[variable]]]] variable[term] assign[=] call[name[Term], parameter[name[variable], name[data], <ast.Starred object at 0x7da1b1633cd0>]] name[self].y assign[=] name[term] name[self].built assign[=] constant[False]
keyword[def] identifier[_add_y] ( identifier[self] , identifier[variable] , identifier[prior] = keyword[None] , identifier[family] = literal[string] , identifier[link] = keyword[None] ,* identifier[args] , ** identifier[kwargs] ): literal[string] keyword[if] identifier[isinstance] ( identifier[family] , identifier[string_types] ): identifier[family] = identifier[self] . identifier[default_priors] . identifier[get] ( identifier[family] = identifier[family] ) identifier[self] . identifier[family] = identifier[family] keyword[if] identifier[link] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[family] . identifier[link] = identifier[link] keyword[if] identifier[prior] keyword[is] keyword[None] : identifier[prior] = identifier[self] . identifier[family] . identifier[prior] keyword[if] identifier[self] . identifier[family] . identifier[name] == literal[string] : identifier[prior] . identifier[update] ( identifier[sd] = identifier[Prior] ( literal[string] , identifier[lower] = literal[int] , identifier[upper] = identifier[self] . identifier[clean_data] [ identifier[variable] ]. identifier[std] ())) identifier[data] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[clean_data] [ identifier[variable] ]) identifier[term] = identifier[Term] ( identifier[variable] , identifier[data] , identifier[prior] = identifier[prior] ,* identifier[args] ,** identifier[kwargs] ) identifier[self] . identifier[y] = identifier[term] identifier[self] . identifier[built] = keyword[False]
def _add_y(self, variable, prior=None, family='gaussian', link=None, *args, **kwargs): """Add a dependent (or outcome) variable to the model. Args: variable (str): the name of the dataset column containing the y values. prior (Prior, int, float, str): Optional specification of prior. Can be an instance of class Prior, a numeric value, or a string describing the width. In the numeric case, the distribution specified in the defaults will be used, and the passed value will be used to scale the appropriate variance parameter. For strings (e.g., 'wide', 'narrow', 'medium', or 'superwide'), predefined values will be used. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. args, kwargs: Optional positional and keyword arguments to pass onto Term initializer. """ if isinstance(family, string_types): family = self.default_priors.get(family=family) # depends on [control=['if'], data=[]] self.family = family # Override family's link if another is explicitly passed if link is not None: self.family.link = link # depends on [control=['if'], data=['link']] if prior is None: prior = self.family.prior # depends on [control=['if'], data=['prior']] # implement default Uniform [0, sd(Y)] prior for residual SD if self.family.name == 'gaussian': prior.update(sd=Prior('Uniform', lower=0, upper=self.clean_data[variable].std())) # depends on [control=['if'], data=[]] data = kwargs.pop('data', self.clean_data[variable]) term = Term(variable, data, *args, prior=prior, **kwargs) self.y = term self.built = False
def get_parallel_regions_block(batch): """CWL target to retrieve block group of callable regions for parallelization. Uses blocking to handle multicore runs. """ samples = [utils.to_single_data(d) for d in batch] regions = _get_parallel_regions(samples[0]) out = [] # Currently don't have core information here so aim for about 10 items per partition n = 10 for region_block in tz.partition_all(n, regions): out.append({"region_block": ["%s:%s-%s" % (c, s, e) for c, s, e in region_block]}) return out
def function[get_parallel_regions_block, parameter[batch]]: constant[CWL target to retrieve block group of callable regions for parallelization. Uses blocking to handle multicore runs. ] variable[samples] assign[=] <ast.ListComp object at 0x7da1b1884670> variable[regions] assign[=] call[name[_get_parallel_regions], parameter[call[name[samples]][constant[0]]]] variable[out] assign[=] list[[]] variable[n] assign[=] constant[10] for taget[name[region_block]] in starred[call[name[tz].partition_all, parameter[name[n], name[regions]]]] begin[:] call[name[out].append, parameter[dictionary[[<ast.Constant object at 0x7da1b1885b10>], [<ast.ListComp object at 0x7da1b1884fd0>]]]] return[name[out]]
keyword[def] identifier[get_parallel_regions_block] ( identifier[batch] ): literal[string] identifier[samples] =[ identifier[utils] . identifier[to_single_data] ( identifier[d] ) keyword[for] identifier[d] keyword[in] identifier[batch] ] identifier[regions] = identifier[_get_parallel_regions] ( identifier[samples] [ literal[int] ]) identifier[out] =[] identifier[n] = literal[int] keyword[for] identifier[region_block] keyword[in] identifier[tz] . identifier[partition_all] ( identifier[n] , identifier[regions] ): identifier[out] . identifier[append] ({ literal[string] :[ literal[string] %( identifier[c] , identifier[s] , identifier[e] ) keyword[for] identifier[c] , identifier[s] , identifier[e] keyword[in] identifier[region_block] ]}) keyword[return] identifier[out]
def get_parallel_regions_block(batch): """CWL target to retrieve block group of callable regions for parallelization. Uses blocking to handle multicore runs. """ samples = [utils.to_single_data(d) for d in batch] regions = _get_parallel_regions(samples[0]) out = [] # Currently don't have core information here so aim for about 10 items per partition n = 10 for region_block in tz.partition_all(n, regions): out.append({'region_block': ['%s:%s-%s' % (c, s, e) for (c, s, e) in region_block]}) # depends on [control=['for'], data=['region_block']] return out
def get_relation_kwargs(field_name, relation_info): """ Creates a default instance of a flat relational field. """ model_field, related_model, to_many, to_field, has_through_model = relation_info kwargs = { 'queryset': related_model._default_manager, 'view_name': get_detail_view_name(related_model) } if to_many: kwargs['many'] = True if to_field: kwargs['to_field'] = to_field if has_through_model: kwargs['read_only'] = True kwargs.pop('queryset', None) if model_field: if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) help_text = model_field.help_text if help_text: kwargs['help_text'] = help_text if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) if kwargs.get('read_only', False): # If this field is read-only, then return early. # No further keyword arguments are valid. return kwargs if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False if model_field.null: kwargs['allow_null'] = True if model_field.validators: kwargs['validators'] = model_field.validators if getattr(model_field, 'unique', False): validator = UniqueValidator(queryset=model_field.model._default_manager) kwargs['validators'] = kwargs.get('validators', []) + [validator] if to_many and not model_field.blank: kwargs['allow_empty'] = False return kwargs
def function[get_relation_kwargs, parameter[field_name, relation_info]]: constant[ Creates a default instance of a flat relational field. ] <ast.Tuple object at 0x7da18f723280> assign[=] name[relation_info] variable[kwargs] assign[=] dictionary[[<ast.Constant object at 0x7da18f721f90>, <ast.Constant object at 0x7da18f7214e0>], [<ast.Attribute object at 0x7da18f7234c0>, <ast.Call object at 0x7da18f723160>]] if name[to_many] begin[:] call[name[kwargs]][constant[many]] assign[=] constant[True] if name[to_field] begin[:] call[name[kwargs]][constant[to_field]] assign[=] name[to_field] if name[has_through_model] begin[:] call[name[kwargs]][constant[read_only]] assign[=] constant[True] call[name[kwargs].pop, parameter[constant[queryset], constant[None]]] if name[model_field] begin[:] if <ast.BoolOp object at 0x7da18f7200a0> begin[:] call[name[kwargs]][constant[label]] assign[=] call[name[capfirst], parameter[name[model_field].verbose_name]] variable[help_text] assign[=] name[model_field].help_text if name[help_text] begin[:] call[name[kwargs]][constant[help_text]] assign[=] name[help_text] if <ast.UnaryOp object at 0x7da1b15a3160> begin[:] call[name[kwargs]][constant[read_only]] assign[=] constant[True] call[name[kwargs].pop, parameter[constant[queryset], constant[None]]] if call[name[kwargs].get, parameter[constant[read_only], constant[False]]] begin[:] return[name[kwargs]] if <ast.BoolOp object at 0x7da1b15a31f0> begin[:] call[name[kwargs]][constant[required]] assign[=] constant[False] if name[model_field].null begin[:] call[name[kwargs]][constant[allow_null]] assign[=] constant[True] if name[model_field].validators begin[:] call[name[kwargs]][constant[validators]] assign[=] name[model_field].validators if call[name[getattr], parameter[name[model_field], constant[unique], constant[False]]] begin[:] variable[validator] assign[=] call[name[UniqueValidator], parameter[]] call[name[kwargs]][constant[validators]] assign[=] binary_operation[call[name[kwargs].get, parameter[constant[validators], list[[]]]] + list[[<ast.Name object at 0x7da18eb56170>]]] if <ast.BoolOp object at 0x7da18eb55870> begin[:] call[name[kwargs]][constant[allow_empty]] assign[=] constant[False] return[name[kwargs]]
keyword[def] identifier[get_relation_kwargs] ( identifier[field_name] , identifier[relation_info] ): literal[string] identifier[model_field] , identifier[related_model] , identifier[to_many] , identifier[to_field] , identifier[has_through_model] = identifier[relation_info] identifier[kwargs] ={ literal[string] : identifier[related_model] . identifier[_default_manager] , literal[string] : identifier[get_detail_view_name] ( identifier[related_model] ) } keyword[if] identifier[to_many] : identifier[kwargs] [ literal[string] ]= keyword[True] keyword[if] identifier[to_field] : identifier[kwargs] [ literal[string] ]= identifier[to_field] keyword[if] identifier[has_through_model] : identifier[kwargs] [ literal[string] ]= keyword[True] identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] ) keyword[if] identifier[model_field] : keyword[if] identifier[model_field] . identifier[verbose_name] keyword[and] identifier[needs_label] ( identifier[model_field] , identifier[field_name] ): identifier[kwargs] [ literal[string] ]= identifier[capfirst] ( identifier[model_field] . identifier[verbose_name] ) identifier[help_text] = identifier[model_field] . identifier[help_text] keyword[if] identifier[help_text] : identifier[kwargs] [ literal[string] ]= identifier[help_text] keyword[if] keyword[not] identifier[model_field] . identifier[editable] : identifier[kwargs] [ literal[string] ]= keyword[True] identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] ) keyword[if] identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] ): keyword[return] identifier[kwargs] keyword[if] identifier[model_field] . identifier[has_default] () keyword[or] identifier[model_field] . identifier[blank] keyword[or] identifier[model_field] . identifier[null] : identifier[kwargs] [ literal[string] ]= keyword[False] keyword[if] identifier[model_field] . identifier[null] : identifier[kwargs] [ literal[string] ]= keyword[True] keyword[if] identifier[model_field] . identifier[validators] : identifier[kwargs] [ literal[string] ]= identifier[model_field] . identifier[validators] keyword[if] identifier[getattr] ( identifier[model_field] , literal[string] , keyword[False] ): identifier[validator] = identifier[UniqueValidator] ( identifier[queryset] = identifier[model_field] . identifier[model] . identifier[_default_manager] ) identifier[kwargs] [ literal[string] ]= identifier[kwargs] . identifier[get] ( literal[string] ,[])+[ identifier[validator] ] keyword[if] identifier[to_many] keyword[and] keyword[not] identifier[model_field] . identifier[blank] : identifier[kwargs] [ literal[string] ]= keyword[False] keyword[return] identifier[kwargs]
def get_relation_kwargs(field_name, relation_info): """ Creates a default instance of a flat relational field. """ (model_field, related_model, to_many, to_field, has_through_model) = relation_info kwargs = {'queryset': related_model._default_manager, 'view_name': get_detail_view_name(related_model)} if to_many: kwargs['many'] = True # depends on [control=['if'], data=[]] if to_field: kwargs['to_field'] = to_field # depends on [control=['if'], data=[]] if has_through_model: kwargs['read_only'] = True kwargs.pop('queryset', None) # depends on [control=['if'], data=[]] if model_field: if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) # depends on [control=['if'], data=[]] help_text = model_field.help_text if help_text: kwargs['help_text'] = help_text # depends on [control=['if'], data=[]] if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) # depends on [control=['if'], data=[]] if kwargs.get('read_only', False): # If this field is read-only, then return early. # No further keyword arguments are valid. return kwargs # depends on [control=['if'], data=[]] if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False # depends on [control=['if'], data=[]] if model_field.null: kwargs['allow_null'] = True # depends on [control=['if'], data=[]] if model_field.validators: kwargs['validators'] = model_field.validators # depends on [control=['if'], data=[]] if getattr(model_field, 'unique', False): validator = UniqueValidator(queryset=model_field.model._default_manager) kwargs['validators'] = kwargs.get('validators', []) + [validator] # depends on [control=['if'], data=[]] if to_many and (not model_field.blank): kwargs['allow_empty'] = False # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return kwargs
def add_contents(self, dest, contents): """Add file contents to the archive under ``dest``. If ``dest`` is a path, it will be added compressed and world-readable (user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for custom behavior. """ assert not self._closed, "Archive closed" if not isinstance(dest, zipfile.ZipInfo): dest = zinfo(dest) # see for some caveats # Ensure we apply the compression dest.compress_type = self.zip_compression # Mark host OS as Linux for all archives dest.create_system = 3 self._zip_file.writestr(dest, contents)
def function[add_contents, parameter[self, dest, contents]]: constant[Add file contents to the archive under ``dest``. If ``dest`` is a path, it will be added compressed and world-readable (user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for custom behavior. ] assert[<ast.UnaryOp object at 0x7da1b1f39f90>] if <ast.UnaryOp object at 0x7da1b1f393c0> begin[:] variable[dest] assign[=] call[name[zinfo], parameter[name[dest]]] name[dest].compress_type assign[=] name[self].zip_compression name[dest].create_system assign[=] constant[3] call[name[self]._zip_file.writestr, parameter[name[dest], name[contents]]]
keyword[def] identifier[add_contents] ( identifier[self] , identifier[dest] , identifier[contents] ): literal[string] keyword[assert] keyword[not] identifier[self] . identifier[_closed] , literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[dest] , identifier[zipfile] . identifier[ZipInfo] ): identifier[dest] = identifier[zinfo] ( identifier[dest] ) identifier[dest] . identifier[compress_type] = identifier[self] . identifier[zip_compression] identifier[dest] . identifier[create_system] = literal[int] identifier[self] . identifier[_zip_file] . identifier[writestr] ( identifier[dest] , identifier[contents] )
def add_contents(self, dest, contents): """Add file contents to the archive under ``dest``. If ``dest`` is a path, it will be added compressed and world-readable (user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for custom behavior. """ assert not self._closed, 'Archive closed' if not isinstance(dest, zipfile.ZipInfo): dest = zinfo(dest) # see for some caveats # depends on [control=['if'], data=[]] # Ensure we apply the compression dest.compress_type = self.zip_compression # Mark host OS as Linux for all archives dest.create_system = 3 self._zip_file.writestr(dest, contents)
def abort_request(self, stream, ident, parent): """abort a specifig msg by id""" msg_ids = parent['content'].get('msg_ids', None) if isinstance(msg_ids, basestring): msg_ids = [msg_ids] if not msg_ids: self.abort_queues() for mid in msg_ids: self.aborted.add(str(mid)) content = dict(status='ok') reply_msg = self.session.send(stream, 'abort_reply', content=content, parent=parent, ident=ident) self.log.debug("%s", reply_msg)
def function[abort_request, parameter[self, stream, ident, parent]]: constant[abort a specifig msg by id] variable[msg_ids] assign[=] call[call[name[parent]][constant[content]].get, parameter[constant[msg_ids], constant[None]]] if call[name[isinstance], parameter[name[msg_ids], name[basestring]]] begin[:] variable[msg_ids] assign[=] list[[<ast.Name object at 0x7da20c6c6e00>]] if <ast.UnaryOp object at 0x7da20c6c5a80> begin[:] call[name[self].abort_queues, parameter[]] for taget[name[mid]] in starred[name[msg_ids]] begin[:] call[name[self].aborted.add, parameter[call[name[str], parameter[name[mid]]]]] variable[content] assign[=] call[name[dict], parameter[]] variable[reply_msg] assign[=] call[name[self].session.send, parameter[name[stream], constant[abort_reply]]] call[name[self].log.debug, parameter[constant[%s], name[reply_msg]]]
keyword[def] identifier[abort_request] ( identifier[self] , identifier[stream] , identifier[ident] , identifier[parent] ): literal[string] identifier[msg_ids] = identifier[parent] [ literal[string] ]. identifier[get] ( literal[string] , keyword[None] ) keyword[if] identifier[isinstance] ( identifier[msg_ids] , identifier[basestring] ): identifier[msg_ids] =[ identifier[msg_ids] ] keyword[if] keyword[not] identifier[msg_ids] : identifier[self] . identifier[abort_queues] () keyword[for] identifier[mid] keyword[in] identifier[msg_ids] : identifier[self] . identifier[aborted] . identifier[add] ( identifier[str] ( identifier[mid] )) identifier[content] = identifier[dict] ( identifier[status] = literal[string] ) identifier[reply_msg] = identifier[self] . identifier[session] . identifier[send] ( identifier[stream] , literal[string] , identifier[content] = identifier[content] , identifier[parent] = identifier[parent] , identifier[ident] = identifier[ident] ) identifier[self] . identifier[log] . identifier[debug] ( literal[string] , identifier[reply_msg] )
def abort_request(self, stream, ident, parent): """abort a specifig msg by id""" msg_ids = parent['content'].get('msg_ids', None) if isinstance(msg_ids, basestring): msg_ids = [msg_ids] # depends on [control=['if'], data=[]] if not msg_ids: self.abort_queues() # depends on [control=['if'], data=[]] for mid in msg_ids: self.aborted.add(str(mid)) # depends on [control=['for'], data=['mid']] content = dict(status='ok') reply_msg = self.session.send(stream, 'abort_reply', content=content, parent=parent, ident=ident) self.log.debug('%s', reply_msg)
def get_notice_content(self, time: str) -> str: """ 取得公布欄特定訊息內容 """ try: # 取得資料 response = self.__session.get( self.__url + '/showArticle?time=' + time, timeout=0.5, verify=False) soup = BeautifulSoup(response.text, 'html.parser') # 回傳結果 return soup.find('pre').get_text().strip().replace('\r', '') except requests.exceptions.Timeout: return "Timeout"
def function[get_notice_content, parameter[self, time]]: constant[ 取得公布欄特定訊息內容 ] <ast.Try object at 0x7da204566a10>
keyword[def] identifier[get_notice_content] ( identifier[self] , identifier[time] : identifier[str] )-> identifier[str] : literal[string] keyword[try] : identifier[response] = identifier[self] . identifier[__session] . identifier[get] ( identifier[self] . identifier[__url] + literal[string] + identifier[time] , identifier[timeout] = literal[int] , identifier[verify] = keyword[False] ) identifier[soup] = identifier[BeautifulSoup] ( identifier[response] . identifier[text] , literal[string] ) keyword[return] identifier[soup] . identifier[find] ( literal[string] ). identifier[get_text] (). identifier[strip] (). identifier[replace] ( literal[string] , literal[string] ) keyword[except] identifier[requests] . identifier[exceptions] . identifier[Timeout] : keyword[return] literal[string]
def get_notice_content(self, time: str) -> str: """ 取得公布欄特定訊息內容 """ try: # 取得資料 response = self.__session.get(self.__url + '/showArticle?time=' + time, timeout=0.5, verify=False) soup = BeautifulSoup(response.text, 'html.parser') # 回傳結果 return soup.find('pre').get_text().strip().replace('\r', '') # depends on [control=['try'], data=[]] except requests.exceptions.Timeout: return 'Timeout' # depends on [control=['except'], data=[]]
def value_edited(self, path, new_value_str): """ Adds the value of the semantic data entry :param path: The path inside the tree store to the target entry :param str new_value_str: The new value of the target cell :return: """ tree_store_path = self.create_tree_store_path_from_key_string(path) if isinstance(path, string_types) else path if self.tree_store[tree_store_path][self.VALUE_STORAGE_ID] == new_value_str: return dict_path = self.tree_store[tree_store_path][self.ID_STORAGE_ID] self.model.state.add_semantic_data(dict_path[0:-1], new_value_str, key=dict_path[-1]) self.reload_tree_store_data()
def function[value_edited, parameter[self, path, new_value_str]]: constant[ Adds the value of the semantic data entry :param path: The path inside the tree store to the target entry :param str new_value_str: The new value of the target cell :return: ] variable[tree_store_path] assign[=] <ast.IfExp object at 0x7da1b192dd20> if compare[call[call[name[self].tree_store][name[tree_store_path]]][name[self].VALUE_STORAGE_ID] equal[==] name[new_value_str]] begin[:] return[None] variable[dict_path] assign[=] call[call[name[self].tree_store][name[tree_store_path]]][name[self].ID_STORAGE_ID] call[name[self].model.state.add_semantic_data, parameter[call[name[dict_path]][<ast.Slice object at 0x7da1b192e6b0>], name[new_value_str]]] call[name[self].reload_tree_store_data, parameter[]]
keyword[def] identifier[value_edited] ( identifier[self] , identifier[path] , identifier[new_value_str] ): literal[string] identifier[tree_store_path] = identifier[self] . identifier[create_tree_store_path_from_key_string] ( identifier[path] ) keyword[if] identifier[isinstance] ( identifier[path] , identifier[string_types] ) keyword[else] identifier[path] keyword[if] identifier[self] . identifier[tree_store] [ identifier[tree_store_path] ][ identifier[self] . identifier[VALUE_STORAGE_ID] ]== identifier[new_value_str] : keyword[return] identifier[dict_path] = identifier[self] . identifier[tree_store] [ identifier[tree_store_path] ][ identifier[self] . identifier[ID_STORAGE_ID] ] identifier[self] . identifier[model] . identifier[state] . identifier[add_semantic_data] ( identifier[dict_path] [ literal[int] :- literal[int] ], identifier[new_value_str] , identifier[key] = identifier[dict_path] [- literal[int] ]) identifier[self] . identifier[reload_tree_store_data] ()
def value_edited(self, path, new_value_str): """ Adds the value of the semantic data entry :param path: The path inside the tree store to the target entry :param str new_value_str: The new value of the target cell :return: """ tree_store_path = self.create_tree_store_path_from_key_string(path) if isinstance(path, string_types) else path if self.tree_store[tree_store_path][self.VALUE_STORAGE_ID] == new_value_str: return # depends on [control=['if'], data=[]] dict_path = self.tree_store[tree_store_path][self.ID_STORAGE_ID] self.model.state.add_semantic_data(dict_path[0:-1], new_value_str, key=dict_path[-1]) self.reload_tree_store_data()
def _labels_from_pyclusters(self): """ Computes and returns the list of labels indicating the data points and the corresponding cluster ids. :return: The list of labels """ clusters = self.model.get_clusters() labels = [] for i in range(0, len(clusters)): for j in clusters[i]: labels.insert(int(j), i) return labels
def function[_labels_from_pyclusters, parameter[self]]: constant[ Computes and returns the list of labels indicating the data points and the corresponding cluster ids. :return: The list of labels ] variable[clusters] assign[=] call[name[self].model.get_clusters, parameter[]] variable[labels] assign[=] list[[]] for taget[name[i]] in starred[call[name[range], parameter[constant[0], call[name[len], parameter[name[clusters]]]]]] begin[:] for taget[name[j]] in starred[call[name[clusters]][name[i]]] begin[:] call[name[labels].insert, parameter[call[name[int], parameter[name[j]]], name[i]]] return[name[labels]]
keyword[def] identifier[_labels_from_pyclusters] ( identifier[self] ): literal[string] identifier[clusters] = identifier[self] . identifier[model] . identifier[get_clusters] () identifier[labels] =[] keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[clusters] )): keyword[for] identifier[j] keyword[in] identifier[clusters] [ identifier[i] ]: identifier[labels] . identifier[insert] ( identifier[int] ( identifier[j] ), identifier[i] ) keyword[return] identifier[labels]
def _labels_from_pyclusters(self): """ Computes and returns the list of labels indicating the data points and the corresponding cluster ids. :return: The list of labels """ clusters = self.model.get_clusters() labels = [] for i in range(0, len(clusters)): for j in clusters[i]: labels.insert(int(j), i) # depends on [control=['for'], data=['j']] # depends on [control=['for'], data=['i']] return labels
def commit(self): """ Commits the changes to the current database connection. :return <bool> success """ with self.native(writeAccess=True) as conn: if not self._closed(conn): return self._commit(conn)
def function[commit, parameter[self]]: constant[ Commits the changes to the current database connection. :return <bool> success ] with call[name[self].native, parameter[]] begin[:] if <ast.UnaryOp object at 0x7da2043471c0> begin[:] return[call[name[self]._commit, parameter[name[conn]]]]
keyword[def] identifier[commit] ( identifier[self] ): literal[string] keyword[with] identifier[self] . identifier[native] ( identifier[writeAccess] = keyword[True] ) keyword[as] identifier[conn] : keyword[if] keyword[not] identifier[self] . identifier[_closed] ( identifier[conn] ): keyword[return] identifier[self] . identifier[_commit] ( identifier[conn] )
def commit(self): """ Commits the changes to the current database connection. :return <bool> success """ with self.native(writeAccess=True) as conn: if not self._closed(conn): return self._commit(conn) # depends on [control=['if'], data=[]] # depends on [control=['with'], data=['conn']]
def get_package_version(self, package): # type: (str) -> Tuple[int, int, int] """ Provides the version of the given package name. :param package: The name of the package :return: The version of the specified package as a tuple or (0,0,0) """ name = "{0}{1}".format(ENDPOINT_PACKAGE_VERSION_, package) try: # Get the version string version = self._properties[name] # Split dots ('.') return tuple(version.split(".")) except KeyError: # No version return 0, 0, 0
def function[get_package_version, parameter[self, package]]: constant[ Provides the version of the given package name. :param package: The name of the package :return: The version of the specified package as a tuple or (0,0,0) ] variable[name] assign[=] call[constant[{0}{1}].format, parameter[name[ENDPOINT_PACKAGE_VERSION_], name[package]]] <ast.Try object at 0x7da18f09cac0>
keyword[def] identifier[get_package_version] ( identifier[self] , identifier[package] ): literal[string] identifier[name] = literal[string] . identifier[format] ( identifier[ENDPOINT_PACKAGE_VERSION_] , identifier[package] ) keyword[try] : identifier[version] = identifier[self] . identifier[_properties] [ identifier[name] ] keyword[return] identifier[tuple] ( identifier[version] . identifier[split] ( literal[string] )) keyword[except] identifier[KeyError] : keyword[return] literal[int] , literal[int] , literal[int]
def get_package_version(self, package): # type: (str) -> Tuple[int, int, int] '\n Provides the version of the given package name.\n\n :param package: The name of the package\n :return: The version of the specified package as a tuple or (0,0,0)\n ' name = '{0}{1}'.format(ENDPOINT_PACKAGE_VERSION_, package) try: # Get the version string version = self._properties[name] # Split dots ('.') return tuple(version.split('.')) # depends on [control=['try'], data=[]] except KeyError: # No version return (0, 0, 0) # depends on [control=['except'], data=[]]
def do_rpc(self, name: str, rpc_function: Callable[..., Awaitable[None]]) -> Callable[..., Awaitable[None]]: """ Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio event loop. The wrapped function catches all unhandled exceptions and reports them to the exception future, which consumers can await upon to listen for unhandled exceptions. The wrapped function also keeps track of the number of outstanding RPCs to synchronize during shutdown. :param name: The name of this RPC, to be used for logging :param rpc_function: The function implementing the RPC :return: An awaitable function implementing the RPC """ async def rpc_wrapper(*args, **kwargs): log.debug(f"beginning rpc {name}") async with self.zero_cond: self.count += 1 log.debug(f"recorded new RPC, {self.count} RPCs outstanding") try: result = await rpc_function(*args, **kwargs) except Exception as exn: log.debug(f"RPC failed with exception:") log.debug(traceback.format_exc()) if not self.exception_future.done(): self.exception_future.set_exception(exn) result = None async with self.zero_cond: self.count -= 1 if self.count == 0: log.debug("All RPC completed, signalling completion") if not self.exception_future.done(): self.exception_future.set_result(None) self.zero_cond.notify_all() log.debug(f"recorded RPC completion, {self.count} RPCs outstanding") return result return rpc_wrapper
def function[do_rpc, parameter[self, name, rpc_function]]: constant[ Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio event loop. The wrapped function catches all unhandled exceptions and reports them to the exception future, which consumers can await upon to listen for unhandled exceptions. The wrapped function also keeps track of the number of outstanding RPCs to synchronize during shutdown. :param name: The name of this RPC, to be used for logging :param rpc_function: The function implementing the RPC :return: An awaitable function implementing the RPC ] <ast.AsyncFunctionDef object at 0x7da2047ea920> return[name[rpc_wrapper]]
keyword[def] identifier[do_rpc] ( identifier[self] , identifier[name] : identifier[str] , identifier[rpc_function] : identifier[Callable] [..., identifier[Awaitable] [ keyword[None] ]])-> identifier[Callable] [..., identifier[Awaitable] [ keyword[None] ]]: literal[string] keyword[async] keyword[def] identifier[rpc_wrapper] (* identifier[args] ,** identifier[kwargs] ): identifier[log] . identifier[debug] ( literal[string] ) keyword[async] keyword[with] identifier[self] . identifier[zero_cond] : identifier[self] . identifier[count] += literal[int] identifier[log] . identifier[debug] ( literal[string] ) keyword[try] : identifier[result] = keyword[await] identifier[rpc_function] (* identifier[args] ,** identifier[kwargs] ) keyword[except] identifier[Exception] keyword[as] identifier[exn] : identifier[log] . identifier[debug] ( literal[string] ) identifier[log] . identifier[debug] ( identifier[traceback] . identifier[format_exc] ()) keyword[if] keyword[not] identifier[self] . identifier[exception_future] . identifier[done] (): identifier[self] . identifier[exception_future] . identifier[set_exception] ( identifier[exn] ) identifier[result] = keyword[None] keyword[async] keyword[with] identifier[self] . identifier[zero_cond] : identifier[self] . identifier[count] -= literal[int] keyword[if] identifier[self] . identifier[count] == literal[int] : identifier[log] . identifier[debug] ( literal[string] ) keyword[if] keyword[not] identifier[self] . identifier[exception_future] . identifier[done] (): identifier[self] . identifier[exception_future] . identifier[set_result] ( keyword[None] ) identifier[self] . identifier[zero_cond] . identifier[notify_all] () identifier[log] . identifier[debug] ( literal[string] ) keyword[return] identifier[result] keyword[return] identifier[rpc_wrapper]
def do_rpc(self, name: str, rpc_function: Callable[..., Awaitable[None]]) -> Callable[..., Awaitable[None]]: """ Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio event loop. The wrapped function catches all unhandled exceptions and reports them to the exception future, which consumers can await upon to listen for unhandled exceptions. The wrapped function also keeps track of the number of outstanding RPCs to synchronize during shutdown. :param name: The name of this RPC, to be used for logging :param rpc_function: The function implementing the RPC :return: An awaitable function implementing the RPC """ async def rpc_wrapper(*args, **kwargs): log.debug(f'beginning rpc {name}') async with self.zero_cond: self.count += 1 log.debug(f'recorded new RPC, {self.count} RPCs outstanding') try: result = await rpc_function(*args, **kwargs) # depends on [control=['try'], data=[]] except Exception as exn: log.debug(f'RPC failed with exception:') log.debug(traceback.format_exc()) if not self.exception_future.done(): self.exception_future.set_exception(exn) # depends on [control=['if'], data=[]] result = None # depends on [control=['except'], data=['exn']] async with self.zero_cond: self.count -= 1 if self.count == 0: log.debug('All RPC completed, signalling completion') if not self.exception_future.done(): self.exception_future.set_result(None) # depends on [control=['if'], data=[]] self.zero_cond.notify_all() # depends on [control=['if'], data=[]] log.debug(f'recorded RPC completion, {self.count} RPCs outstanding') return result return rpc_wrapper
def add_process(self, tgt, args=None, kwargs=None, name=None): ''' Create a processes and args + kwargs This will deterimine if it is a Process class, otherwise it assumes it is a function ''' if args is None: args = [] if kwargs is None: kwargs = {} if salt.utils.platform.is_windows(): # Need to ensure that 'log_queue' and 'log_queue_level' is # correctly transferred to processes that inherit from # 'MultiprocessingProcess'. if type(MultiprocessingProcess) is type(tgt) and ( issubclass(tgt, MultiprocessingProcess)): need_log_queue = True else: need_log_queue = False if need_log_queue: if 'log_queue' not in kwargs: if hasattr(self, 'log_queue'): kwargs['log_queue'] = self.log_queue else: kwargs['log_queue'] = ( salt.log.setup.get_multiprocessing_logging_queue() ) if 'log_queue_level' not in kwargs: if hasattr(self, 'log_queue_level'): kwargs['log_queue_level'] = self.log_queue_level else: kwargs['log_queue_level'] = ( salt.log.setup.get_multiprocessing_logging_level() ) # create a nicer name for the debug log if name is None: if isinstance(tgt, types.FunctionType): name = '{0}.{1}'.format( tgt.__module__, tgt.__name__, ) else: name = '{0}{1}.{2}'.format( tgt.__module__, '.{0}'.format(tgt.__class__) if six.text_type(tgt.__class__) != "<type 'type'>" else '', tgt.__name__, ) if type(multiprocessing.Process) is type(tgt) and issubclass(tgt, multiprocessing.Process): process = tgt(*args, **kwargs) else: process = multiprocessing.Process(target=tgt, args=args, kwargs=kwargs, name=name) if isinstance(process, SignalHandlingMultiprocessingProcess): with default_signals(signal.SIGINT, signal.SIGTERM): process.start() else: process.start() log.debug("Started '%s' with pid %s", name, process.pid) self._process_map[process.pid] = {'tgt': tgt, 'args': args, 'kwargs': kwargs, 'Process': process} return process
def function[add_process, parameter[self, tgt, args, kwargs, name]]: constant[ Create a processes and args + kwargs This will deterimine if it is a Process class, otherwise it assumes it is a function ] if compare[name[args] is constant[None]] begin[:] variable[args] assign[=] list[[]] if compare[name[kwargs] is constant[None]] begin[:] variable[kwargs] assign[=] dictionary[[], []] if call[name[salt].utils.platform.is_windows, parameter[]] begin[:] if <ast.BoolOp object at 0x7da20e9618a0> begin[:] variable[need_log_queue] assign[=] constant[True] if name[need_log_queue] begin[:] if compare[constant[log_queue] <ast.NotIn object at 0x7da2590d7190> name[kwargs]] begin[:] if call[name[hasattr], parameter[name[self], constant[log_queue]]] begin[:] call[name[kwargs]][constant[log_queue]] assign[=] name[self].log_queue if compare[constant[log_queue_level] <ast.NotIn object at 0x7da2590d7190> name[kwargs]] begin[:] if call[name[hasattr], parameter[name[self], constant[log_queue_level]]] begin[:] call[name[kwargs]][constant[log_queue_level]] assign[=] name[self].log_queue_level if compare[name[name] is constant[None]] begin[:] if call[name[isinstance], parameter[name[tgt], name[types].FunctionType]] begin[:] variable[name] assign[=] call[constant[{0}.{1}].format, parameter[name[tgt].__module__, name[tgt].__name__]] if <ast.BoolOp object at 0x7da204962e00> begin[:] variable[process] assign[=] call[name[tgt], parameter[<ast.Starred object at 0x7da204960640>]] if call[name[isinstance], parameter[name[process], name[SignalHandlingMultiprocessingProcess]]] begin[:] with call[name[default_signals], parameter[name[signal].SIGINT, name[signal].SIGTERM]] begin[:] call[name[process].start, parameter[]] call[name[log].debug, parameter[constant[Started '%s' with pid %s], name[name], name[process].pid]] call[name[self]._process_map][name[process].pid] assign[=] dictionary[[<ast.Constant object at 0x7da18eb57730>, <ast.Constant object at 0x7da18eb576d0>, <ast.Constant object at 0x7da18eb578e0>, <ast.Constant object at 0x7da18eb550f0>], [<ast.Name object at 0x7da18eb54820>, <ast.Name object at 0x7da18eb566e0>, <ast.Name object at 0x7da18eb56650>, <ast.Name object at 0x7da18eb560b0>]] return[name[process]]
keyword[def] identifier[add_process] ( identifier[self] , identifier[tgt] , identifier[args] = keyword[None] , identifier[kwargs] = keyword[None] , identifier[name] = keyword[None] ): literal[string] keyword[if] identifier[args] keyword[is] keyword[None] : identifier[args] =[] keyword[if] identifier[kwargs] keyword[is] keyword[None] : identifier[kwargs] ={} keyword[if] identifier[salt] . identifier[utils] . identifier[platform] . identifier[is_windows] (): keyword[if] identifier[type] ( identifier[MultiprocessingProcess] ) keyword[is] identifier[type] ( identifier[tgt] ) keyword[and] ( identifier[issubclass] ( identifier[tgt] , identifier[MultiprocessingProcess] )): identifier[need_log_queue] = keyword[True] keyword[else] : identifier[need_log_queue] = keyword[False] keyword[if] identifier[need_log_queue] : keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] : keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ): identifier[kwargs] [ literal[string] ]= identifier[self] . identifier[log_queue] keyword[else] : identifier[kwargs] [ literal[string] ]=( identifier[salt] . identifier[log] . identifier[setup] . identifier[get_multiprocessing_logging_queue] () ) keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] : keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ): identifier[kwargs] [ literal[string] ]= identifier[self] . identifier[log_queue_level] keyword[else] : identifier[kwargs] [ literal[string] ]=( identifier[salt] . identifier[log] . identifier[setup] . identifier[get_multiprocessing_logging_level] () ) keyword[if] identifier[name] keyword[is] keyword[None] : keyword[if] identifier[isinstance] ( identifier[tgt] , identifier[types] . identifier[FunctionType] ): identifier[name] = literal[string] . identifier[format] ( identifier[tgt] . identifier[__module__] , identifier[tgt] . identifier[__name__] , ) keyword[else] : identifier[name] = literal[string] . identifier[format] ( identifier[tgt] . identifier[__module__] , literal[string] . identifier[format] ( identifier[tgt] . identifier[__class__] ) keyword[if] identifier[six] . identifier[text_type] ( identifier[tgt] . identifier[__class__] )!= literal[string] keyword[else] literal[string] , identifier[tgt] . identifier[__name__] , ) keyword[if] identifier[type] ( identifier[multiprocessing] . identifier[Process] ) keyword[is] identifier[type] ( identifier[tgt] ) keyword[and] identifier[issubclass] ( identifier[tgt] , identifier[multiprocessing] . identifier[Process] ): identifier[process] = identifier[tgt] (* identifier[args] ,** identifier[kwargs] ) keyword[else] : identifier[process] = identifier[multiprocessing] . identifier[Process] ( identifier[target] = identifier[tgt] , identifier[args] = identifier[args] , identifier[kwargs] = identifier[kwargs] , identifier[name] = identifier[name] ) keyword[if] identifier[isinstance] ( identifier[process] , identifier[SignalHandlingMultiprocessingProcess] ): keyword[with] identifier[default_signals] ( identifier[signal] . identifier[SIGINT] , identifier[signal] . identifier[SIGTERM] ): identifier[process] . identifier[start] () keyword[else] : identifier[process] . identifier[start] () identifier[log] . identifier[debug] ( literal[string] , identifier[name] , identifier[process] . identifier[pid] ) identifier[self] . identifier[_process_map] [ identifier[process] . identifier[pid] ]={ literal[string] : identifier[tgt] , literal[string] : identifier[args] , literal[string] : identifier[kwargs] , literal[string] : identifier[process] } keyword[return] identifier[process]
def add_process(self, tgt, args=None, kwargs=None, name=None): """ Create a processes and args + kwargs This will deterimine if it is a Process class, otherwise it assumes it is a function """ if args is None: args = [] # depends on [control=['if'], data=['args']] if kwargs is None: kwargs = {} # depends on [control=['if'], data=['kwargs']] if salt.utils.platform.is_windows(): # Need to ensure that 'log_queue' and 'log_queue_level' is # correctly transferred to processes that inherit from # 'MultiprocessingProcess'. if type(MultiprocessingProcess) is type(tgt) and issubclass(tgt, MultiprocessingProcess): need_log_queue = True # depends on [control=['if'], data=[]] else: need_log_queue = False if need_log_queue: if 'log_queue' not in kwargs: if hasattr(self, 'log_queue'): kwargs['log_queue'] = self.log_queue # depends on [control=['if'], data=[]] else: kwargs['log_queue'] = salt.log.setup.get_multiprocessing_logging_queue() # depends on [control=['if'], data=['kwargs']] if 'log_queue_level' not in kwargs: if hasattr(self, 'log_queue_level'): kwargs['log_queue_level'] = self.log_queue_level # depends on [control=['if'], data=[]] else: kwargs['log_queue_level'] = salt.log.setup.get_multiprocessing_logging_level() # depends on [control=['if'], data=['kwargs']] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # create a nicer name for the debug log if name is None: if isinstance(tgt, types.FunctionType): name = '{0}.{1}'.format(tgt.__module__, tgt.__name__) # depends on [control=['if'], data=[]] else: name = '{0}{1}.{2}'.format(tgt.__module__, '.{0}'.format(tgt.__class__) if six.text_type(tgt.__class__) != "<type 'type'>" else '', tgt.__name__) # depends on [control=['if'], data=['name']] if type(multiprocessing.Process) is type(tgt) and issubclass(tgt, multiprocessing.Process): process = tgt(*args, **kwargs) # depends on [control=['if'], data=[]] else: process = multiprocessing.Process(target=tgt, args=args, kwargs=kwargs, name=name) if isinstance(process, SignalHandlingMultiprocessingProcess): with default_signals(signal.SIGINT, signal.SIGTERM): process.start() # depends on [control=['with'], data=[]] # depends on [control=['if'], data=[]] else: process.start() log.debug("Started '%s' with pid %s", name, process.pid) self._process_map[process.pid] = {'tgt': tgt, 'args': args, 'kwargs': kwargs, 'Process': process} return process