Python get entry
60 Python code examples are found related to "
get entry".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: ContainerNode.py From Cura with GNU Lesser General Public License v3.0 | 7 votes |
def getMetaDataEntry(self, entry: str, default: Any = None) -> Any: """Get an entry from the metadata of the container that this node contains. This is just a convenience function. :param entry: The metadata entry key to return. :param default: If the metadata is not present or the container is not found, the value of this default is returned. :return: The value of the metadata entry, or the default if it was not present. """ container_metadata = ContainerRegistry.getInstance().findContainersMetadata(id = self.container_id) if len(container_metadata) == 0: return default return container_metadata[0].get(entry, default)
Example 2
Source File: data_utils.py From DOTA_models with Apache License 2.0 | 6 votes |
def get_max_entry(a): e = {} for w in a: if (w != "UNK, "): if (e.has_key(w)): e[w] += 1 else: e[w] = 1 if (len(e) > 0): (key, val) = sorted(e.items(), key=lambda x: -1 * x[1])[0] if (val > 1): return key else: return -1.0 else: return -1.0
Example 3
Source File: csHelpers.py From LightNet with MIT License | 6 votes |
def getColorEntry(val, args): if not args.colorized: return "" if not isinstance(val, float) or math.isnan(val): return colors.ENDC if (val < .20): return colors.RED elif (val < .40): return colors.YELLOW elif (val < .60): return colors.BLUE elif (val < .80): return colors.CYAN else: return colors.GREEN # Cityscapes files have a typical filename structure # <city>_<sequenceNb>_<frameNb>_<type>[_<type2>].<ext> # This class contains the individual elements as members # For the sequence and frame number, the strings are returned, including leading zeros
Example 4
Source File: uds.py From scapy with GNU General Public License v2.0 | 6 votes |
def getTableEntry(tup): """ Helping function for make_lined_table. Returns the session and response code of tup. Args: tup: tuple with session and UDS response package Example: make_lined_table([('DefaultSession', UDS()/UDS_SAPR(), 'ExtendedDiagnosticSession', UDS()/UDS_IOCBI())], getTableEntry) """ session, pkt = tup if pkt.service == 0x7f: return (session, "0x%02x: %s" % (pkt.requestServiceId, pkt.sprintf("%UDS_NR.requestServiceId%")), pkt.sprintf("%UDS_NR.negativeResponseCode%")) else: return (session, "0x%02x: %s" % (pkt.service & ~0x40, pkt.get_field('service'). i2s[pkt.service & ~0x40]), "PositiveResponse")
Example 5
Source File: changelog.py From clonedigger with GNU General Public License v3.0 | 6 votes |
def get_entry(self, version='', create=None): """ return a given changelog entry if version is omited, return the current entry """ if not self.entries: if version or not create: raise NoEntry() self.entries.append(self.entry_class()) if not version: if self.entries[0].version and create is not None: self.entries.insert(0, self.entry_class()) return self.entries[0] version = self.version_class(version) for entry in self.entries: if entry.version == version: return entry raise EntryNotFound()
Example 6
Source File: gather_info_functions.py From ChaosTestingCode with MIT License | 6 votes |
def get_last_confirmed_entry(topic, attempt=1): broker = get_live_broker() bash_command = f"bash ../cluster/find-last-bk-entry.sh {broker} {topic}" process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE) output, error = process.communicate() lac_line = output.decode('ascii').replace('\n', '') print(f"LCE. broker {broker} lac_line {lac_line}") if "No such container" in lac_line or not lac_line: # most likely, zk has a stale view on the world, let it catch up and try once more if attempt > 3: print("live broker is not really live. Aborting test") else: time.sleep(5) attempt += 1 return get_last_confirmed_entry(topic, attempt) entry = int(lac_line.split(":")[1].replace("\"", "").replace(",", "")) first = int(lac_line.split(":")[0].replace("\"", "")) return [first, entry]
Example 7
Source File: ContainerStack.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
def getMetaDataEntry(self, entry: str, default: Any = None) -> Any: """:copydoc ContainerInterface::getMetaDataEntry Reimplemented from ContainerInterface """ value = self._metadata.get(entry, None) if value is None: for container in self._containers: value = container.getMetaDataEntry(entry, None) if value is not None: break if value is None: return default else: return value
Example 8
Source File: ParserATNSimulator.py From FATE with Apache License 2.0 | 6 votes |
def getAltThatFinishedDecisionEntryRule(self, configs:ATNConfigSet): alts = set() for c in configs: if c.reachesIntoOuterContext>0 or (isinstance(c.state, RuleStopState) and c.context.hasEmptyPath() ): alts.add(c.alt) if len(alts)==0: return ATN.INVALID_ALT_NUMBER else: return min(alts) # Walk the list of configurations and split them according to # those that have preds evaluating to true/false. If no pred, assume # true pred and include in succeeded set. Returns Pair of sets. # # Create a new set so as not to alter the incoming parameter. # # Assumption: the input stream has been restored to the starting point # prediction, which is where predicates need to evaluate. #
Example 9
Source File: models.py From opensurfaces with MIT License | 6 votes |
def get_entry_dict(self): """ Return a dictionary of this model containing just the fields needed for javascript rendering. """ # generating thumbnail URLs is slow, so only generate the ones # that will definitely be used. return { 'id': self.id, 'fov': self.fov, 'aspect_ratio': self.aspect_ratio, 'image': { #'200': self.image_200.url, #'300': self.image_300.url, #'512': self.image_512.url, '1024': self.image_1024.url, '2048': self.image_2048.url, 'orig': self.image_orig.url, } }
Example 10
Source File: mal.py From mangaki with GNU Affero General Public License v3.0 | 6 votes |
def get_entry_from_work(self, work: Work) -> MALEntry: """ Using a mangaki.models.Work to fetch the first (potential) matching MALEntry through MAL Search API. WARNING: it is not guaranteed that MAL Search API will return the *good* work (i.e. could be same series, another season, specials, movie, or yet another Japanese invention.) Also, will fail on unsupported MALWorks (read the Enum definition to see what is supported). :param work: The work to search from (`work.category.slug` and `work.title` will be used) :type work: `mangaki.models.Work` :return: the first matching entry from MAL :rtype: MALEntry """ return self.search_work( MALWorks(work.category.slug), work.title )
Example 11
Source File: search.py From palanaeum with GNU Affero General Public License v3.0 | 6 votes |
def get_entry_ids(self) -> frozenset: """ Find entries that have at least one tag that we're looking for. Every tag gives +1 search rank. Tags are powerful! """ results = defaultdict(int) cache_key = "search_tag_{}" for tag in self.tags: entries_with_tag = SEARCH_CACHE.get(cache_key.format(tag)) if not entries_with_tag: entries_with_tag = EntryVersion.newest.filter(tags=tag).values_list('entry_id', flat=True) SEARCH_CACHE.set(cache_key.format(tag), entries_with_tag, SEARCH_CACHE_TTL) for entry_id in entries_with_tag: results[entry_id] += 1 return frozenset(results.items())
Example 12
Source File: import3031.py From community-edition-setup with MIT License | 6 votes |
def getOldEntryMap(self): files = os.listdir(self.ldifDir) dnMap = {} # get the new admin DN admin_ldif = '/install/community-edition-setup/output/people.ldif' admin_dn = self.getDns(admin_ldif)[0] for fn in files: dnList = self.getDns(os.path.join(self.ldifDir, fn)) for dn in dnList: # skip the entry of Admin DN if fn == 'people.ldif' and admin_dn in dn: continue dnMap[dn] = fn return dnMap
Example 13
Source File: EWSv2.py From content with MIT License | 6 votes |
def get_entry_for_object(title, context_key, obj, headers=None): if len(obj) == 0: return "There is no output results" obj = filter_dict_null(obj) if isinstance(obj, list): obj = map(filter_dict_null, obj) if headers and isinstance(obj, dict): headers = list(set(headers).intersection(set(obj.keys()))) return { 'Type': entryTypes['note'], 'Contents': obj, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(title, obj, headers), ENTRY_CONTEXT: { context_key: obj } }
Example 14
Source File: QRadar_5_4_9.py From content with MIT License | 6 votes |
def get_entry_for_assets(title, obj, contents, human_readable_obj, headers=None): if len(obj) == 0: return "There is no output result" obj = filter_dict_null(obj) human_readable_obj = filter_dict_null(human_readable_obj) if headers: if isinstance(headers, str): headers = headers.split(',') headers = list(filter(lambda x: x in headers, list_entry) for list_entry in human_readable_obj) human_readable_md = '' for k, h_obj in human_readable_obj.iteritems(): human_readable_md = human_readable_md + tableToMarkdown(k, h_obj, headers) return { 'Type': entryTypes['note'], 'Contents': contents, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': "### {0}\n{1}".format(title, human_readable_md), 'EntryContext': obj }
Example 15
Source File: EWSO365.py From content with MIT License | 6 votes |
def get_entry_for_item_attachment(item_id, attachment, target_email): """ Creates a note entry for an item attachment :param item_id: Item id :param attachment: exchangelib attachment :param target_email: target email :return: note entry dict for item attachment """ item = attachment.item dict_result = parse_attachment_as_dict(item_id, attachment) dict_result.update( parse_item_as_dict(item, target_email, camel_case=True, compact_fields=True) ) title = f'EWS get attachment got item for "{target_email}", "{get_attachment_name(attachment.name)}"' return get_entry_for_object( title, CONTEXT_UPDATE_EWS_ITEM_FOR_ATTACHMENT + CONTEXT_UPDATE_ITEM_ATTACHMENT, dict_result, )
Example 16
Source File: cache.py From dawgmon with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_entry_timestamp(self, entry_id, hostname="localhost"): entries = self.get_entries(hostname) if len(entries) == 0: return None if entry_id == -1: # default to the last entry entry_id = entries[-1]["id"] elif entry_id >= len(self.data[hostname]): return None # fall back automatically on timestamps that do not record # subsecond intervals such as the timestamps that are in old # caches ts = self.data[hostname][entry_id]["timestamp"] try: return str_to_ts(ts) except ValueError: return str_to_ts(ts, False)
Example 17
Source File: update_kubeconfig.py From bash-lambda-layer with MIT License | 6 votes |
def get_cluster_entry(self): """ Return a cluster entry generated using the previously obtained description. """ cert_data = self._get_cluster_description().get("certificateAuthority", {"data": ""})["data"] endpoint = self._get_cluster_description().get("endpoint") arn = self._get_cluster_description().get("arn") return OrderedDict([ ("cluster", OrderedDict([ ("certificate-authority-data", cert_data), ("server", endpoint) ])), ("name", arn) ])
Example 18
Source File: variabilityops.py From anvio with GNU General Public License v3.0 | 6 votes |
def get_formatted_consensus_sequence_entry(self, key, sample_name, sequence_name): """Gets a sample name and gene callers id, returns a well-formatted dict for sequence entry using the `self.sequence_variants_in_samples_dict`. `key` must be unique string identifier.""" F = self.sequence_variants_in_samples_dict[sample_name][sequence_name] return {'key': key, 'sample_name': sample_name, self.sequence_name_key: sequence_name, 'num_changes': F['num_changes'], 'in_pos_0': F['in_pos_0'], 'in_pos_1': F['in_pos_1'], 'in_pos_2': F['in_pos_2'], 'in_pos_3': F['in_pos_3'], 'sequence': ''.join(F['sequence_as_list'])}
Example 19
Source File: xcom_endpoint.py From airflow with Apache License 2.0 | 6 votes |
def get_xcom_entry( dag_id: str, task_id: str, dag_run_id: str, xcom_key: str, session: Session ) -> XComCollectionItemSchema: """ Get an XCom entry """ query = session.query(XCom) query = query.filter(and_(XCom.dag_id == dag_id, XCom.task_id == task_id, XCom.key == xcom_key)) query = query.join(DR, and_(XCom.dag_id == DR.dag_id, XCom.execution_date == DR.execution_date)) query = query.filter(DR.run_id == dag_run_id) query_object = query.one_or_none() if not query_object: raise NotFound("XCom entry not found") return xcom_collection_item_schema.dump(query_object)
Example 20
Source File: create_GTF_from_database.py From TALON with MIT License | 6 votes |
def get_gene_GTF_entry(gene_ID, associated_transcript_tuples, annotation_dict): """ Creates a GTF annotation entry for the given gene """ if "source" in annotation_dict: source = annotation_dict["source"] else: source = "TALON" # GTF fields chromosome = associated_transcript_tuples[0]["chromosome"] feature = "gene" start = str(associated_transcript_tuples[0]["min_pos"]) end = str(associated_transcript_tuples[-1]["max_pos"]) score = "." strand = associated_transcript_tuples[0]["strand"] frame = "." attributes = " ".join(format_GTF_tag_values_for_gene(gene_ID, annotation_dict)) GTF = '\t'.join([chromosome, source, feature, start, end, score, strand, frame, attributes]) return GTF
Example 21
Source File: cfb.py From pyaaf2 with MIT License | 6 votes |
def get_entry_path(root, entry, max_depth): parent = None node = root count = 0 path = [] while node is not None and count < max_depth: path.append(node) if node is entry: break direction = 0 if entry < node else 1 parent = node node = node[direction] count += 1 return path
Example 22
Source File: wallet_common.py From dash-masternode-tool with MIT License | 6 votes |
def get_child_entry(self, index) -> 'Bip44Entry': child = self.child_entries.get(index) if not child: key = self.get_bip32key() child_key = key.ChildKey(index) child_xpub = child_key.ExtendedKey(False, True) if self.bip32_path: bip32_path_n = bip32_path_string_to_n(self.bip32_path) bip32_path_n.append(index) bip32_path = bip32_path_n_to_string(bip32_path_n) else: raise Exception('Unknown BIP32 path of the parrent') child = Bip44Entry(tree_id=self.tree_id, id=None, parent=self, xpub=child_xpub, address_index=index, bip32_path=bip32_path, bip32_key=child_key) self.child_entries[index] = child return child
Example 23
Source File: freebusy.py From ccs-calendarserver with Apache License 2.0 | 6 votes |
def getCacheEntry(cls, calresource, useruid, timerange): key = str(calresource.id()) + "/" + useruid token = (yield calresource.syncToken()) entry = (yield cls.fbcacher.get(key)) if entry: # Offset one day at either end to account for floating entry_timerange = Period.parseText(entry.timerange) cached_start = entry_timerange.getStart() + Duration(days=cls.CACHE_DAYS_FLOATING_ADJUST) cached_end = entry_timerange.getEnd() - Duration(days=cls.CACHE_DAYS_FLOATING_ADJUST) # Verify that the requested time range lies within the cache time range if compareDateTime(timerange.getEnd(), cached_end) <= 0 and compareDateTime(timerange.getStart(), cached_start) >= 0: # Verify that cached entry is still valid if token == entry.token: returnValue(entry.fbresults) returnValue(None)
Example 24
Source File: facade.py From GloboNetworkAPI with Apache License 2.0 | 6 votes |
def get_route_map_entry_by_ids(obj_ids): """Return RouteMapEntry list by ids. Args: obj_ids: List of Ids of RouteMapEntry's. """ ids = list() for obj_id in obj_ids: try: obj = get_route_map_entry_by_id(obj_id).id ids.append(obj) except RouteMapEntryDoesNotExistException as e: raise ObjectDoesNotExistException(str(e)) except Exception as e: raise NetworkAPIException(str(e)) return RouteMapEntry.objects.filter(id__in=ids)
Example 25
Source File: ififuncs.py From IFIscripts with MIT License | 6 votes |
def get_object_entry(): ''' Asks user for an Object Entry number. A valid Object Entry (OE####) must be provided. ''' object_entry = False while object_entry is False: object_entry = input( '\n\n**** Please enter the object entry number of the representation\n\n' ) if object_entry[:4] == 'scoe': return object_entry if object_entry[:2] != 'oe': print(' - First two characters must be \'oe\' and last four characters must be four digits') object_entry = False elif len(object_entry[2:]) not in range(4, 6): object_entry = False print(' - First two characters must be \'oe\' and last four characters must be four digits') elif not object_entry[2:].isdigit(): object_entry = False print(' - First two characters must be \'oe\' and last four characters must be four digits') else: return object_entry
Example 26
Source File: collection.py From QCPortal with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_entry(self, name: str) -> Any: """Obtains a record from the Dataset Parameters ---------- name : str The record name to pull from. Returns ------- Record The requested record """ try: return self.data.records[name.lower()] except KeyError: raise KeyError(f"Could not find entry name '{name}' in the dataset.")
Example 27
Source File: symboltable.py From zxbasic with GNU General Public License v3.0 | 6 votes |
def get_entry(self, id_: str, scope=None): """ Returns the ID entry stored in self.table, starting by the first one. Returns None if not found. If scope is not None, only the given scope is searched. """ if id_[-1] in DEPRECATED_SUFFIXES: id_ = id_[:-1] # Remove it if scope is not None: assert len(self.table) > scope return self[scope][id_] for sc in self: if sc[id_] is not None: return sc[id_] return None # Not found
Example 28
Source File: cache_manager.py From pybel with MIT License | 6 votes |
def get_namespace_entry(self, url: str, name: str) -> Optional[NamespaceEntry]: """Get a given NamespaceEntry object. :param url: The url of the namespace source :param name: The value of the namespace from the given url's document """ entry_filter = and_(Namespace.url == url, NamespaceEntry.name == name) result = self.session.query(NamespaceEntry).join(Namespace).filter(entry_filter).all() if 0 == len(result): return if 1 < len(result): logger.warning( 'result for get_namespace_entry is too long. Returning first of %s', [str(r) for r in result], ) return result[0]
Example 29
Source File: cache_manager.py From pybel with MIT License | 6 votes |
def get_or_create_regex_namespace_entry(self, *, pattern: str, concept: Entity) -> NamespaceEntry: """Get a namespace entry from a regular expression. Need to commit after! :param pattern: The regular expression pattern for the namespace :param concept: The prefix/identifier/name triple """ namespace = self.ensure_regex_namespace(concept.namespace, pattern) n_filter = and_(Namespace.pattern == pattern, NamespaceEntry.name == concept.name) namespace_entry = self.session.query(NamespaceEntry).join(Namespace).filter(n_filter).one_or_none() if namespace_entry is None: namespace_entry = NamespaceEntry( namespace=namespace, name=concept.name, identifier=concept.identifier, ) self.session.add(namespace_entry) return namespace_entry
Example 30
Source File: writemdict.py From writemdict with MIT License | 6 votes |
def get_index_entry(self): # Returns a bytes object, containing the header data for this block if self._version == "2.0": long_format = b">Q" short_format = b">H" else: long_format = b">L" short_format = b">B" return ( struct.pack(long_format, self._num_entries) + struct.pack(short_format, self._first_key_len) + self._first_key + struct.pack(short_format, self._last_key_len) + self._last_key + struct.pack(long_format, self._comp_size) + struct.pack(long_format, self._decomp_size) )
Example 31
Source File: mongo_core.py From cachier with MIT License | 6 votes |
def get_entry_by_key(self, key): res = self.mongo_collection.find_one({ 'func': _MongoCore._get_func_str(self.func), 'key': key }) if res: try: entry = { 'value': pickle.loads(res['value']), 'time': res.get('time', None), 'stale': res.get('stale', False), 'being_calculated': res.get('being_calculated', False) } except KeyError: entry = { 'value': None, 'time': res.get('time', None), 'stale': res.get('stale', False), 'being_calculated': res.get('being_calculated', False) } return key, entry return key, None
Example 32
Source File: mdaio.py From spikeextractors with MIT License | 6 votes |
def get_num_bytes_per_entry_from_dt(dt): if dt == 'uint8': return 1 if dt == 'float32': return 4 if dt == 'int16': return 2 if dt == 'int32': return 4 if dt == 'uint16': return 2 if dt == 'float64': return 8 if dt == 'uint32': return 4 return None
Example 33
Source File: oc_obj.py From ansible-redhat_openshift_utils with Apache License 2.0 | 6 votes |
def get_entry(data, key, sep='.'): ''' Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c ''' if key == '': pass elif (not (key and Yedit.valid_key(key, sep)) and isinstance(data, (list, dict))): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes: if dict_key and isinstance(data, dict): data = data.get(dict_key) elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: return None return data
Example 34
Source File: visualize_causal.py From indra with BSD 2-Clause "Simplified" License | 6 votes |
def get_entry_compact_text_repr(entry, entries): """If the entry has a text value, return that. If the entry has a source_from value, return the text value of the source. Otherwise, return None.""" text = get_shortest_text_value(entry) if text is not None: return text else: sources = get_sourced_from(entry) # There are a lot of references to this entity, each of which refer # to it by a different text label. For the sake of visualization, # let's pick one of these labels (in this case, the shortest one) if sources is not None: texts = [] for source in sources: source_entry = entries[source] texts.append(get_shortest_text_value(source_entry)) return get_shortest_string(texts)
Example 35
Source File: hgnc_client.py From indra with BSD 2-Clause "Simplified" License | 6 votes |
def get_hgnc_entry(hgnc_id): """Return the HGNC entry for the given HGNC ID from the web service. Parameters ---------- hgnc_id : str The HGNC ID to be converted. Returns ------- xml_tree : ElementTree The XML ElementTree corresponding to the entry for the given HGNC ID. """ url = hgnc_url + 'hgnc_id/%s' % hgnc_id headers = {'Accept': '*/*'} res = requests.get(url, headers=headers) if not res.status_code == 200: return None xml_tree = ET.XML(res.content, parser=UTB()) return xml_tree
Example 36
Source File: chebi_client.py From indra with BSD 2-Clause "Simplified" License | 6 votes |
def get_chebi_entry_from_web(chebi_id): """Return a ChEBI entry corresponding to a given ChEBI ID using a REST API. Parameters ---------- chebi_id : str The ChEBI ID whose entry is to be returned. Returns ------- xml.etree.ElementTree.Element An ElementTree element representing the ChEBI entry. """ url_base = 'http://www.ebi.ac.uk/webservices/chebi/2.0/test/' url_fmt = url_base + 'getCompleteEntity?chebiId=%s' resp = requests.get(url_fmt % chebi_id) if resp.status_code != 200: logger.warning("Got bad code form CHEBI client: %s" % resp.status_code) return None tree = etree.fromstring(resp.content) path = 'n:Body/c:getCompleteEntityResponse/c:return' elem = tree.find(path, namespaces=chebi_xml_ns) return elem
Example 37
Source File: request_history.py From Requester with MIT License | 6 votes |
def get_entry_parts(self, req): """Display request and other properties for each entry. """ tabname = req[1].get('tabname', None) meta = req[1].get('meta', None) header = '{}{}: {}'.format( req[1]['method'].upper(), ' ({})'.format(meta) if meta else '', req[1]['url'] ) if tabname: header = '{} - {}'.format(tabname, header) try: # in case, e.g., schema has changed seconds = time() - req[1]['ts'] pad = chr(8203) * min(round(pow(round(seconds / 60), 0.4)), 150) return [ pad + truncate(header, 100), approximate_age(req[1]['ts']), str(req[1]['code']), req[1]['file'] or '?', ] except: return None
Example 38
Source File: entry_points.py From ros2cli with Apache License 2.0 | 6 votes |
def get_all_entry_points(): """ Get all entry points related to ``ros2cli`` and any of its extensions. :returns: mapping of entry point names to ``EntryPoint`` instances :rtype: dict """ extension_points = get_entry_points(EXTENSION_POINT_GROUP_NAME) entry_points = defaultdict(dict) for dist in importlib_metadata.distributions(): for ep in dist.entry_points: # skip groups which are not registered as extension points if ep.group not in extension_points: continue entry_points[ep.group][ep.name] = (dist, ep) return entry_points
Example 39
Source File: backup.py From upribox with GNU General Public License v3.0 | 6 votes |
def get_entry(extra, id, format): """Searches for a specific extra field inside the extra value of the ZipInfo.""" # make bytesequence mutable array = bytearray(extra) try: # while extra value is not empty while len(array) > 0: # extract first extra field id and length entry_id, length = struct.unpack("<HH" + "x" * (len(array) - EXTRA_HEADER_LENGTH), array) # if desired extra field has not been found if entry_id != id: # remove the extra field bytes from the bytearray del array[:length + EXTRA_HEADER_LENGTH] else: # unpack and return values of desired extra field return struct.unpack(format, array) except struct.error: return None
Example 40
Source File: playlist.py From rhinobot_heroku with MIT License | 6 votes |
def get_next_entry(self, predownload_next=True): """ A coroutine which will return the next song or None if no songs left to play. Additionally, if predownload_next is set to True, it will attempt to download the next song to be played - so that it's ready by the time we get to it. """ if not self.entries: return None entry = self.entries.popleft() if predownload_next: next_entry = self.peek() if next_entry: next_entry.get_ready_future() return await entry.get_ready_future()
Example 41
Source File: tbentries.py From open-context-py with GNU General Public License v3.0 | 6 votes |
def get_page_range_from_tb_entry_label(self, label): """ gets the page range from an trench book entry label """ p_range = [] if ':' in label and ';' in label: l_ex_a = label.split(':') p_part = l_ex_a[1] if ';' in p_part: p_part_ex = p_part.split(';') pages = p_part_ex[0] if '-' in pages: pages_ex = pages.split('-') else: pages_ex = [pages] for page_str in pages_ex: page = None try: page = int(float(page_str)) except: page = None if page is not None: p_range.append(page) return p_range
Example 42
Source File: functions.py From protwis with Apache License 2.0 | 6 votes |
def get_uniprot_entry_name (self, up_id): #get the 'entry name' field for given uniprot id #'entry name' is a protein id in gpcrdb url = "http://www.uniprot.org/uniprot/?query=accession:%s&columns=entry name&format=tab" %up_id #used urllib, urllib2 throws an error here for some reason try: response = urllib.urlopen(url) page = response.readlines() return page[1].strip().lower() except urllib.HTTPError as error: print(error) return '' #============================================================================== #stores information about alignments and b-w numbers
Example 43
Source File: waveconverter_gui.py From waveconverter with MIT License | 6 votes |
def getListFromEntry(self, widgetName): tempWidget = self.builder.get_object(widgetName) listString = tempWidget.get_text().strip('[]') # resolves to string of comma-separated values listItemsText = listString.split(',') tempList = [] # first check if we have an empty list if not listItemsText or listItemsText == ['']: return [] # otherwise build the list and return it for item in listItemsText: tempList.append(int(item)) return tempList #def setIntToEntry(self, widgetName, value): # tempWidget = self.builder.get_object(widgetName) # Gtk.Entry.set_text(tempWidget, str(value)) #def setFloatToEntry(self, widgetName, value): # tempWidget = self.builder.get_object(widgetName) # Gtk.Entry.set_text(tempWidget, str(value))
Example 44
Source File: apt_inputs.py From mirage with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_entry(dict, entry_number): """Return a numbered entry from a dictionary that corresponds to the observataion_list.yaml. Parameters ---------- dict entry_number Returns ------- """ entry_key = 'EntryNumber{}'.format(entry_number) for key, observation in dict.items(): if entry_key in observation.keys(): return observation[entry_key]
Example 45
Source File: elf.py From pwnypack with MIT License | 6 votes |
def get_dynamic_section_entry(self, index): """ Get a specific .dynamic section entry by index. Args: symbol(int): The index of the .dynamic section entry to return. Returns: ELF.DynamicSectionEntry: The .dynamic section entry. Raises: KeyError: The requested entry does not exist. """ self._ensure_dynamic_section_loaded() return self._dynamic_section_entries[index]
Example 46
Source File: find_disks.py From kolla with Apache License 2.0 | 6 votes |
def get_id_part_entry_name(dev, use_udev): if use_udev: dev_name = dev.get('ID_PART_ENTRY_NAME', '') else: part = re.sub(r'.*[^\d]', '', dev.device_node) parent = dev.find_parent('block').device_node # NOTE(Mech422): Need to use -i as -p truncates the partition name out = subprocess.Popen(['/usr/sbin/sgdisk', '-i', part, # nosec parent], stdout=subprocess.PIPE).communicate() match = re.search(r'Partition name: \'(\w+)\'', out[0]) if match: dev_name = match.group(1) else: dev_name = '' return dev_name
Example 47
Source File: X86.py From deprecated-binaryninja-python with GNU General Public License v2.0 | 6 votes |
def get_size_for_sse_entry_type(state, type): if type == "sse_16": return 2 if type == "sse_32": return 4 if type == "mmx_32": return 4 if type == "sse_64": return 8 if type == "mmx_64": return 8 if type == "gpr_32_or_64": if state.final_op_size == 8: return 8 else: return 4 return 16
Example 48
Source File: __init__.py From fava with MIT License | 6 votes |
def get_entry(self, entry_hash: str) -> Directive: """Find an entry. Arguments: entry_hash: Hash of the entry. Returns: The entry with the given hash. Raises: FavaAPIException: If there is no entry for the given hash. """ try: return next( entry for entry in self.all_entries if entry_hash == hash_entry(entry) ) except StopIteration: raise FavaAPIException(f'No entry found for hash "{entry_hash}"')
Example 49
Source File: file.py From fava with MIT License | 6 votes |
def get_entry_slice(entry: Directive) -> Tuple[str, str]: """Get slice of the source file for an entry. Args: entry: An entry. Returns: A string containing the lines of the entry and the `sha256sum` of these lines. """ with open(entry.meta["filename"], mode="r", encoding="utf-8") as file: lines = file.readlines() entry_lines = find_entry_lines(lines, entry.meta["lineno"] - 1) entry_source = "".join(entry_lines).rstrip("\n") return entry_source, sha256_str(entry_source)
Example 50
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def get_threat_entry_types(params): """Takes input parameters from user and creates a list of appropriate threat entry types.""" types = list() if params.get("threat_entry_type_unspecified"): types.append("THREAT_ENTRY_TYPE_UNSPECIFIED") if params.get("threat_entry_type_url"): types.append("URL") if params.get("threat_entry_type_executable"): types.append("EXECUTABLE") if params.get("threat_entry_type_ip"): types.append("IP_RANGE") return types
Example 51
Source File: _util.py From azure-cli-extensions with MIT License | 6 votes |
def get_network_resource_property_entry(resource, prop): """ Factory method for creating get functions. """ def get_func(cmd, resource_group_name, resource_name, item_name): client = getattr(network_client_factory(cmd.cli_ctx), resource) items = getattr(client.get(resource_group_name, resource_name), prop) result = next((x for x in items if x.name.lower() == item_name.lower()), None) if not result: raise CLIError("Item '{}' does not exist on {} '{}'".format( item_name, resource, resource_name)) return result func_name = 'get_network_resource_property_entry_{}_{}'.format(resource, prop) setattr(sys.modules[__name__], func_name, get_func) return func_name
Example 52
Source File: semdictionary.py From mishkal with GNU General Public License v3.0 | 6 votes |
def get_entry_by_id(self, idf): """ Get dictionary entry by id from the dictionary @param id :word identifier @type id: integer @return: all attributes @rtype: dict """ # lookup for a word sql = u"select * FROM %s WHERE id='%s'" % (self.table_name, idf) try: self.cursor.execute(sql) if self.cursor: return self.cursor.fetchall() except sqlite.OperationalError: return False return False