_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q50300
AbstractNode.list_attributes
train
def list_attributes(self): """ Returns the Node attributes names. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.list_attributes() ['attributeB', 'attributeA'] :return: Attributes names. ...
python
{ "resource": "" }
q50301
AbstractNode.get_attributes
train
def get_attributes(self): """ Returns the Node attributes. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(value="A"), attributeB=Attribute(value="B")) >>> node_a.get_attributes() [<Attribute object at 0x7fa471d3b5e0>, <Attribute object at ...
python
{ "resource": "" }
q50302
AbstractNode.attribute_exists
train
def attribute_exists(self, name): """ Returns if given attribute exists in the node. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.attribute_exists("attributeA") True >>> node_a.attribute_...
python
{ "resource": "" }
q50303
AbstractNode.add_attribute
train
def add_attribute(self, name, value): """ Adds given attribute to the node. Usage:: >>> node_a = AbstractNode() >>> node_a.add_attribute("attributeA", Attribute()) True >>> node_a.list_attributes() [u'attributeA'] :param name...
python
{ "resource": "" }
q50304
AbstractNode.remove_attribute
train
def remove_attribute(self, name): """ Removes given attribute from the node. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.remove_attribute("attributeA") True >>> node_a.list_attributes() ...
python
{ "resource": "" }
q50305
AbstractCompositeNode.child
train
def child(self, index): """ Returns the child associated with given index. Usage:: >>> node_b = AbstractCompositeNode("MyNodeB") >>> node_c = AbstractCompositeNode("MyNodeC") >>> node_a = AbstractCompositeNode("MyNodeA", children=[node_b, node_c]) ...
python
{ "resource": "" }
q50306
AbstractCompositeNode.index_of
train
def index_of(self, child): """ Returns the given child index. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_a.index_of(no...
python
{ "resource": "" }
q50307
AbstractCompositeNode.add_child
train
def add_child(self, child): """ Adds given child to the node. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB") >>> node_a.add_child(node_b) True >>> node_a.children [<Abst...
python
{ "resource": "" }
q50308
AbstractCompositeNode.remove_child
train
def remove_child(self, index): """ Removes child at given index from the Node children. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) ...
python
{ "resource": "" }
q50309
AbstractCompositeNode.insert_child
train
def insert_child(self, child, index): """ Inserts given child at given index. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> no...
python
{ "resource": "" }
q50310
AbstractCompositeNode.sort_children
train
def sort_children(self, attribute=None, reverse_order=False): """ Sorts the children using either the given attribute or the Node name. :param attribute: Attribute name used for sorting. :type attribute: unicode :param reverse_order: Sort in reverse order. :type reverse_...
python
{ "resource": "" }
q50311
AbstractCompositeNode.find_children
train
def find_children(self, pattern=r".*", flags=0, candidates=None): """ Finds the children matching the given patten. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode...
python
{ "resource": "" }
q50312
AbstractCompositeNode.list_node
train
def list_node(self, tab_level=-1): """ Lists the current Node and its children. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> ...
python
{ "resource": "" }
q50313
add_repositories
train
def add_repositories(): """ Adds additional sources as defined in LINUX_PACKAGE_REPOSITORIES. """ if not env.overwrite and env.LINUX_PACKAGE_REPOSITORIES == server_state('linux_package_repositories'): return if env.verbosity: print env.host, "UNCOMMENTING SOURCES in /etc/apt/sources.list an...
python
{ "resource": "" }
q50314
add_user
train
def add_user(username='',password='',group='', site_user=False): """ Adds the username """ if group: group = '-g %s'% group if not site_user: run('echo %s:%s > /tmp/users.txt'% (username,password)) if not site_user: sudo('useradd -m -s /bin/bash %s %s'% (group,username)) ...
python
{ "resource": "" }
q50315
change_ssh_port
train
def change_ssh_port(): """ For security woven changes the default ssh port. """ host = normalize(env.host_string)[1] after = env.port before = str(env.DEFAULT_SSH_PORT) host_string=join_host_strings(env.user,host,before) with settings(host_string=host_string, user=env.user): ...
python
{ "resource": "" }
q50316
install_packages
train
def install_packages(): """ Install a set of baseline packages and configure where necessary """ if env.verbosity: print env.host, "INSTALLING & CONFIGURING NODE PACKAGES:" #Get a list of installed packages p = run("dpkg -l | awk '/ii/ {print $2}'").split('\n') #Remove apparmor...
python
{ "resource": "" }
q50317
port_is_open
train
def port_is_open(): """ Determine if the default port and user is open for business. """ with settings(hide('aborts'), warn_only=True ): try: if env.verbosity: print "Testing node for previous installation on port %s:"% env.port distribution = lsb_release(...
python
{ "resource": "" }
q50318
set_timezone
train
def set_timezone(rollback=False): """ Set the time zone on the server using Django settings.TIME_ZONE """ if not rollback: if contains(filename='/etc/timezone', text=env.TIME_ZONE, use_sudo=True): return False if env.verbosity: print env.host, "CHANGING TIMEZONE /...
python
{ "resource": "" }
q50319
setup_ufw
train
def setup_ufw(): """ Setup basic ufw rules just for ssh login """ if not env.ENABLE_UFW: return ufw_state = server_state('ufw_installed') if ufw_state and not env.overwrite or ufw_state == str(env.HOST_SSH_PORT): return #check for actual package ufw = run("dpkg -l | grep 'ufw' | awk ...
python
{ "resource": "" }
q50320
setup_ufw_rules
train
def setup_ufw_rules(): """ Setup ufw app rules from application templates and settings UFW_RULES """ #current rules current_rules = server_state('ufw_rules') if current_rules: current_rules = set(current_rules) else: current_rules = set([]) role = env.role_lookup[env.host_string] ...
python
{ "resource": "" }
q50321
uninstall_packages
train
def uninstall_packages(): """ Uninstall unwanted packages """ p = server_state('packages_installed') if p: installed = set(p) else: return env.uninstalled_packages[env.host] = [] #first uninstall any that have been taken off the list packages = set(get_packages()) uninstall = ins...
python
{ "resource": "" }
q50322
upgrade_packages
train
def upgrade_packages(): """ apt-get update and apt-get upgrade """ if env.verbosity: print env.host, "apt-get UPDATING and UPGRADING SERVER PACKAGES" print " * running apt-get update " sudo('apt-get -qqy update') if env.verbosity: print " * running apt-get upgrade" ...
python
{ "resource": "" }
q50323
upload_ssh_key
train
def upload_ssh_key(rollback=False): """ Upload your ssh key for passwordless logins """ auth_keys = '/home/%s/.ssh/authorized_keys'% env.user if not rollback: local_user = getpass.getuser() host = socket.gethostname() u = '@'.join([local_user,host]) u = 'ssh-key-uploa...
python
{ "resource": "" }
q50324
generate_text_files
train
def generate_text_files(in_dir, out_dir, include_header=False): """\ Walks through the `in_dir` and generates text versions of the cables in the `out_dir`. """ for cable in cables_from_source(in_dir): out = codecs.open(out_dir + '/' + cable.reference_id + '.txt', 'wb', encoding='utf-8') ...
python
{ "resource": "" }
q50325
extract_stack
train
def extract_stack(frame, context=10, exceptionsFrameSymbol=EXCEPTIONS_FRAME_SYMBOL): """ Extracts the stack from given frame while excluded any symbolized frame. :param frame: Frame. :type frame: Frame :param context: Context to extract. :type context: int :param exceptionsFrameSymbol: Stac...
python
{ "resource": "" }
q50326
extract_arguments
train
def extract_arguments(frame): """ Extracts the arguments from given frame. :param frame: Frame. :type frame: object :return: Arguments. :rtype: tuple """ arguments = ([], None, None) try: source = textwrap.dedent("".join(inspect.getsourcelines(frame)[0]).replace("\\\n", "")...
python
{ "resource": "" }
q50327
extract_locals
train
def extract_locals(trcback): """ Extracts the frames locals of given traceback. :param trcback: Traceback. :type trcback: Traceback :return: Frames locals. :rtype: list """ output = [] stack = extract_stack(get_inner_most_frame(trcback)) for frame, file_name, line_number, name,...
python
{ "resource": "" }
q50328
format_report
train
def format_report(cls, instance, trcback, context=1): """ Formats a report using given exception. :param cls: Exception class. :type cls: object :param instance: Exception instance. :type instance: object :param trcback: Traceback. :type trcback: Traceback :param context: Context be...
python
{ "resource": "" }
q50329
base_exception_handler
train
def base_exception_handler(*args): """ Provides the base exception handler. :param \*args: Arguments. :type \*args: \* :return: Definition success. :rtype: bool """ header, frames, trcback = format_report(*extract_exception(*args)) LOGGER.error("!> {0}".format(Constants.logging_se...
python
{ "resource": "" }
q50330
update_parameters
train
def update_parameters(url, parameters, encoding='utf8'): """ Updates a URL's existing GET parameters. :param url: a base URL to which to add additional parameters. :param parameters: a dictionary of parameters, any mix of unicode and string objects as the parameters and the values. :parameter encoding: the...
python
{ "resource": "" }
q50331
copy
train
def copy(source, destination): """ Copies given file or directory to destination. :param source: Source to copy from. :type source: unicode :param destination: Destination to copy to. :type destination: unicode :return: Method success. :rtype: bool """ try: if os.path.i...
python
{ "resource": "" }
q50332
remove
train
def remove(path): """ Removes given path. :param path: Path to remove. :type path: unicode :return: Method success. :rtype: bool """ try: if os.path.isfile(path): LOGGER.debug("> Removing '{0}' file.".format(path)) os.remove(path) elif os.path.is...
python
{ "resource": "" }
q50333
is_readable
train
def is_readable(path): """ Returns if given path is readable. :param path: Path to check access. :type path: unicode :return: Is path writable. :rtype: bool """ if os.access(path, os.R_OK): LOGGER.debug("> '{0}' path is readable.".format(path)) return True else: ...
python
{ "resource": "" }
q50334
is_writable
train
def is_writable(path): """ Returns if given path is writable. :param path: Path to check access. :type path: unicode :return: Is path writable. :rtype: bool """ if os.access(path, os.W_OK): LOGGER.debug("> '{0}' path is writable.".format(path)) return True else: ...
python
{ "resource": "" }
q50335
is_binary_file
train
def is_binary_file(file): """ Returns if given file is a binary file. :param file: File path. :type file: unicode :return: Is file binary. :rtype: bool """ file_handle = open(file, "rb") try: chunk_size = 1024 while True: chunk = file_handle.read(chunk_s...
python
{ "resource": "" }
q50336
File.cache
train
def cache(self, mode="r", encoding=Constants.default_codec, errors=Constants.codec_error): """ Reads given file content and stores it in the content cache. :param mode: File read mode. :type mode: unicode :param encoding: File encoding codec. :type encoding: unicode ...
python
{ "resource": "" }
q50337
File.uncache
train
def uncache(self): """ Uncaches the cached content. :return: Method success. :rtype: bool """ LOGGER.debug("> Uncaching '{0}' file content.".format(self.__path)) self.__content = [] return True
python
{ "resource": "" }
q50338
File.append
train
def append(self, mode="a", encoding=Constants.default_codec, errors=Constants.codec_error): """ Appends content to defined file. :param mode: File write mode. :type mode: unicode :param encoding: File encoding codec. :type encoding: unicode :param errors: File en...
python
{ "resource": "" }
q50339
File.clear
train
def clear(self, encoding=Constants.default_codec): """ Clears the defined file content. :param encoding: File encoding codec. :type encoding: unicode :return: Method success. :rtype: bool """ if foundations.strings.is_website(self.__path): ra...
python
{ "resource": "" }
q50340
cpp_best_split_full_model
train
def cpp_best_split_full_model(X, Uy, C, S, U, noderange, delta, save_memory=False): """wrappe calling cpp splitting function""" return CSP.best_split_full_model(X, Uy, C, S, U, noderange, delta)
python
{ "resource": "" }
q50341
WsgiApp.error
train
def error(self, status_code, request, message=None): """Handle error response. :param int status_code: :param request: :return: """ status_code_text = HTTP_STATUS_CODES.get(status_code, 'http error') status_error_tag = status_code_text.lower().replace(' ', '_') ...
python
{ "resource": "" }
q50342
Credentials._get_auth
train
def _get_auth(self, force_console=False): """Try to get login auth from known sources.""" if not self.target: raise ValueError("Unspecified target ({!r})".format(self.target)) elif not force_console and self.URL_RE.match(self.target): auth_url = urlparse(self.target) ...
python
{ "resource": "" }
q50343
Credentials._get_auth_from_console
train
def _get_auth_from_console(self, realm): """Prompt for the user and password.""" self.user, self.password = self.AUTH_MEMOIZE_INPUT.get(realm, (self.user, None)) if not self.auth_valid(): if not self.user: login = getpass.getuser() self.user = self._ra...
python
{ "resource": "" }
q50344
Container.provide
train
def provide(self, name): """Gets the value registered with ``name`` and determines whether the value is a provider or a configuration setting. The ``KeyError`` is raised when the ``name`` is not found. The registered value is interpreted as a provider if it's callable. The provi...
python
{ "resource": "" }
q50345
Container.add_provider
train
def add_provider(self, provider, cache, name=None): """Registers a provider on the container. :param provider: Anything that's callable and expects exactly one argument, the :class:`Container` object. :param cache: Whether to cache the return value of the pro...
python
{ "resource": "" }
q50346
copy_content
train
def copy_content(origin, dstPath, blockSize, mode): ''' copy the content of `origin` to `dstPath` in a safe manner. this function will first copy the content to a temporary file and then move it atomically to the requested destination. if some error occurred during content copy or file mov...
python
{ "resource": "" }
q50347
GridRunner.run
train
def run(self): """Run all the test in the test batch """ executed_tests = [] try: active_thread = 0 start_thread = True current_index = 0 active_thread_by_browser_id = {} test_index_by_browser_id = {} for browser_...
python
{ "resource": "" }
q50348
GridRunner.tear_down_instances
train
def tear_down_instances(self): """Tear down all instances """ self.info_log('Tearing down all instances...') for instance in self.alive_instances: instance.tear_down() self.info_log('[Done]Tearing down all instances')
python
{ "resource": "" }
q50349
GridRunner.start_selenium_server
train
def start_selenium_server(self): """Start the selenium server """ ip = BROME_CONFIG['grid_runner']['selenium_server_ip'] port = BROME_CONFIG['grid_runner']['selenium_server_port'] def is_selenium_server_is_running(): s = socket.socket(socket.AF_INET, socket.SOCK_STR...
python
{ "resource": "" }
q50350
BrowserConfig.validate_config
train
def validate_config(self): """Validate that the browser config contains all the needed config """ # LOCALHOST if self.location == 'localhost': if 'browserName' not in self.config.keys(): msg = "Add the 'browserName' in your local_config: e.g.: 'Firefox', 'Chr...
python
{ "resource": "" }
q50351
BrowserConfig.validate_ec2_browser_config
train
def validate_ec2_browser_config(self): """Validate that the ec2 config is conform """ if self.config.get('launch', True): required_keys = [ 'browserName', 'platform', 'ssh_key_path', 'username', 'amiid',...
python
{ "resource": "" }
q50352
Database.load_contents
train
def load_contents(self): """ Loads contents of the tables into database. """ with open(METADATA_FILE) as f: lines = f.readlines() lines = map(lambda x: x.strip(), lines) exclude_strings = ['<begin_table>', '<end_table>'] list_of_databases_and_co...
python
{ "resource": "" }
q50353
Database.store_contents
train
def store_contents(self): """ Stores the contents of tables into file. """ string_buffer = os.linesep.join( map( lambda x: os.linesep.join( ["<begin_table>"] + [x.name] + x.columns + ["<end_table>"] ), se...
python
{ "resource": "" }
q50354
Database.delete_table
train
def delete_table(self, tablename): """ Deletes a table from the database. """ self.tables = filter(lambda x: x.name != tablename, self.tables)
python
{ "resource": "" }
q50355
Database.get_table
train
def get_table(self, tablename): """ Returns the table whoose name is tablename. """ temp = filter(lambda x: x.name == tablename, self.tables) if temp == list(): raise Exception("No such table") return temp[0]
python
{ "resource": "" }
q50356
Table.get_column_list_prefixed
train
def get_column_list_prefixed(self): """ Returns a list of columns """ return map( lambda x: ".".join([self.name, x]), self.columns )
python
{ "resource": "" }
q50357
Table.get_column
train
def get_column(self, column): """ Return the values having of column. """ if "(" in str(column): temp_list = column.split("(") key = temp_list[1].strip("()") func = temp_list[0].lower() else: key = column func = None...
python
{ "resource": "" }
q50358
Table.delete_row
train
def delete_row(self, key, value): """ Deletes the rows where key = value. """ self.rows = filter(lambda x: x.get(key) != value, self.rows)
python
{ "resource": "" }
q50359
Table.invert_delete_row
train
def invert_delete_row(self, key, value): """ Inverts delete_row and returns the rows where key = value """ self.rows = filter(lambda x: x.get(key) == value, self.rows)
python
{ "resource": "" }
q50360
Table.invert_delete_row2
train
def invert_delete_row2(self, key, value): """ Invert of type two where there are two columns given """ self.rows = filter(lambda x: x.get(key) == x.get(value), self.rows)
python
{ "resource": "" }
q50361
Table.load_contents
train
def load_contents(self): """ Loads contents of Database from a filename database.csv. """ with open(self.name + ".csv") as f: list_of_rows = f.readlines() list_of_rows = map( lambda x: x.strip(), map( lambda x: x.replace("\...
python
{ "resource": "" }
q50362
Table.store_contents
train
def store_contents(self): """ Stores contests of the Database into a filename database.csv. """ string_buffer = os.linesep.join( map( lambda x: ",".join(x), map( lambda x: map( str, ...
python
{ "resource": "" }
q50363
Table.print_contents
train
def print_contents(self): """ Prints Contents of Table. """ print "\t\t\t".join(self.columns) temp_list = [] for i in self.columns: temp_list.append(self.get_column(i)) for i in zip(*(temp_list)): print "\t\t\t".join(map(str, i))
python
{ "resource": "" }
q50364
CommentReplyAdmin.formfield_for_foreignkey
train
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Limit canned reply options to those with same site as comment. """ field = super(CommentReplyAdmin, self).\ formfield_for_foreignkey(db_field, request, **kwargs) comment_id = request.GET.get(sel...
python
{ "resource": "" }
q50365
CommentAdmin.queryset
train
def queryset(self, request): """ Exclude replies from listing since they are displayed inline as part of listing. For proxy models with cls apptribute limit comments to those classified as cls. """ qs = super(CommentAdmin, self).queryset(request) qs = qs....
python
{ "resource": "" }
q50366
AdminModeratorMixin.moderate_view
train
def moderate_view(self, request, object_id, extra_context=None): """ Handles moderate object tool through a somewhat hacky changelist view whose queryset is altered via CommentAdmin.get_changelist to only list comments for the object under review. """ opts = self.model._m...
python
{ "resource": "" }
q50367
LocalRunner.run
train
def run(self): """Run the test batch """ self.info_log("The test batch is ready.") self.executed_tests = [] for test in self.tests: localhost_instance = LocalhostInstance( runner=self, browser_config=self.browser_config, ...
python
{ "resource": "" }
q50368
LocalRunner.terminate
train
def terminate(self): """Terminate the test batch """ self.info_log('The test batch is finished.') with DbSessionContext(BROME_CONFIG['database']['mongo_database_name']) as session: # noqa test_batch = session.query(Testbatch)\ .filter(Testbatch.mongo_id == ...
python
{ "resource": "" }
q50369
IDBFile.getpart
train
def getpart(self, ix): """ Returns a fileobject for the specified section. This method optionally decompresses the data found in the .idb file, and returns a file-like object, with seek, read, tell. """ if self.offsets[ix] == 0: return comp...
python
{ "resource": "" }
q50370
BTree.dump
train
def dump(self): """ raw dump of all records in the b-tree """ print("pagesize=%08x, reccount=%08x, pagecount=%08x" % (self.pagesize, self.reccount, self.pagecount)) self.dumpfree() self.dumptree(self.firstindex)
python
{ "resource": "" }
q50371
BTree.dumpfree
train
def dumpfree(self): """ list all free pages """ fmt = "L" if self.version > 15 else "H" hdrsize = 8 if self.version > 15 else 4 pn = self.firstfree if pn == 0: print("no free pages") return while pn: self.fh.seek(pn * self.page...
python
{ "resource": "" }
q50372
BTree.dumpindented
train
def dumpindented(self, pn, indent=0): """ Dump all nodes of the current page with keys indented, showing how the `indent` feature works """ page = self.readpage(pn) print(" " * indent, page) if page.isindex(): print(" " * indent, end="") ...
python
{ "resource": "" }
q50373
BTree.dumptree
train
def dumptree(self, pn): """ Walks entire tree, dumping all records on each page in sequential order """ page = self.readpage(pn) print("%06x: preceeding = %06x, reccount = %04x" % (pn, page.preceeding, page.count)) for ent in page.index: print(...
python
{ "resource": "" }
q50374
BTree.pagedump
train
def pagedump(self): """ dump the contents of all pages, ignoring links between pages, this will enable you to view contents of pages which have become lost due to datacorruption. """ self.fh.seek(self.pagesize) pn = 1 while True: try: ...
python
{ "resource": "" }
q50375
ID0File.prettykey
train
def prettykey(self, key): """ returns the key in a readable format. """ f = list(self.decodekey(key)) f[0] = f[0].decode('utf-8') if len(f) > 2 and type(f[2]) == bytes: f[2] = f[2].decode('utf-8') if f[0] == '.': if len(f) == 2: ...
python
{ "resource": "" }
q50376
ID0File.prettyval
train
def prettyval(self, val): """ returns the value in a readable format. """ if len(val) == self.wordsize and val[-1:] in (b'\x00', b'\xff'): return "%x" % struct.unpack("<" + self.fmt, val) if len(val) == self.wordsize and re.search(b'[\x00-\x08\x0b\x0c\x0e-\x1f]'...
python
{ "resource": "" }
q50377
ID0File.nodeByName
train
def nodeByName(self, name): """ Return a nodeid by name """ # note: really long names are encoded differently: # 'N'+'\x00'+pack('Q', nameid) => ofs # and (ofs, 'N') -> nameid # at nodebase ( 0xFF000000, 'S', 0x100*nameid ) there is a series of blobs for max 0x80000 s...
python
{ "resource": "" }
q50378
ID0File.makekey
train
def makekey(self, *args): """ return a binary key for the nodeid, tag and optional value """ if len(args) > 1: args = args[:1] + (args[1].encode('utf-8'),) + args[2:] if len(args) == 3 and type(args[-1]) == str: # node.tag.string type keys return struct....
python
{ "resource": "" }
q50379
ID0File.bytes
train
def bytes(self, *args): """ return a raw value for the given arguments """ if len(args) == 1 and isinstance(args[0], BTree.Cursor): cur = args[0] else: cur = self.btree.find('eq', self.makekey(*args)) if cur: return cur.getval()
python
{ "resource": "" }
q50380
ID0File.string
train
def string(self, *args): """ return string stored in node """ data = self.bytes(*args) if data is not None: return data.rstrip(b"\x00").decode('utf-8')
python
{ "resource": "" }
q50381
ID0File.name
train
def name(self, id): """ resolves a name, both short and long names. """ data = self.bytes(id, 'N') if not data: print("%x has no name" % id) return if data[:1] == b'\x00': nameid, = struct.unpack_from(">" + self.fmt, data, 1) ...
python
{ "resource": "" }
q50382
ID0File.blob
train
def blob(self, nodeid, tag, start=0, end=0xFFFFFFFF): """ Blobs are stored in sequential nodes with increasing index values. most blobs, like scripts start at index 0, long names start at a specified offset. """ startkey = self.makekey(nodeid, ...
python
{ "resource": "" }
q50383
ID1File.dump
train
def dump(self): """ print first and last bits for each segment """ for seg in self.seglist: print("==== %08x-%08x" % (seg.startea, seg.endea)) if seg.endea - seg.startea < 30: for ea in range(seg.startea, seg.endea): print(" %08x: %08x...
python
{ "resource": "" }
q50384
ID1File.find_segment
train
def find_segment(self, ea): """ do a linear search for the given address in the segment list """ for seg in self.seglist: if seg.startea <= ea < seg.endea: return seg
python
{ "resource": "" }
q50385
_num_vowel_to_acc
train
def _num_vowel_to_acc(vowel, tone): """Convert a numbered vowel to an accented vowel.""" try: return VOWEL_MAP[vowel + str(tone)] except IndexError: raise ValueError("Vowel must be one of '{}' and tone must be a tone.".format(VOWELS))
python
{ "resource": "" }
q50386
numbered_syllable_to_accented
train
def numbered_syllable_to_accented(syllable): """Convert a numbered pinyin syllable to an accented pinyin syllable. Implements the following algorithm, modified from https://github.com/tsroten/zhon: 1. If the syllable has an 'a' or 'e', put the tone over that vowel. 2. If the syllable has 'ou', ...
python
{ "resource": "" }
q50387
_LogRecord_msg
train
def _LogRecord_msg(): """ Overrides logging.LogRecord.msg attribute to ensure variable content is stored as unicode. """ def _LogRecord_msgProperty(self): return self.__msg def _LogRecord_msgSetter(self, value): self.__msg = to_unicode(value) logging.LogRecord.msg = property(_...
python
{ "resource": "" }
q50388
install_logger
train
def install_logger(logger=None, module=None): """ Installs given logger in given module or default logger in caller introspected module. :param logger: Logger to install. :type logger: Logger :param module: Module. :type module: ModuleType :return: Logger. :rtype: Logger """ lo...
python
{ "resource": "" }
q50389
uninstall_logger
train
def uninstall_logger(logger=None, module=None): """ Uninstalls given logger in given module or default logger in caller introspected module. :param logger: Logger to uninstall. :type logger: Logger :param module: Module. :type module: ModuleType :return: Definition success. :rtype: bool...
python
{ "resource": "" }
q50390
get_logging_console_handler
train
def get_logging_console_handler(logger=None, formatter=LOGGING_DEFAULT_FORMATTER): """ Adds a logging console handler to given logger or default logger. :param logger: Logger to add the handler to. :type logger: Logger :param formatter: Handler formatter. :type formatter: Formatter :return:...
python
{ "resource": "" }
q50391
get_logging_file_handler
train
def get_logging_file_handler(logger=None, file=None, formatter=LOGGING_DEFAULT_FORMATTER): """ Adds a logging file handler to given logger or default logger using given file. :param logger: Logger to add the handler to. :type logger: Logger :param file: File to verbose into. :type file: unicode...
python
{ "resource": "" }
q50392
get_logging_stream_handler
train
def get_logging_stream_handler(logger=None, formatter=LOGGING_DEFAULT_FORMATTER): """ Adds a logging stream handler to given logger or default logger using given file. :param logger: Logger to add the handler to. :type logger: Logger :param file: File to verbose into. :type file: unicode :p...
python
{ "resource": "" }
q50393
remove_logging_handler
train
def remove_logging_handler(handler, logger=None): """ Removes given logging handler from given logger. :param handler: Handler. :type handler: Handler :param logger: Handler logger. :type logger: Logger :return: Definition success. :rtype: bool """ logger = LOGGER if logger is ...
python
{ "resource": "" }
q50394
set_verbosity_level
train
def set_verbosity_level(verbosity_level=3, logger=None): """ Defines logging verbosity level. Available verbosity levels:: 0: Critical. 1: Error. 2: Warning. 3: Info. 4: Debug. :param verbosity_level: Verbosity level. :type verbosity_level: int :param l...
python
{ "resource": "" }
q50395
StandardOutputStreamer.write
train
def write(self, message): """ Writes given message to logger handlers. :param message: Message. :type message: unicode :return: Method success. :rtype: bool """ for handler in self.__logger.__dict__["handlers"]: handler.stream.write(message) ...
python
{ "resource": "" }
q50396
SqliteObject._do_write
train
def _do_write(self): """ Check commit counter and do a commit if need be """ with self.lock: self._commit_counter += 1 if self._commit_counter >= self._commit_every: self._db.commit() self._commit_counter = 0
python
{ "resource": "" }
q50397
register_type
train
def register_type(env_type, alias=None): """Registers environment type. :param str|unicode|Environment env_type: Environment type or its alias (for already registered types). :param str|unicode alias: Alias to register type under. If not set type name is used. :rtype: Environment """ ...
python
{ "resource": "" }
q50398
watch._close
train
def _close(self, fd): """ Close the descriptor used for a path regardless of mode. """ if self._mode == WF_INOTIFYX: try: pynotifyx.rm_watch(self._inx_fd, fd) except: pass else: try: os.close(fd) except: pass
python
{ "resource": "" }
q50399
watch._self_pipe
train
def _self_pipe(self): """ This sets up a self-pipe so we can hand back an fd to the caller allowing the object to manage event triggers. The ends of the pipe are set non-blocking so it doesn't really matter if a bunch of events fill the pipe buffer. """ import fcntl ...
python
{ "resource": "" }