query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
called when a POST request comes in for a Product instance already in the shopping cart
def argument_quantity(self, quantity): self.quantity = self.quantity + int(quantity) self.save()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _add_to_cart(request):\n postdata = request.POST.copy()\n slug = postdata.get('product', '')\n quantity = postdata.get('quantity', 1)\n product = get_object_or_404(Node, slug=slug)\n _cart_found = False\n if request.session.get(CART_ID_SESSION_KEY):\n try:\n cart = Cart.obje...
[ "0.6826102", "0.67538476", "0.67059445", "0.6633548", "0.6633132", "0.65685964", "0.6527332", "0.64987946", "0.64980817", "0.6484866", "0.64728206", "0.6432382", "0.640497", "0.63988966", "0.63514036", "0.6349805", "0.6307788", "0.62616706", "0.623183", "0.6227218", "0.620944...
0.0
-1
Initialize the document metadata session.
def __init__(self, latest_versions_path: str, original_versions_path: str) -> None: if not os.path.isdir(latest_versions_path): raise AbsException('Path to latest .abs versions ' f'"{latest_versions_path}" does not exist' ) if not os.path.isdir(original_versions_path): raise AbsException('Path to original .abs versions ' f'"{original_versions_path}" does not exist' ) self.latest_versions_path = os.path.realpath(latest_versions_path) self.original_versions_path = os.path.realpath(original_versions_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def init_session(self):\n pass", "def init_session(self):\n pass", "def init():\n get_writer_session()", "def initial_metadata(self):\n raise NotImplementedError()", "def _initialize_metadata(self):\n\n survey_metadata = metadata.Survey(id=\"0\")\n survey_metadata.stat...
[ "0.67784715", "0.67784715", "0.6263935", "0.62590474", "0.6240638", "0.6162484", "0.6090155", "0.6080682", "0.6068665", "0.6050694", "0.59644043", "0.59170955", "0.5908484", "0.58766645", "0.5872285", "0.58711493", "0.58711493", "0.58711493", "0.58176106", "0.57765025", "0.57...
0.0
-1
Get the .abs metadata for the specified arXiv paper identifier.
def get_abs(self, arxiv_id: str) -> DocMetadata: paper_id = Identifier(arxiv_id=arxiv_id) if paper_id.id in DELETED_PAPERS: raise AbsDeletedException(DELETED_PAPERS[paper_id.id]) latest_version = self._get_version(identifier=paper_id) if not paper_id.has_version \ or paper_id.version == latest_version.version: return dataclasses.replace(latest_version, is_definitive=True, is_latest=True) try: this_version = self._get_version(identifier=paper_id, version=paper_id.version) except AbsNotFoundException as e: if paper_id.is_old_id: raise else: raise AbsVersionNotFoundException(e) # Several fields need to reflect the latest version's data combined_version: DocMetadata = dataclasses.replace( this_version, version_history=latest_version.version_history, categories=latest_version.categories, primary_category=latest_version.primary_category, secondary_categories=latest_version.secondary_categories, primary_archive=latest_version.primary_archive, primary_group=latest_version.primary_group, is_definitive=True, is_latest=False) return combined_version
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def extract_meta_from_remote(paper_id):\n # $ Query Paper\n paper = arxiv.query(id_list=[paper_id])[0]\n # $ Set the Arxiv Object to ensure Proper extraction\n return ArxivIdentity.from_arxiv_response(paper),paper", "def get_abs(arxiv_id: str) -> DocMetadata:\n return current_sessi...
[ "0.67460513", "0.6647594", "0.6460236", "0.6408", "0.6279491", "0.558977", "0.5542963", "0.54372674", "0.53841174", "0.5379686", "0.5329302", "0.53129435", "0.52867734", "0.5258321", "0.51943076", "0.5147208", "0.5138165", "0.5131317", "0.5099704", "0.50869715", "0.5070285", ...
0.6633076
2
Get next consecutive Identifier relative to the provided Identifier.
def _next_id(self, identifier: Identifier) -> Optional['Identifier']: next_id = None if identifier.year is not None and \ identifier.month is not None and \ identifier.num is not None: new_year = identifier.year new_month = identifier.month new_num = identifier.num + 1 if (identifier.is_old_id and new_num > 999) \ or (not identifier.is_old_id and identifier.year < 2015 and new_num > 9999) \ or (not identifier.is_old_id and identifier.year >= 2015 and new_num > 99999): new_num = 1 new_month = new_month + 1 if new_month > 12: new_month = 1 new_year = new_year + 1 if identifier.is_old_id: next_id = '{}/{:02d}{:02d}{:03d}'.format( identifier.archive, new_year % 100, new_month, new_num) else: if new_year >= 2015: next_id = '{:02d}{:02d}.{:05d}'.format( new_year % 100, new_month, new_num) else: next_id = '{:02d}{:02d}.{:04d}'.format( new_year % 100, new_month, new_num) try: return Identifier(arxiv_id=next_id) except IdentifierException: return None else: return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_next_id(self, identifier: Identifier) -> Optional['Identifier']:\n next_id = self._next_id(identifier)\n if not next_id:\n return None\n\n path = self._get_parent_path(identifier=next_id)\n file_path = os.path.join(path, f'{next_id.filename}.abs')\n if os.path....
[ "0.68572384", "0.68154293", "0.65648353", "0.5960032", "0.5778565", "0.57366836", "0.57362103", "0.57106215", "0.56841695", "0.5662907", "0.5662147", "0.5626672", "0.5551417", "0.553537", "0.55154103", "0.5512396", "0.5491547", "0.5480652", "0.5477145", "0.5476946", "0.547689...
0.64670867
3
Get the first identifier for the next month.
def _next_yymm_id(self, identifier: Identifier) -> Optional[Identifier]: next_yymm_id = None if identifier.year is not None and \ identifier.month is not None: new_year = identifier.year new_month = identifier.month + 1 new_num = 1 if new_month > 12: new_month = 1 new_year = new_year + 1 if identifier.is_old_id: next_yymm_id = '{}/{:02d}{:02d}{:03d}'.format( identifier.archive, new_year % 100, new_month, new_num) elif new_year >= 2015: next_yymm_id = '{:02d}{:02d}.{:05d}'.format( new_year % 100, new_month, new_num) else: next_yymm_id = '{:02d}{:02d}.{:04d}'.format( new_year % 100, new_month, new_num) try: return Identifier(arxiv_id=next_yymm_id) except IdentifierException: return None else: return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def first_of_next_month(ref_date):\n year, month = add_months(ref_date.year, ref_date.month, 1)\n return type(ref_date)(year, month, 1)", "def _next_id(self, identifier: Identifier) -> Optional['Identifier']:\n next_id = None\n if identifier.year is not None and \\\n identifier...
[ "0.71140623", "0.70819384", "0.65288323", "0.64989054", "0.64522034", "0.6431146", "0.6364784", "0.63500136", "0.63453865", "0.62631005", "0.6257072", "0.6244404", "0.6200054", "0.6192637", "0.6188998", "0.6186235", "0.6151943", "0.61216503", "0.61216503", "0.61076903", "0.60...
0.74007684
0
Get the next identifier in sequence if it exists in the repository. Under certain conditions this is called to generate the "next" link in the "browse context" portion of the abs page rendering. These conditions are dependent on the identifier and context; it emulates legacy functionality. It is recommended to deprecate this function once the /prevnext route is fixed (or replaced) to handle old identifiers correctly.
def get_next_id(self, identifier: Identifier) -> Optional['Identifier']: next_id = self._next_id(identifier) if not next_id: return None path = self._get_parent_path(identifier=next_id) file_path = os.path.join(path, f'{next_id.filename}.abs') if os.path.isfile(file_path): return next_id next_yymm_id = self._next_yymm_id(identifier) if not next_yymm_id: return None path = self._get_parent_path(identifier=next_yymm_id) file_path = os.path.join(path, f'{next_yymm_id.filename}.abs') if os.path.isfile(file_path): return next_yymm_id return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def next_link(self) -> Optional[str]:\n return pulumi.get(self, \"next_link\")", "def next_link(self) -> str:\n return pulumi.get(self, \"next_link\")", "def nextId(self):\r\n \r\n nextId = -1\r\n if self._wizard.currentId() == SOURCE_PAGE_ID:\r\n nextId = TARGET_P...
[ "0.6984729", "0.67221254", "0.66676", "0.65789485", "0.62992543", "0.6268824", "0.6088184", "0.6079562", "0.60538673", "0.60469353", "0.6030127", "0.6015494", "0.5967108", "0.5966589", "0.5950977", "0.589943", "0.5884767", "0.5878848", "0.587126", "0.585398", "0.5844635", "...
0.6222639
6
Get previous consecutive Identifier relative to provided Identifier.
def _previous_id(self, identifier: Identifier) -> Optional['Identifier']: previous_id = None if identifier.year is not None and \ identifier.month is not None and \ identifier.num is not None: new_year = identifier.year new_month = identifier.month new_num = identifier.num - 1 if new_num == 0: new_month = new_month - 1 if new_month == 0: new_month = 12 new_year = new_year - 1 if identifier.is_old_id: if new_num == 0: new_num = 999 previous_id = '{}/{:02d}{:02d}{:03d}'.format( identifier.archive, new_year % 100, new_month, new_num) else: if new_year >= 2015: if new_num == 0: new_num = 99999 previous_id = '{:02d}{:02d}.{:05d}'.format( new_year % 100, new_month, new_num) else: if new_num == 0: new_num = 9999 previous_id = '{:02d}{:02d}.{:04d}'.format( new_year % 100, new_month, new_num) try: return Identifier(arxiv_id=previous_id) except IdentifierException: return None else: return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_previous_id(identifier: Identifier) -> Optional[Identifier]:\n return current_session().get_previous_id(identifier)", "def getPreviousElement(self,currentId):\n\tids = self.getObjectIds()\n\tpreviousId = None\n\tfor id in ids:\n\t if id == currentId:\n\t\treturn previousId\n\t else:\n\t\tpreviou...
[ "0.68398184", "0.6584527", "0.63730377", "0.63493836", "0.6142223", "0.6125821", "0.61153346", "0.597462", "0.5952775", "0.5942755", "0.5874705", "0.5858013", "0.5850779", "0.57981914", "0.5797494", "0.57876164", "0.57495373", "0.5744229", "0.5709335", "0.56956834", "0.566618...
0.6983114
0
Get previous identifier in sequence if it exists in repository. Under certain conditions this is called to generate the "previous" link in the "browse context" portion of the abs page rendering. These conditions are dependent on the identifier and context; it emulates legacy functionality. It is recommended to deprecate this function once the /prevnext route is fixed (or replaced) to handle old identifiers correctly.
def get_previous_id(self, identifier: Identifier) -> Optional[Identifier]: previous_id = self._previous_id(identifier) if not previous_id: return None if identifier.year == previous_id.year \ and identifier.month == previous_id.month: return previous_id path = self._get_parent_path(previous_id) if not os.path.exists(path): return None for _, _, file_list in os.walk(path): abs_files = [f[:-4] for f in file_list if f.endswith('.abs')] if not abs_files: return None max_id = max(abs_files) try: if previous_id.is_old_id: short_id = Identifier( arxiv_id=f'{previous_id.archive}/{max_id}') else: short_id = Identifier(arxiv_id=max_id) return short_id except IdentifierException: return None return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_previous(self):\n return self._next_previous_helper('previous')", "def previous(self, result, **kwargs):\n if result[\"previous\"]:\n return self._get(result[\"previous\"], **kwargs)\n\n return None", "def previous_page(self):\r\n if self.page.has_previous():\r\n ...
[ "0.70605826", "0.69684184", "0.6836895", "0.6755949", "0.6713104", "0.6711421", "0.67056006", "0.66659355", "0.6610744", "0.65709424", "0.6520972", "0.6516752", "0.65042716", "0.65036935", "0.64895576", "0.6465482", "0.6444505", "0.6440678", "0.6430793", "0.6418435", "0.64140...
0.612897
38
Get the absolute path of this DocMetadata's source file.
def _get_source_path(self, docmeta: DocMetadata) -> Optional[str]: identifier = docmeta.arxiv_identifier version = docmeta.version file_noex = identifier.filename if not docmeta.is_latest: parent_path = self._get_parent_path(identifier, version) file_noex = f'{file_noex}v{version}' else: parent_path = self._get_parent_path(identifier) for extension in VALID_SOURCE_EXTENSIONS: possible_path = os.path.join( parent_path, f'{file_noex}{extension[0]}') if os.path.isfile(possible_path): return possible_path return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def source_file_path(self) -> str:\n return self._source_file_path", "def get_source_path(self):\n return self.source_path", "def get_source_file(self):\n return self.get_attribute(\"source_file\")", "def path(self) -> str:\n return self.src + \"/\"", "def source(self) -> str | ...
[ "0.8547733", "0.82610506", "0.8053611", "0.7574011", "0.75686365", "0.7461368", "0.74287295", "0.73307705", "0.7301582", "0.7259421", "0.725329", "0.7234538", "0.7218298", "0.7183691", "0.7129371", "0.7121566", "0.710466", "0.70831716", "0.707813", "0.70628047", "0.6983357", ...
0.7473641
5
Get a list of formats that can be disseminated for this DocMetadata. Several checks are performed to determine available dissemination
def get_dissemination_formats(self, docmeta: DocMetadata, format_pref: Optional[str] = None, add_sciencewise: bool = False) -> List[str]: formats: List[str] = [] # first, get possible list of formats based on available source file source_file_path = self._get_source_path(docmeta) source_file_formats: List[str] = [] if source_file_path is not None: source_file_formats = \ formats_from_source_file_name(source_file_path) if source_file_formats: formats.extend(source_file_formats) if add_sciencewise: if formats and formats[-1] == 'other': formats.insert(-1, 'sciencewise_pdf') else: formats.append('sciencewise_pdf') else: # check source type from metadata, with consideration of # user format preference and cache version = docmeta.version format_code = docmeta.version_history[version - 1].source_type.code cached_ps_file_path = cache.get_cache_file_path( docmeta, 'ps') cache_flag = False if cached_ps_file_path \ and os.path.getsize(cached_ps_file_path) == 0 \ and source_file_path \ and os.path.getmtime(source_file_path) \ < os.path.getmtime(cached_ps_file_path): cache_flag = True source_type_formats = formats_from_source_type(format_code, format_pref, cache_flag, add_sciencewise) if source_type_formats: formats.extend(source_type_formats) return formats
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_dissemination_formats(docmeta: DocMetadata,\n format_pref: Optional[str] = None,\n add_sciencewise: bool = False) -> List:\n return current_session().get_dissemination_formats(docmeta,\n forma...
[ "0.72833514", "0.71896124", "0.68494296", "0.66793936", "0.6407827", "0.62660515", "0.5939488", "0.59020805", "0.5886499", "0.5860163", "0.5782993", "0.5706852", "0.56232613", "0.5623107", "0.5592796", "0.55736804", "0.55503446", "0.554279", "0.552786", "0.5473686", "0.545146...
0.69500184
2
Get list of ancillary file names and sizes.
def get_ancillary_files(self, docmeta: DocMetadata) \ -> List[Dict]: version = docmeta.version format_code = docmeta.version_history[version - 1].source_type.code if has_ancillary_files(format_code): source_file_path = self._get_source_path(docmeta) if source_file_path is not None: return list_ancillary_files(source_file_path) else: return [] return []
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def list_of(self):\r\n self.files = os.listdir(self.p)\r\n self.size = [0] * len(self.files)\r\n self.created = [0] * len(self.files)\r\n self.modified = [0] * len(self.files)\r\n total_size = 0\r\n iteration = 0\r\n for file in self.files:\r\n self.fol =...
[ "0.69518465", "0.63716376", "0.63222516", "0.6231716", "0.62269795", "0.6224222", "0.6198995", "0.61967695", "0.61952776", "0.61443186", "0.61215734", "0.6118438", "0.6078157", "0.6013874", "0.6011424", "0.60010415", "0.59977686", "0.59929526", "0.59908706", "0.59845823", "0....
0.0
-1
Parse arXiv .abs file.
def parse_abs_file(filename: str) -> DocMetadata: try: with open(filename, mode='r', encoding='latin-1') as absf: raw = absf.read() except FileNotFoundError: raise AbsNotFoundException except UnicodeDecodeError as e: # TODO: log this raise AbsParsingException( f'Failed to decode .abs file "{filename}": {e}') # TODO: clean up modified = datetime.fromtimestamp( os.path.getmtime(filename), tz=gettz('US/Eastern')) modified = modified.astimezone(tz=tzutc()) # there are two main components to an .abs file that contain data, # but the split must always return four components components = RE_ABS_COMPONENTS.split(raw) if len(components) > 4: components = alt_component_split(components) if not len(components) == 4: raise AbsParsingException( 'Unexpected number of components parsed from .abs.') # everything else is in the second main component prehistory, misc_fields = re.split(r'\n\n', components[1]) fields: Dict[str, Any] = \ AbsMetaSession._parse_metadata_fields(key_value_block=misc_fields) # abstract is the first main component fields['abstract'] = components[2] id_match = RE_ARXIV_ID_FROM_PREHISTORY.match(prehistory) if not id_match: raise AbsParsingException( 'Could not extract arXiv ID from prehistory component.') arxiv_id = id_match.group('arxiv_id') prehistory = re.sub(r'^.*\n', '', prehistory) parsed_version_entries = re.split(r'\n', prehistory) # submitter data from_match = RE_FROM_FIELD.match(parsed_version_entries.pop(0)) if not from_match: raise AbsParsingException('Could not extract submitter data.') name = from_match.group('name') if name is not None: name = name.rstrip() email = from_match.group('email') # get the version history for this particular version of the document if not len(parsed_version_entries) >= 1: raise AbsParsingException('At least one version entry expected.') (version, version_history, arxiv_id_v) \ = AbsMetaSession._parse_version_entries( arxiv_id=arxiv_id, version_entry_list=parsed_version_entries) arxiv_identifier = Identifier(arxiv_id=arxiv_id) # named (key-value) fields if not all(rf in fields for rf in REQUIRED_FIELDS): raise AbsParsingException(f'missing required field(s)') # some transformations category_list: List[str] = [] primary_category = None if 'categories' in fields and fields['categories']: category_list = fields['categories'].split() if category_list[0] in taxonomy.CATEGORIES: primary_category = Category(category_list[0]) primary_archive = \ Archive( taxonomy.CATEGORIES[primary_category.id]['in_archive']) elif arxiv_identifier.is_old_id: primary_archive = Archive(arxiv_identifier.archive) elif arxiv_identifier.is_old_id: primary_archive = Archive(arxiv_identifier.archive) else: raise AbsException('Cannot infer archive from identifier.') doc_license: License = \ License() if 'license' not in fields else License( recorded_uri=fields['license']) raw_safe = re.sub(RE_FROM_FIELD, r'\g<from>\g<name>', raw, 1) return DocMetadata( raw_safe=raw_safe, arxiv_id=arxiv_id, arxiv_id_v=arxiv_id_v, arxiv_identifier=Identifier(arxiv_id=arxiv_id), title=fields['title'], abstract=fields['abstract'], authors=AuthorList(fields['authors']), submitter=Submitter(name=name, email=email), categories=fields['categories'] if 'categories' in fields else None, primary_category=primary_category, primary_archive=primary_archive, primary_group=Group( taxonomy.ARCHIVES[primary_archive.id]['in_group']), secondary_categories=[ Category(x) for x in category_list[1:] if (category_list and len(category_list) > 1) ], journal_ref=None if 'journal_ref' not in fields else fields['journal_ref'], report_num=None if 'report_num' not in fields else fields['report_num'], doi=None if 'doi' not in fields else fields['doi'], acm_class=None if 'acm_class' not in fields else fields['acm_class'], msc_class=None if 'msc_class' not in fields else fields['msc_class'], proxy=None if 'proxy' not in fields else fields['proxy'], comments=fields['comments'] if 'comments' in fields else None, version=version, license=doc_license, version_history=version_history, modified=modified # private=private # TODO, not implemented )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load(filename):\n o = open(filename)\n s = o.read()\n a = ArffFile.parse(s)\n o.close()\n return a", "def parser(path):\n\t\n\tdata = Arff()\n\tdata.read_arff(path)\n\t\n\treturn data", "def read_abinit(filename='abinit.in'):\n\n from ase import Atoms, units\n\n if ...
[ "0.6293335", "0.5960045", "0.5839446", "0.56938064", "0.5470229", "0.54585195", "0.5442415", "0.5383238", "0.5345072", "0.5325224", "0.53108054", "0.530532", "0.5262298", "0.5240521", "0.5239216", "0.5221165", "0.5207952", "0.51851124", "0.51766455", "0.51730996", "0.5159004"...
0.7341478
0
Get a specific version of a paper's abstract metadata.
def _get_version(self, identifier: Identifier, version: Optional[int] = None) -> DocMetadata: parent_path = self._get_parent_path(identifier=identifier, version=version) path = os.path.join(parent_path, (f'{identifier.filename}.abs' if not version else f'{identifier.filename}v{version}.abs')) return self.parse_abs_file(filename=path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def extract_meta_from_remote(paper_id):\n # $ Query Paper\n paper = arxiv.query(id_list=[paper_id])[0]\n # $ Set the Arxiv Object to ensure Proper extraction\n return ArxivIdentity.from_arxiv_response(paper),paper", "def get_abs(self, arxiv_id: str) -> DocMetadata:\n paper_id =...
[ "0.6080023", "0.60320914", "0.5905042", "0.58196634", "0.575648", "0.5752106", "0.56954294", "0.5672822", "0.56069934", "0.5584644", "0.54881644", "0.54842895", "0.54152155", "0.5414221", "0.5410572", "0.54053754", "0.5396079", "0.53368646", "0.5315691", "0.52807045", "0.5266...
0.6086258
0
Get the absolute parent path of the provided identifier.
def _get_parent_path(self, identifier: Identifier, version: Optional[int] = None) -> str: parent_path = os.path.join( (self.latest_versions_path if not version else self.original_versions_path), ('arxiv' if not identifier.is_old_id or identifier.archive is None else identifier.archive), 'papers', identifier.yymm, ) return parent_path
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_parent(self, id_) -> str:\n return list(self._nodes[id_]['parents'].keys())[0]", "def parent_dir_path(path):\n return absolute_path(os.path.dirname(path))", "def get_parent_id_from_trace_id():\n trace_id = get_trace_id()\n return trace_id.parent_id", "def get_parent(path):\n\n # secu...
[ "0.74234164", "0.7001471", "0.698503", "0.69271344", "0.69162315", "0.6713711", "0.6697498", "0.66670144", "0.66431475", "0.66178703", "0.6597941", "0.6594848", "0.6549766", "0.6548474", "0.6538243", "0.6464383", "0.64623785", "0.64418644", "0.64418644", "0.63819927", "0.6351...
0.7567351
0
Parse the version entries from the arXiv .abs file.
def _parse_version_entries(arxiv_id: str, version_entry_list: List) \ -> Tuple[int, List[VersionEntry], str]: version_count = 0 version_entries = list() for parsed_version_entry in version_entry_list: version_count += 1 date_match = RE_DATE_COMPONENTS.match(parsed_version_entry) if not date_match: raise AbsParsingException( 'Could not extract date components from date line.') try: sd = date_match.group('date') submitted_date = parser.parse(date_match.group('date')) except (ValueError, TypeError): raise AbsParsingException( f'Could not parse submitted date {sd} as datetime') source_type = SourceType(code=date_match.group('source_type')) ve = VersionEntry( raw=date_match.group(0), source_type=source_type, size_kilobytes=int(date_match.group('size_kilobytes')), submitted_date=submitted_date, version=version_count ) version_entries.append(ve) return ( version_count, version_entries, f"{arxiv_id}v" f"{version_entries[-1].version}")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_abs_file(filename: str) -> DocMetadata:\n try:\n with open(filename, mode='r', encoding='latin-1') as absf:\n raw = absf.read()\n except FileNotFoundError:\n raise AbsNotFoundException\n except UnicodeDecodeError as e:\n # TODO: log thi...
[ "0.6567073", "0.5690683", "0.56216645", "0.5586731", "0.5546465", "0.55331504", "0.5424544", "0.5418142", "0.5321359", "0.5282709", "0.52254856", "0.5218742", "0.52110106", "0.5190335", "0.51662725", "0.5163971", "0.5161085", "0.51590484", "0.5139128", "0.5135782", "0.5133198...
0.6053738
1
Parse the keyvalue block from the arXiv .abs string.
def _parse_metadata_fields(key_value_block: str) -> Dict[str, str]: key_value_block = key_value_block.lstrip() field_lines = re.split(r'\n', key_value_block) field_name = 'unknown' fields_builder: Dict[str, str] = {} for field_line in field_lines: field_match = RE_FIELD_COMPONENTS.match(field_line) if field_match and field_match.group('field') in NAMED_FIELDS: field_name = field_match.group( 'field').lower().replace('-', '_') field_name = re.sub(r'_no$', '_num', field_name) fields_builder[field_name] = field_match.group( 'value').rstrip() elif field_name != 'unknown': # we have a line with leading spaces fields_builder[field_name] += re.sub(r'^\s+', ' ', field_line) return fields_builder
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parseLine(line):\n\n\teq = line.find('=')\n\tif eq == -1: raise Exception()\n\tkey = line[:eq].strip()\n\tvalue = line[eq+1:-1].strip()\n\treturn key, parseValue(value)", "def parse_authenticator_data(val: bytes) -> AuthenticatorData:\n # Don't bother parsing if there aren't enough bytes for at least:\n ...
[ "0.5502035", "0.54756844", "0.53982985", "0.53168106", "0.52334744", "0.51876444", "0.50723124", "0.50410956", "0.5033745", "0.503361", "0.500491", "0.49377406", "0.49351236", "0.49270114", "0.48791102", "0.48754433", "0.48350626", "0.4834375", "0.47928026", "0.47764754", "0....
0.0
-1
Get list of ancillary file names and sizes.
def get_ancillary_files(docmeta: DocMetadata) -> List[Dict]: return current_session().get_ancillary_files(docmeta)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def list_of(self):\r\n self.files = os.listdir(self.p)\r\n self.size = [0] * len(self.files)\r\n self.created = [0] * len(self.files)\r\n self.modified = [0] * len(self.files)\r\n total_size = 0\r\n iteration = 0\r\n for file in self.files:\r\n self.fol =...
[ "0.6951985", "0.637173", "0.6322451", "0.62318736", "0.6227063", "0.62240994", "0.6199027", "0.6196705", "0.6195469", "0.6144316", "0.61217695", "0.6118644", "0.60781914", "0.60140824", "0.6011602", "0.60010785", "0.5997914", "0.59930575", "0.5990947", "0.59845144", "0.598373...
0.0
-1
Get list of dissemination formats.
def get_dissemination_formats(docmeta: DocMetadata, format_pref: Optional[str] = None, add_sciencewise: bool = False) -> List: return current_session().get_dissemination_formats(docmeta, format_pref, add_sciencewise)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def formats(self):\n logger.debug(\"Get formats\")\n return self._raw_api.formats.get()", "def getFormats(self):\n return self.formats", "def get_export_formats(self):\n return [f for f in self.formats if f().can_export()]", "def export_formats(self):\n return list(self._ex...
[ "0.7676491", "0.72095263", "0.6843036", "0.676619", "0.6653835", "0.664365", "0.65041065", "0.6443467", "0.64138347", "0.60489416", "0.6047862", "0.6045683", "0.60069233", "0.60045713", "0.59716725", "0.5901643", "0.58269656", "0.580406", "0.57598495", "0.56726515", "0.566924...
0.745034
1
Retrieve next arxiv document metadata by id.
def get_next_id(identifier: Identifier) -> Optional[Identifier]: return current_session().get_next_id(identifier)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch_metadata (self, id):\n payload = {\n 'movieid': id,\n 'imageformat': 'jpg',\n '_': int(time())\n }\n response = self._session_get(component='metadata', params=payload, type='api')\n return self._process_response(response=response, component=sel...
[ "0.6512268", "0.5990063", "0.59627163", "0.5904663", "0.58782244", "0.58716303", "0.58335143", "0.5800125", "0.5605787", "0.55422497", "0.54966855", "0.545362", "0.5449414", "0.54356223", "0.53878677", "0.5359083", "0.5344773", "0.53221405", "0.5306357", "0.5281371", "0.52794...
0.0
-1
Retrieve previous arxiv document metadata by id.
def get_previous_id(identifier: Identifier) -> Optional[Identifier]: return current_session().get_previous_id(identifier)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_metadata(self, file_id):\n pass", "def get_abs(self, arxiv_id: str) -> DocMetadata:\n paper_id = Identifier(arxiv_id=arxiv_id)\n\n if paper_id.id in DELETED_PAPERS:\n raise AbsDeletedException(DELETED_PAPERS[paper_id.id])\n\n latest_version = self._get_version(ident...
[ "0.62685925", "0.6112167", "0.6098469", "0.59229183", "0.57163763", "0.5660339", "0.56069016", "0.5589769", "0.55594236", "0.5459823", "0.5458314", "0.54363245", "0.53857076", "0.53690284", "0.53659326", "0.5350738", "0.52522564", "0.52347064", "0.52260345", "0.5214516", "0.5...
0.0
-1
Retrieve arxiv document metadata by id.
def get_abs(arxiv_id: str) -> DocMetadata: return current_session().get_abs(arxiv_id)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch_metadata (self, id):\n payload = {\n 'movieid': id,\n 'imageformat': 'jpg',\n '_': int(time())\n }\n response = self._session_get(component='metadata', params=payload, type='api')\n return self._process_response(response=response, component=sel...
[ "0.7180735", "0.6914526", "0.6769934", "0.670825", "0.6669114", "0.6606881", "0.6565573", "0.65052676", "0.6451483", "0.6325305", "0.6291632", "0.62834805", "0.6270202", "0.6257079", "0.61705565", "0.6157013", "0.6127251", "0.603581", "0.60247993", "0.5977185", "0.5951391", ...
0.6389172
9
Get a new session with the abstract metadata service.
def get_session(app: object = None) -> AbsMetaSession: config = get_application_config(app) orignal_versions_path = config.get('DOCUMENT_ORIGNAL_VERSIONS_PATH', None) latest_versions_path = config.get('DOCUMENT_LATEST_VERSIONS_PATH', None) return AbsMetaSession(latest_versions_path, orignal_versions_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new_session(self):\n return self.Session()", "def session(self):\n if not self._session: #Create new session if none exists\n return self._new_session()\n return self._session", "def session(get_session):\n return get_session()", "def loadSession():\n metadata = Base...
[ "0.7296449", "0.6973715", "0.68892246", "0.6835348", "0.68246645", "0.68246543", "0.67933273", "0.6792176", "0.6756659", "0.6756441", "0.67097235", "0.66761094", "0.66475564", "0.661505", "0.65300965", "0.6523089", "0.65006286", "0.64843434", "0.6483488", "0.64824617", "0.647...
0.6573127
14
r"""Alternative split to accomidate extra \\ in the abstract.
def alt_component_split(components: List[str]) -> List[str]: if len(components) <= 4: raise AbsParsingException( 'Unexpected number of components parsed from .abs.') alt_comp = [] abstract = "" for idx, itm in enumerate(components): if idx < 2: alt_comp.append(itm) if idx == 2: abstract += itm if idx > 2 and itm: abstract += r" \\ " + itm # Add back in \\ stripped by split alt_comp.append(abstract) alt_comp.append('') return alt_comp
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def addSplit(self):\n pass", "def split(self, splits, catchall=False):\r\n raise NotImplementedError()", "def test_splitDelimiters(self):\n r = irc.split(\"xx yyz\", 2)\n self.assertEqual([\"xx\", \"yy\", \"z\"], r)\n r = irc.split(\"xx\\nyyz\", 2)\n self.assertEqual([\"xx...
[ "0.6545829", "0.6121232", "0.59847283", "0.597881", "0.5923667", "0.57499874", "0.5742462", "0.57287633", "0.5727164", "0.57085973", "0.5625653", "0.5609635", "0.55904573", "0.5570576", "0.5550438", "0.550439", "0.546011", "0.5413647", "0.5412393", "0.5412105", "0.5409049", ...
0.5983564
3
get the closest mesh triangles ids from a transomr position
def closestTriangleToTransform(transform, meshName): faceVertices, points = meshData.getMeshData(meshName) vertexFaces = meshData.getMeshVertexFaces(faceVertices) point = np.array(cmds.xform(transform, q=1, ws=1, t=1), dtype=np.double) return meshData.getClosestTriangle(point, points, vertexFaces, faceVertices)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def MeshVtxAdjacentVtxs (strMesh, index, blnAbsolutConnections=False, blnCreate=False):\n \"\"\"custom function\"\"\"\n #-----------------------------------------------------------------------------------------------------------------------------------------\n def CullDuplicates(seq, idfun=None): \n ...
[ "0.5805424", "0.57145", "0.56526566", "0.565149", "0.56275636", "0.55619234", "0.55525434", "0.545092", "0.54096115", "0.53921366", "0.538401", "0.536471", "0.5312883", "0.5299891", "0.5299523", "0.52991015", "0.52976525", "0.5295863", "0.5291774", "0.5280542", "0.52317286", ...
0.59132826
0
get the skinweights form the skincluster, create a skintransforms node and connect it to drive the transforms
def createSkinTansformNode(skinCluster, transforms): node = cmds.createNode('skinTransforms') influences = cmds.listConnections('{}.matrix'.format(skinCluster), s=1, d=0) for i, jnt in enumerate(influences): cmds.connectAttr('{}.worldMatrix[0]'.format(jnt), '{}.matrix[{}]'.format(node,i)) m = cmds.getAttr('{}.wim[0]'.format(jnt)) cmds.setAttr ('{}.bindPreMatrix[{}]'.format(node, i), m, type="matrix") mesh = cmds.deformer(skinCluster, q=1, g=1)[0] for i, each in enumerate(transforms): triangle = closestTriangleToTransform(each, mesh) weights=list() positions=list() for vtx in triangle: vtxName = '{}.vtx[{}]'.format(mesh, vtx) weights.extend(cmds.skinPercent(skinCluster, vtxName, query=True, value=True )) positions.extend(cmds.xform(vtxName, q=1, ws=1, t=1)) cmds.setAttr('{}.weightsList[{}].weights'.format(node, i), weights, type="doubleArray") cmds.setAttr('{}.weightsList[{}].points'.format(node, i), positions, type="doubleArray") m = cmds.getAttr('{}.wm[0]'.format(each)); cmds.setAttr('{}.weightsList[{}].pbm'.format(node, i), m, type="matrix") for i, loc in enumerate(transforms): dec = cmds.createNode('decomposeMatrix') cmds.connectAttr('{}.outputs[{}]'.format(node, i), '{}.inputMatrix'.format(dec)) cmds.connectAttr('{}.outputTranslate'.format(dec), '{}.translate'.format(loc)) cmds.connectAttr('{}.outputRotate'.format(dec), '{}.rotate'.format(loc)) cmds.connectAttr('{}.outputScale'.format(dec), '{}.scale'.format(loc)) return node
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def copy_cluster_weights(shape, weight_file, method=\"bilinear\"):\n\n # gets the temporary folder path\n temp_path = get_temp_folder()\n short_name = get_prefix_less_name(shape)\n\n for node in weight_file:\n if not weight_file[node]:\n continue\n cmds.deformerWeights(weight_f...
[ "0.60992557", "0.59548813", "0.5897242", "0.58499587", "0.5831983", "0.57551503", "0.57265556", "0.5725397", "0.5677713", "0.54353786", "0.5421846", "0.5350296", "0.5301341", "0.5252528", "0.5239307", "0.52385575", "0.52209234", "0.5210054", "0.52021974", "0.51798564", "0.517...
0.72898114
0
Changes the value of var to value, in target card json target
def doEdit(var, value, target): currentValue = target.get(var, "") newValue = Simplifier.simplify(str(value).replace(f"{{{var}}}", str(currentValue))) target[var] = newValue
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_var(self,variable,value):\n self.template=self.template.replace(\"@{}@\".format(variable),value)", "def updateValue(self):\n self.value = self.var.get()", "def set_variable(self, request, context):\n response = SetVariableResponse()\n value = decode(request.value)\n s...
[ "0.5401657", "0.53921354", "0.5373613", "0.53605235", "0.5335546", "0.5331462", "0.5317318", "0.5298089", "0.5265769", "0.5262278", "0.52587116", "0.5233701", "0.520725", "0.514586", "0.51372725", "0.50887924", "0.5060526", "0.5028422", "0.50151414", "0.5007186", "0.49935517"...
0.5842602
0
Esta funcion utiliza las funciones desarrolladas anteriormente y calcula la posicion optima de una red de N particulas con radio r y el porcentaje de estas definido por el usuario
def Montecarlo(h,porcentaje,nombre): tm = time() print('Se esta procesando el '+str(porcentaje)+'% de particulas') print('\n') redor = Quitar(porcentaje,redhex) Guardar_archivo(redor,nombre + 'original') redopt = Optim(redor,h,1) fin = datetime.now() Guardar_archivo(redopt,nombre +'optim') print('Calculado para '+str(len(redor))+' particulas') Dt2 = time() -tm print('en un tiempo de '+str(Dt2)+'s. \n') print(fin) return()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calc_ros(self, *args):\n return 0", "def reprographie():\n nombreDePhotocopie = int(input(\"Entrez le nombre de photocopie a effectuer \"))\n PREMIER_PRIX = 0.10\n DEUXIEME_PRIX = 0.09\n TROISIEME_PRIX = 0.08\n PREMIERE_TRANCHE = 10\n DEUXIEME_TRANCHE = 20\n TROISIEME_TRANCHE = 30...
[ "0.60318774", "0.60297036", "0.57904255", "0.5759242", "0.56882286", "0.56862867", "0.5674591", "0.56636524", "0.5636586", "0.5592679", "0.5588461", "0.55816984", "0.55071455", "0.54997176", "0.5483748", "0.5462496", "0.5423283", "0.5417487", "0.5394506", "0.539347", "0.53915...
0.0
-1
Common util function that generates random string of desired length from set of letters and digits
def generate_key(length): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def randomStringDigits(stringLength:int=4)->str:\n lettersAndDigits = string.ascii_letters + string.digits\n return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))", "def _generate_random_string(length: int):\n\tall_chars = string.ascii_letters + string.digits\n\treturn ''.join(random...
[ "0.81941396", "0.8172787", "0.814063", "0.81391037", "0.8110602", "0.8100234", "0.80905783", "0.8060947", "0.803296", "0.8026487", "0.8021553", "0.8010257", "0.80099964", "0.80039036", "0.79910237", "0.79653245", "0.7934098", "0.7928981", "0.7907178", "0.79025376", "0.7882018...
0.767259
53
Return a numeric PIN with length digits
def get_pin(length=6): pin = str(random.sample(range(10 ** (length - 1), 10 ** length), 1)[0]) print("pin "+pin) return pin
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __generate_pin(cls) -> str:\n return str(randbelow(10 ** cls.PIN_DIGITS)).zfill(cls.PIN_DIGITS)", "def get_pin_digits(pin):\n digits = []\n for i in range(1, 5):\n digit = pin % 10\n pin = int(pin / 10)\n digits = [digit] + digits\n return digits", "def number2patten(nu...
[ "0.74236387", "0.70152956", "0.6587809", "0.64308965", "0.62868375", "0.6269005", "0.6230067", "0.6148351", "0.6140739", "0.6132022", "0.6079048", "0.6036217", "0.59997034", "0.5981399", "0.59480107", "0.5926849", "0.5907118", "0.58957", "0.5892246", "0.58810383", "0.587727",...
0.76024115
0
Send an email utility
def send_mail(user, subject, message, from_email, recipient_list, fail_silently=False,\ auth_user=None, auth_password=None, connection=None, html_message=None): message = smart_text(gpg.sign(message)) try: Profile.objects.get(user= user).pgp_gpg_public_key message = smart_text(gpg.encrypt(message)) except: pass send_email_django(subject, message, from_email, recipient_list, fail_silently,\ auth_user, auth_password, connection, html_message) return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def send_mail(email):\n return email.send()", "def send_email():\n send_mail(\"You've got some problem.\", 'REPAIR IT', 'dimazarj2009@rambler.ru',\n ['dimazarj2009@rambler.ru'], fail_silently=False,)", "def send_email(msg):\n\tprint(\"sendEmail: \" + msg)", "def exec(self): \r\n ema...
[ "0.7893454", "0.76480544", "0.75946885", "0.75844413", "0.7576186", "0.73962814", "0.73682386", "0.73424965", "0.73239505", "0.7319048", "0.7314937", "0.7285326", "0.72801477", "0.7278673", "0.7230599", "0.7217163", "0.71966106", "0.71918434", "0.7187204", "0.71753323", "0.71...
0.65766037
94
Send an email utility
def send_email(subject, ctx_dict, to_email, email_template_txt=None, email_template_html=None, request=None): # Email subject *must not* contain newlines if type(to_email) == str: to_email = [to_email] subject = ''.join(subject.splitlines()) from_email = getattr(settings, 'DEFAULT_FROM_EMAIL') message_txt = render_to_string(email_template_txt, ctx_dict, request=request) email_message = EmailMultiAlternatives(subject, message_txt, from_email, to_email) message_html = render_to_string( email_template_html, ctx_dict, request=request) email_message.attach_alternative(message_html, 'text/html') email_message.send()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def send_mail(email):\n return email.send()", "def send_email():\n send_mail(\"You've got some problem.\", 'REPAIR IT', 'dimazarj2009@rambler.ru',\n ['dimazarj2009@rambler.ru'], fail_silently=False,)", "def send_email(msg):\n\tprint(\"sendEmail: \" + msg)", "def exec(self): \r\n ema...
[ "0.7893454", "0.76480544", "0.75946885", "0.75844413", "0.7576186", "0.73962814", "0.73682386", "0.73424965", "0.73239505", "0.7319048", "0.7314937", "0.7285326", "0.72801477", "0.7278673", "0.7230599", "0.7217163", "0.71966106", "0.71918434", "0.7187204", "0.71753323", "0.71...
0.0
-1
Returns a JSON response, transforming 'context' to make the payload.
def render_to_json_response(self, context, **response_kwargs): return JsonResponse( self.get_data(context), **response_kwargs )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def render_to_response(self, context):\n return self.get_json_response(self.convert_context_to_json(context))", "def render_to_response(self, context):\n\t\treturn self.get_json_response(self.convert_context_to_json(context))", "def render_to_json_response(self, context, **response_kwargs):\n ret...
[ "0.7898263", "0.7824009", "0.76766837", "0.76766837", "0.7560496", "0.75058556", "0.73821956", "0.73662317", "0.7348336", "0.7347456", "0.7309291", "0.7130906", "0.6941217", "0.6892298", "0.6722085", "0.663044", "0.663044", "0.663044", "0.663044", "0.6624278", "0.66101027", ...
0.74115
9
Returns an object that will be serialized as JSON by json.dumps().
def get_data(self, context): # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. return context
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def toJSON(cls, obj):\n return json.dumps(obj)", "def serialize(self, obj):\n return json.dumps(obj)", "def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__)", "def to_json(self, *args, **kwargs):\n return json.dumps(self.serialize(primitive=True), *args, **kwa...
[ "0.78144574", "0.7662045", "0.76151204", "0.74891126", "0.7480223", "0.7432419", "0.7416268", "0.7400361", "0.7388459", "0.7362635", "0.73541415", "0.73291653", "0.7320688", "0.7310187", "0.73080957", "0.727898", "0.727898", "0.72756785", "0.7259399", "0.72041607", "0.7153282...
0.0
-1
Fixture for DataFrame of ints which are constant per column
def int_frame_const_col(): df = DataFrame( np.tile(np.arange(3, dtype="int64"), 6).reshape(6, -1) + 1, columns=["A", "B", "C"], ) return df
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _to_constant_df(self, num):\n if isinstance(num, pd.DataFrame):\n# pdb.set_trace()\n return num\n else:\n return self.data['ones'].copy() * num", "def test_df():\n return pd.DataFrame({\n 'intcol': [1, 2, 3],\n 'strcol': ['four', 'five', 'six'],...
[ "0.62194395", "0.60628957", "0.5972536", "0.57523376", "0.5721764", "0.56640995", "0.56414294", "0.5635445", "0.559424", "0.5559713", "0.55304813", "0.5526375", "0.5492284", "0.54894716", "0.5483786", "0.5478982", "0.5412668", "0.5365263", "0.5359209", "0.5358688", "0.5310620...
0.6852467
0
Logs a message, preserving the progress bar correct output format.
def log_message(self, message: str) -> None: from tqdm import tqdm tqdm.write(message, file=self.tqdm_kwargs.get("file", None))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def log_message(self, message):\n if self.root.is_logging:\n if len(repr(str(msg))) < 1:\n stdout(msg)\n self.root.log_file.write(\"%.4f\" % time.time() + \" \" + repr(str(msg)) + \"\\n\")\n return", "def log_and_print(self, message):\n self.f.write(messa...
[ "0.72831756", "0.7170845", "0.71509373", "0.7105534", "0.7096617", "0.6908535", "0.6884731", "0.6878834", "0.6869885", "0.682706", "0.67774737", "0.6756506", "0.67553526", "0.67249006", "0.67246664", "0.6717832", "0.6699004", "0.66793716", "0.66682446", "0.66388786", "0.66219...
0.73927295
0
Attaches the progress bar to an engine object.
def attach( # type: ignore[override] self, engine: Engine, metric_names: Optional[Union[str, List[str]]] = None, output_transform: Optional[Callable] = None, event_name: Union[Events, CallableEventWithFilter] = Events.ITERATION_COMPLETED, closing_event_name: Union[Events, CallableEventWithFilter] = Events.EPOCH_COMPLETED, state_attributes: Optional[List[str]] = None, ) -> None: desc = self.tqdm_kwargs.get("desc", None) if event_name not in engine._allowed_events: raise ValueError(f"Logging event {event_name.name} is not in allowed events for this engine") if isinstance(closing_event_name, CallableEventWithFilter): if closing_event_name.filter is not None: raise ValueError("Closing Event should not be a filtered event") if not self._compare_lt(event_name, closing_event_name): raise ValueError(f"Logging event {event_name} should be called before closing event {closing_event_name}") log_handler = _OutputHandler( desc, metric_names, output_transform, closing_event_name=closing_event_name, state_attributes=state_attributes, ) super(ProgressBar, self).attach(engine, log_handler, event_name) engine.add_event_handler(closing_event_name, self._close)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_progress(self, progress: float):", "def progress(self, progress):\n\n self._progress = progress", "def progress(self, progress):\n\n self._progress = progress", "def start_progress_bar(self):\r\n self.progress[\"value\"] = self.progress_step", "def setProgress(self, prog):\n\t\...
[ "0.6675522", "0.6575613", "0.6575613", "0.6366625", "0.6311144", "0.6308899", "0.6113574", "0.6113574", "0.6059104", "0.602622", "0.602041", "0.595098", "0.5913407", "0.5906952", "0.588988", "0.5886486", "0.5834592", "0.58345807", "0.58221585", "0.58096355", "0.57276875", "...
0.0
-1
Creates a connection to a minio client.
def get_minio_client(access: str, secret: str) -> Minio: return Minio( config.minio_host + ":9000", access_key=access, secret_key=secret, secure=False )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_minio_client(\n host=\"minio\", \n port=\"9000\", \n access_key=\"minio\", \n secret_key=\"minio123\", \n secure=False\n ):\n return Minio(\n endpoint=f\"{host}:{port}\",\n access_key=access_key,\n secret_key=secret_key,\n secure=secure\n )", "def g...
[ "0.77459127", "0.75584656", "0.7501291", "0.67123073", "0.65052503", "0.6390793", "0.637641", "0.63676625", "0.6254031", "0.62502515", "0.6195835", "0.61245006", "0.60537136", "0.6052816", "0.6049785", "0.6039034", "0.6032452", "0.6021877", "0.6020293", "0.60018814", "0.59781...
0.68421245
3
Given a title, format it as a title/subtitle/etc.
def title(text, level=0): return '\n' + text + '\n' + '=-~_#%^' [level] * len(text) + '\n\n'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pretty_title(title):\n output = '-' * 5 + ' ' + title + ' ' + '-' * 5\n return output", "def pretty_title(title):\n output = '-' * 5 + ' ' + title.lower() + ' ' + '-' * 5\n return output", "def format_title(self, title):\n new_title = ''.join(word.lower().strip('!\"#$%&\\'()*+,-./:;<=>?@...
[ "0.77604055", "0.7668561", "0.7375752", "0.73693407", "0.7343961", "0.73062205", "0.7250976", "0.72417545", "0.7131877", "0.70663816", "0.70402277", "0.70368814", "0.6962171", "0.6954695", "0.6933593", "0.6933249", "0.6852279", "0.68489885", "0.6843278", "0.6822912", "0.67877...
0.70659155
10
Initialize a cache to store the key value pair, and define a wrapper method for invoker function
def memoize(f): cache = OrderedDict({}) def wrapper(*keys, **kwargs): """ Search for invoker function's return value in cache for given arguments, if found then return else store function parameters as key and function return value as value in cache If cache size exceeds 2, delete the oldest used key value record """ key = str(keys) + str(kwargs) if key in cache: value = cache.pop(key) cache[key] = value return cache[key] while len(cache)>1: cache.popitem(False) cache[key] = f(*keys, **kwargs) return cache[key] return wrapper
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def instance_cache(func):\n def _wrapper(self, *args, **kwargs):\n key = (func.__name__,) + args\n for pair in sorted(kwargs.items()):\n key += pair\n if key in self._cache:\n return self._cache[key]\n data = func(self, *args, **kwargs)\n self._cache[key]...
[ "0.7277223", "0.71770215", "0.715268", "0.7124713", "0.7084185", "0.703103", "0.7005773", "0.6985863", "0.69002616", "0.68960965", "0.68862516", "0.6799958", "0.6730158", "0.67280996", "0.6692615", "0.6692513", "0.6617353", "0.66095406", "0.6592093", "0.6561765", "0.6548805",...
0.6497542
27
Search for invoker function's return value in cache for given arguments, if found then return else store function parameters as key and function return value as value in cache If cache size exceeds 2, delete the oldest used key value record
def wrapper(*keys, **kwargs): key = str(keys) + str(kwargs) if key in cache: value = cache.pop(key) cache[key] = value return cache[key] while len(cache)>1: cache.popitem(False) cache[key] = f(*keys, **kwargs) return cache[key]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def memoize(f):\n cache = OrderedDict({})\n\n def wrapper(*keys, **kwargs):\n \"\"\" Search for invoker function's return value in cache for given arguments,\n if found then return else store function parameters as key\n and function return value as value in cache\n ...
[ "0.74807256", "0.7031692", "0.6974766", "0.6857274", "0.68498635", "0.67605025", "0.6647616", "0.66386634", "0.6564361", "0.6442545", "0.642939", "0.6426649", "0.6388788", "0.6338939", "0.6338939", "0.6334363", "0.6321886", "0.6312213", "0.6310382", "0.6309857", "0.6278765", ...
0.6634452
8
Encode the sequence as a list of floats using the provided vocab.
def encode_dna_as_floats(sequence: Iterable[str], vocab: str = dc_constants.VOCAB, offset: int = 0) -> Optional[Iterable[float]]: ids = [] for base in sequence: if base not in vocab: return None base_id = float(vocab.index(base) + offset) ids.append(base_id) return ids
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def put_float_list_to_feature(seq_example: tf.train.SequenceExample,\n value: Sequence[Sequence[float]], key: str):\n for s in value:\n seq_example.feature_lists.feature_list.get_or_create(\n key).feature.add().float_list.value[:] = s", "def encode_sequence(text: List[str]...
[ "0.55322623", "0.55027866", "0.54789644", "0.5260034", "0.5258647", "0.5159166", "0.5092331", "0.50536036", "0.5027336", "0.50256157", "0.50224316", "0.50179625", "0.5005602", "0.5005602", "0.49933308", "0.49916053", "0.49875823", "0.49784765", "0.49743456", "0.49743456", "0....
0.67705715
0
Reverses the sequence and complement the valid bases. If the complement of a particular base cannot be found in complement_dict, we
def reverse_complement(sequence: str) -> str: complement_dict = sequence_utils.DNA_COMPLEMENT # If a base is not present in the vocabulary, we don't reverse complement it # in this function, and these sequences will get discarded downstream in the # TF Example generation pipeline. return ''.join(complement_dict.get(nt, nt) for nt in reversed(sequence))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reverse_complement(base):\n try:\n assert isinstance(base, str)\n assert len(base) is 1\n rc = str.maketrans('ACGT', 'TGCA') # Traslation table for reverse complentary sequences\n return base.translate(rc)\n except AssertionError:\n raise Not...
[ "0.701657", "0.69497687", "0.69136834", "0.6908366", "0.6803027", "0.6733149", "0.6662957", "0.64786804", "0.6446309", "0.6433807", "0.6409999", "0.6374465", "0.62980473", "0.627324", "0.62719995", "0.6271825", "0.62514186", "0.6158045", "0.6153276", "0.6146368", "0.6100468",...
0.6412292
10
Returns information used to help determine label base positions.
def get_ref_and_start_and_offset(forward_ref_sequence: str, strand: bed_pb2.BedRecord.Strand, chrom_start: int, chrom_end: int) -> Tuple[str, int, int]: ref_sequence = forward_ref_sequence if strand == bed_pb2.BedRecord.Strand.FORWARD_STRAND: start = chrom_start offset = 1 elif strand == bed_pb2.BedRecord.Strand.REVERSE_STRAND: start = chrom_end offset = -1 # For the reverse strand, we want the reverse complement. ref_sequence = reverse_complement(forward_ref_sequence) else: raise ValueError('Strand must be set.') return ref_sequence, start, offset
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def labelpos(self):\n return self._labelpos", "def getLabelInfo(self, label): # real signature unknown; restored from __doc__\n pass", "def getLabels(self):\n return self.numToLabel", "def getLabel(self):\n return self.content[:12]", "def get_label_position(self) -> LabelPositionStr...
[ "0.69641536", "0.65309316", "0.6444464", "0.63758844", "0.635286", "0.62371516", "0.6221768", "0.62208426", "0.62140536", "0.61365473", "0.612567", "0.60587156", "0.6046399", "0.60448956", "0.5994253", "0.5988822", "0.594738", "0.59370047", "0.5934904", "0.59292036", "0.59165...
0.0
-1
Returns the sequence with GAP_OR_PAD and GAP_OR_PAD tokens removed.
def get_sequence_without_gaps_or_padding(sequence: str) -> str: return sequence.replace(dc_constants.GAP_OR_PAD, '').replace(dc_constants.GAP_OR_PAD, '')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ungapped(self):\n s = self.sequence\n for sGapChar in GAP_CHARACTERS:\n s = s.replace(sGapChar, '')\n return s", "def remove_guff(seqs):\n new_seqs = {}\n stop_codons = [\"TGA\", \"TAA\", \"TAG\"]\n for key, value in seqs.items():\n new_seq = \"\"\n for ...
[ "0.6750863", "0.5907528", "0.5521466", "0.5289905", "0.5231796", "0.51557064", "0.50116265", "0.4972692", "0.49560896", "0.49461672", "0.4935586", "0.48857594", "0.48742893", "0.4835272", "0.4817296", "0.48110196", "0.4809287", "0.4806622", "0.47794852", "0.47744012", "0.4755...
0.68402666
0
Returns start and end coordinates of label in the reference genome. Querying the reference genome for these coordinates will produce the label sequence. We need to add 1 to either start or end depending on the orientation of the reference.
def get_label_start_end( label_base_positions: Iterable[int], strand: bed_pb2.BedRecord.Strand) -> Tuple[Optional[int], Optional[int]]: # Gap and padding tokens may have a position of -1, since they are not # actually present in the reference. Remove all instances of -1, since we do # not want to consider it when computing min/max position. valid_label_base_positions = set(label_base_positions) valid_label_base_positions.discard(-1) if not valid_label_base_positions: return None, None start = min(valid_label_base_positions) end = max(valid_label_base_positions) if strand == bed_pb2.BedRecord.Strand.FORWARD_STRAND: end += 1 elif strand == bed_pb2.BedRecord.Strand.REVERSE_STRAND: start -= 1 else: raise ValueError('Strand must be set.') return start, end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def labelpos(self):\n return self._labelpos", "def get_ref_and_start_and_offset(forward_ref_sequence: str,\n strand: bed_pb2.BedRecord.Strand,\n chrom_start: int,\n chrom_end: int) -> Tuple[str, int, int]:\n r...
[ "0.6364321", "0.6140304", "0.61087877", "0.60330933", "0.60321313", "0.575407", "0.5750131", "0.57237166", "0.55922985", "0.55865574", "0.55369616", "0.5511564", "0.5482404", "0.5407526", "0.53941387", "0.53722996", "0.5353169", "0.5347849", "0.53471684", "0.53188986", "0.528...
0.6887572
0
Gets subreads/encoded field from example as a string.
def get_encoded_subreads_from_example(example): return example.features.feature['subreads/encoded'].bytes_list.value[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_field(self, bib_entry, field):\n output = bib_entry.fields[field] if field in bib_entry.fields else \"\"\n return self.strip_braces(output)", "def __str__(self):\n outstr = self._field1\n return outstr", "def get_encoded_label_from_example(example):\n return example.feature...
[ "0.5705618", "0.5460794", "0.5459715", "0.539829", "0.5357855", "0.5356727", "0.5356727", "0.5356539", "0.53236294", "0.5237667", "0.5237599", "0.5225943", "0.5169422", "0.51572955", "0.5146009", "0.5126784", "0.51213324", "0.51131326", "0.5083494", "0.5076718", "0.5053751", ...
0.70664877
0
Gets the subreads/shape field from example as a list of int64.
def get_subreads_shape_from_example(example): assert len(example.features.feature['subreads/shape'].int64_list.value) == 3 return example.features.feature['subreads/shape'].int64_list.value[:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_encoded_subreads_from_example(example):\n return example.features.feature['subreads/encoded'].bytes_list.value[0]", "def read_ints(self):\n return self.numbers", "def as_list(self) -> List[int]:\n return self.my_partition", "def get_list_of_int2(self):\n pass", "def getIntArra...
[ "0.6184817", "0.5882475", "0.5881324", "0.57822245", "0.57525074", "0.56289333", "0.5594792", "0.5497891", "0.54603356", "0.5455274", "0.5443167", "0.54085", "0.53583235", "0.5348249", "0.53445643", "0.53237766", "0.53161526", "0.53096575", "0.5279014", "0.52352875", "0.52090...
0.7593962
0
Gets the subreads/num_passes field from example as a list of int64.
def get_num_passes_from_example(example): assert len( example.features.feature['subreads/num_passes'].int64_list.value) == 1 return example.features.feature['subreads/num_passes'].int64_list.value[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getRefReads(self):# -> int\n return self.refReads", "def list_of_runnums (ins, exp) :\n try : expruns = experiment_info.experiment_runs(ins, exp)\n #if exp == 'xcs83814' : return []\n except : return []\n\n return [int(rec['num']) for rec in expruns]\n #runs = experiment_info.experiment...
[ "0.5838554", "0.57468516", "0.57462114", "0.55311155", "0.5446684", "0.5408164", "0.5309831", "0.5301768", "0.527564", "0.52182186", "0.51577634", "0.5125342", "0.5124437", "0.51199293", "0.51196676", "0.5108761", "0.506709", "0.5051076", "0.5049883", "0.5034971", "0.5034971"...
0.78519976
0
Gets label/encoded field from example as a string.
def get_encoded_label_from_example(example): return example.features.feature['label/encoded'].bytes_list.value[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def label_from_example(example):\n val = example.features.feature['label'].int64_list.value\n if val:\n return int(val[0])\n else:\n return None", "def get_label(self, which_label: str, extra_label: str) -> str:\n result = self.row_dict.get(extra_label)\n if result:\n # We will ...
[ "0.6567466", "0.6203385", "0.6174128", "0.6174128", "0.6174128", "0.6174128", "0.60609", "0.60340345", "0.5977775", "0.59713846", "0.5863954", "0.58526266", "0.58526266", "0.58526266", "0.57978487", "0.5788342", "0.57807505", "0.57807505", "0.57807505", "0.57807505", "0.57807...
0.7369651
0
Gets the label/shape field from example as a list of int64.
def get_label_shape_from_example(example): assert len(example.features.feature['label/shape'].int64_list.value) == 1 return example.features.feature['label/shape'].int64_list.value[:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def label_from_example(example):\n val = example.features.feature['label'].int64_list.value\n if val:\n return int(val[0])\n else:\n return None", "def provide_label(self):\n return [(k, v.shape) for k, v in self.label]", "def provide_label(self):\r\n return [(k, tuple([1] + list(v.shape...
[ "0.679036", "0.6569586", "0.62951785", "0.6134868", "0.6108419", "0.59921026", "0.59756845", "0.5952071", "0.5952071", "0.59401375", "0.58788294", "0.5849895", "0.5831298", "0.5816761", "0.5816761", "0.5807753", "0.5801871", "0.5795513", "0.5795513", "0.5795513", "0.5794914",...
0.74587005
0
Gets deepconsensus_input/encoded field from example as a string.
def get_encoded_deepconsensus_input_from_example(example): return example.features.feature[ 'deepconsensus_input/encoded'].bytes_list.value[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_encoded_label_from_example(example):\n return example.features.feature['label/encoded'].bytes_list.value[0]", "def get_encoded_subreads_from_example(example):\n return example.features.feature['subreads/encoded'].bytes_list.value[0]", "def deepconsensus_input_to_example(\n deepconsensus_input: dee...
[ "0.6439003", "0.58448774", "0.53348607", "0.5202095", "0.5010533", "0.49677646", "0.49160782", "0.4901157", "0.48838043", "0.4850435", "0.4850435", "0.4814992", "0.48128593", "0.47833014", "0.47751632", "0.46998075", "0.46935028", "0.4684098", "0.46840334", "0.4667676", "0.46...
0.81469035
0
Returns tf.Example created from the given DeepConsensusInput proto.
def deepconsensus_input_to_example( deepconsensus_input: deepconsensus_pb2.DeepConsensusInput, example_height: int, inference: bool, counters: Optional[Dict[str, metrics.Metrics.counter]] = None, ) -> Optional[tf.train.Example]: if not deepconsensus_input.subreads: if counters and counters['examples_no_subreads_counter']: counters['examples_no_subreads_counter'].inc() return # Get the example_width from the first subreads. example_width = len(deepconsensus_input.subreads[0].bases) # The full example will include 4 rows for the signal to noise ratio (sn) # values. The remaining rows will contain three sets of per-base values: # the base, pulse width (pw), and interpulse distance (ip). Some models # may use only a subset of this information downstream. per_base_rows = get_per_base_rows(example_height) if per_base_rows < 0 or per_base_rows % 4 != 0: raise ValueError('example_height - 5 must be non-negative, and divisible ' 'by four.') max_passes = get_max_passes(example_height) if len(deepconsensus_input.subreads) > max_passes: # Increment a counter if the number of subreads from the # deepconsensus_input is more than the `max_passes` derived from the # input `example_height`. # But still continue. if counters and counters['examples_with_discarded_subreads']: counters['examples_with_discarded_subreads'].inc() example = tf.train.Example() features = example.features data = np.zeros( shape=(example_height, example_width, 1), dtype=dc_constants.NP_DATA_TYPE) data += dc_constants.GAP_OR_PAD_INT # Number of subreads is capped at num_subreads. In the cases of fewer # subreads, rows are left empty. kept_subreads = 0 # Add extra dimension so that shape is (example_width, 1). base_indices, pw_indices, ip_indices, strand_indices, ccs_indices, sn_indices = get_indices( max_passes) for i in range(min(len(deepconsensus_input.subreads), max_passes)): subread = deepconsensus_input.subreads[i] # Each tuple should already be padded to the appropriate length. assert len(subread.bases) == example_width encoded_bases = encode_dna_as_floats(subread.bases) # pytype: disable=wrong-arg-types assert encoded_bases is not None data[base_indices[0] + i] += np.expand_dims(np.array(encoded_bases), -1) data[pw_indices[0] + i] += np.expand_dims(np.array(subread.pw), -1) data[ip_indices[0] + i] += np.expand_dims(np.array(subread.ip), -1) data[strand_indices[0] + i] += np.expand_dims( np.expand_dims(np.array(subread.subread_strand), -1), -1) kept_subreads += 1 if kept_subreads == 0: if counters and counters['examples_no_subreads_counter']: counters['examples_no_subreads_counter'].inc() return if deepconsensus_input.ccs_sequence: encoded_ccs_bases = encode_dna_as_floats(deepconsensus_input.ccs_sequence) # pytype: disable=wrong-arg-types data[slice(*ccs_indices)] += np.expand_dims(np.array(encoded_ccs_bases), -1) data[slice(*sn_indices)] += np.expand_dims( np.expand_dims(np.array(deepconsensus_input.sn), -1), -1) features.feature['subreads/encoded'].bytes_list.value.append(data.tostring()) features.feature['subreads/shape'].int64_list.value.extend(data.shape) features.feature['subreads/num_passes'].int64_list.value.append(kept_subreads) if not inference: label_bases_list = encode_dna_as_floats(deepconsensus_input.label.bases) # pytype: disable=wrong-arg-types assert label_bases_list is not None # Final shape of label should be (example_width, ). label_matrix = np.array(label_bases_list).astype(dc_constants.NP_DATA_TYPE) features.feature['label/encoded'].bytes_list.value.append( label_matrix.tostring()) features.feature['label/shape'].int64_list.value.extend(label_matrix.shape) features.feature['deepconsensus_input/encoded'].bytes_list.value.append( deepconsensus_input.SerializeToString()) return example
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_encoded_deepconsensus_input_from_example(example):\n return example.features.feature[\n 'deepconsensus_input/encoded'].bytes_list.value[0]", "def _create_example(self):\n source = np.random.randn(self.batch_size, self.max_decode_length,\n self.input_depth)\n source...
[ "0.6588792", "0.5950223", "0.58684516", "0.5803522", "0.5487936", "0.5469294", "0.5404084", "0.5355273", "0.527753", "0.51956975", "0.5192631", "0.51771414", "0.516648", "0.51630205", "0.51613873", "0.51525664", "0.5150702", "0.5136441", "0.51273745", "0.5113387", "0.511311",...
0.70847815
0
Returns whether input should be in eval or train for current species.
def check_region(deepconsensus_input: deepconsensus_pb2.DeepConsensusInput, species: str, contig_chrom: Dict[str, str]) -> Tuple[bool, bool, bool]: # Eval set contains only molecules that start and end within the bounds. # Train set contains only molecules that are entirely outside of the bounds. # Based on this logic, molecules that span the training and eval regions # will be thrown out entirely. if species == 'ecoli': assert 'ecoli' in deepconsensus_input.chrom_name in_train_region = between(deepconsensus_input.chrom_start, * dc_constants.ECOLI_REGIONS['TRAIN']) and between( deepconsensus_input.chrom_end, * dc_constants.ECOLI_REGIONS['TRAIN']) in_eval_region = between(deepconsensus_input.chrom_start, * dc_constants.ECOLI_REGIONS['EVAL']) and between( deepconsensus_input.chrom_end, * dc_constants.ECOLI_REGIONS['EVAL']) in_test_region = between(deepconsensus_input.chrom_start, * dc_constants.ECOLI_REGIONS['TEST']) and between( deepconsensus_input.chrom_end, * dc_constants.ECOLI_REGIONS['TEST']) elif species == 'human': assert 'ecoli' not in deepconsensus_input.chrom_name # Resolve the chrom name for each contig chrom_name = contig_chrom.get(deepconsensus_input.chrom_name, deepconsensus_input.chrom_name) in_train_region = chrom_name in dc_constants.HUMAN_TRAIN_REGIONS in_eval_region = chrom_name in dc_constants.HUMAN_EVAL_REGIONS in_test_region = chrom_name in dc_constants.HUMAN_TEST_REGIONS else: raise ValueError( f"Invalid species: {species}. Must be either 'human' or 'ecoli.'") return in_train_region, in_eval_region, in_test_region
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_training(self):\n return self.mode == \"train\"", "def is_training(self):\n return self.mode == \"train\"", "def is_training(self):\n return self._labels_one_hot is not None", "def is_training(self):\n return (\n self.detector.training\n # and self.recognizer.trai...
[ "0.69932437", "0.69932437", "0.6552823", "0.6470823", "0.6207395", "0.62030923", "0.6136686", "0.6063968", "0.59703904", "0.5943829", "0.59267473", "0.58717257", "0.58691746", "0.5867876", "0.5831515", "0.5829699", "0.5804761", "0.5675888", "0.56597865", "0.56266797", "0.5625...
0.0
-1
Returns an integer for the data split for the given deepconsensus_input.
def train_eval_partition_fn( deepconsensus_input: deepconsensus_pb2.DeepConsensusInput, num_partitions: int, species: str, contig_chrom: Dict[str, str]) -> int: assert num_partitions == 4 in_train_region, in_eval_region, in_test_region = check_region( deepconsensus_input, species, contig_chrom) if in_train_region: return 0 elif in_eval_region: return 1 elif in_test_region: return 2 else: return 3
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def split_count(self) -> int:\n return int(self.graph_tuple_stats.split_count or 0)", "def _get_split_indices(self):\n\n cumsum = np.cumsum(\n np.concatenate((np.array([0], dtype=np.int8), self.split_sizes)))\n \n fold_inds = np.array(\n [(cumsum[n], cumsum[n + 1]) f...
[ "0.5873781", "0.5608078", "0.5402677", "0.53813106", "0.52235", "0.52235", "0.52235", "0.5191688", "0.5122822", "0.5101202", "0.50942945", "0.5074645", "0.50467694", "0.5011611", "0.5003356", "0.50026923", "0.49957234", "0.49891073", "0.49884978", "0.496605", "0.49529505", ...
0.4727582
45
Returns a list of empty column indices.
def get_empty_columns( dc_input: deepconsensus_pb2.DeepConsensusInput) -> List[int]: columns_to_remove = [] for i in range(len(dc_input.subreads[0].bases)): all_internal_gaps = True for subread in dc_input.subreads: if subread.bases[i] != dc_constants.GAP_OR_PAD: all_internal_gaps = False break if all_internal_gaps: columns_to_remove.append(i) return columns_to_remove
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_undef_cols_idx(x, undef_val):\n undef_col_idx = []\n for col_idx in range(x.shape[1]):\n column = x[:, col_idx]\n if((column == undef_val).all()):\n undef_col_idx.append(col_idx)\n\n return undef_col_idx", "def get_empty_cells(state):\n cells = []\n for row_index, ...
[ "0.69981074", "0.6958577", "0.69492024", "0.67620707", "0.6651748", "0.66420007", "0.6605788", "0.6539305", "0.6522109", "0.64973074", "0.6485834", "0.6461882", "0.64566773", "0.6454144", "0.64250505", "0.6408465", "0.6384017", "0.63711303", "0.63505524", "0.6279498", "0.6273...
0.6780791
3
Add external padding to bases, PW, IP, and cigar.
def pad_bases_pw_ip_cigar(read: deepconsensus_pb2.Subread, padded_len: int) -> None: pad_amt = padded_len - len(read.bases) if pad_amt > 0: str_padding = dc_constants.GAP_OR_PAD * pad_amt list_padding = [dc_constants.GAP_OR_PAD_INT] * pad_amt read.bases = read.bases + str_padding read.pw[:] = list(read.pw) + list_padding read.ip[:] = list(read.ip) + list_padding read.expanded_cigar = read.expanded_cigar + str_padding
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _add_padding(input_str):\r\n padding_len = AES.block_size - len(input_str) % AES.block_size\r\n return input_str + padding_len * chr(padding_len)", "def add_padding(im, pad):\n\n return np.pad(im, pad_width=((pad, pad), (pad, pad), (0, 0)), mode='symmetric')", "def pad(data):\r\n bytes_...
[ "0.6520033", "0.62590957", "0.61074096", "0.6048786", "0.60357", "0.6028013", "0.6009145", "0.60039216", "0.59985995", "0.5989889", "0.5911762", "0.5902912", "0.5881732", "0.5876407", "0.58472306", "0.5836514", "0.58284765", "0.58035165", "0.5787002", "0.57860774", "0.5778415...
0.7777972
0
Collects all counter data and outputs to JSON file.
def metrics_to_json(pipeline_result, fname): metric_results = pipeline_result.metrics().query() results = {} for counter in metric_results['counters']: counter_name = counter.key.step + ':' + counter.key.metric.name results[counter_name] = counter.result with tf.io.gfile.GFile(fname, 'w') as f: f.write(json.dumps(results, indent=4, sort_keys=True))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write():\n output_data = book_list_manipulation()\n\n # Create data directory\n try:\n os.mkdir(DATA_DIR)\n except FileExistsError:\n pass # Ignore - if directory exists, don't need to do anything.\n\n with open(BOOKS_FILE_NAME, 'w') as f:\n json.dump(output_data, f)\n\n ...
[ "0.6897171", "0.65699464", "0.655101", "0.6260423", "0.60603076", "0.60049134", "0.58612525", "0.58312637", "0.58150655", "0.5782462", "0.5774704", "0.57425416", "0.56975865", "0.5643802", "0.5629753", "0.56237644", "0.5607349", "0.55825114", "0.5539956", "0.55331606", "0.552...
0.52685857
57
Return row indices for bases/PW/IP/SN in tf.Example subreads array.
def get_indices(max_passes: int) -> Iterable[Tuple[int, int]]: base_indices = (0, max_passes) pw_indices = (max_passes, max_passes * 2) ip_indices = (max_passes * 2, max_passes * 3) strand_indices = (max_passes * 3, max_passes * 4) ccs_indices = (max_passes * 4, max_passes * 4 + 1) sn_indices = (max_passes * 4 + 1, max_passes * 4 + 5) return base_indices, pw_indices, ip_indices, strand_indices, ccs_indices, sn_indices
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_subreads_shape_from_example(example):\n assert len(example.features.feature['subreads/shape'].int64_list.value) == 3\n return example.features.feature['subreads/shape'].int64_list.value[:]", "def get_encoded_subreads_from_example(example):\n return example.features.feature['subreads/encoded'].bytes_li...
[ "0.6031639", "0.58456427", "0.5577519", "0.54927975", "0.53644127", "0.53457946", "0.5316935", "0.53025067", "0.52801096", "0.52456707", "0.5232305", "0.5213919", "0.52041537", "0.519936", "0.51455504", "0.5135533", "0.51329434", "0.5126514", "0.5122314", "0.51185924", "0.511...
0.46289027
99
Returns the number of rows for bases/PW/IP.
def get_per_base_rows(example_height: int) -> int: return example_height - 5
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getNumRows(self) -> int:\n ...", "def get_total_rows(max_passes: int) -> int:\n # For each of `max_subreads`, we have three pieces of information: bases, PW,\n # and IP. We also have four rows for SN, and one for strand.\n # The information is structured as follows:\n # Bases: (0, params.max_passe...
[ "0.7275314", "0.6997064", "0.6890674", "0.6787566", "0.65937537", "0.6576061", "0.65256315", "0.65069455", "0.6501978", "0.64683366", "0.6468044", "0.64620405", "0.6461119", "0.6461119", "0.6458274", "0.64385223", "0.6435857", "0.64277416", "0.64216626", "0.6378092", "0.63566...
0.0
-1
Returns the max passes for bases/PW/IP.
def get_max_passes(example_height: int) -> int: return (example_height - 5) // 4
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def max_pw(self, entity):\n return float(entity['pw_bb'][1])", "def get_password_count(frm, to, is_adjascent):\n\n num = frm\n\n # make number compatible with #1\n if num < 100000:\n num = 100000\n\n digits = []\n while num > 0:\n digit = num % 10\n digits.append(digit)...
[ "0.6741339", "0.60329866", "0.58437866", "0.58013153", "0.5779518", "0.57709515", "0.57115567", "0.56688434", "0.5657231", "0.5628787", "0.5628583", "0.5627118", "0.5619595", "0.56186515", "0.56177336", "0.55893004", "0.55542743", "0.5524528", "0.55046046", "0.5483269", "0.54...
0.6484286
1
Returns total rows in input tf.Examples. Update if other signals added.
def get_total_rows(max_passes: int) -> int: # For each of `max_subreads`, we have three pieces of information: bases, PW, # and IP. We also have four rows for SN, and one for strand. # The information is structured as follows: # Bases: (0, params.max_passes - 1) represent bases. # PW: rows params.max_passes to (params.max_passes * 2 - 1) # IP: rows (params.max_passes * 2) to (params.max_passes * 3 - 1) # Strand: rows (params.max_passes * 3) to (params.max_passes * 4) # CCS+SN: rows (params.max_passes * 4 + 1) to (params.max_passes * 4 + 5) # The last five rows are CCS sequence (1), and SN (4). return (max_passes * 4) + 5
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def total_action(self, samples):\n if tf.executing_eagerly():\n return [self._total_action(sample) for sample in samples]\n else:\n total_actions = []\n for idx in range(samples.shape[0]):\n total_actions.append(self._total_action(samples[idx]))\n\n ...
[ "0.5810911", "0.58098763", "0.5807444", "0.5798802", "0.57397205", "0.5658059", "0.5558251", "0.5489365", "0.548826", "0.5462633", "0.54614043", "0.5459259", "0.534666", "0.53411347", "0.5280334", "0.5276176", "0.5237991", "0.5232198", "0.521096", "0.5203806", "0.5198669", ...
0.0
-1
You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the corporate firewall only allows communication with certain external IP addresses. You've retrieved the list of blocked IPs from the firewall, but the list seems to be messy and poorly maintained, and it's not clear which IPs are allowed. Also, rather than being written in dotdecimal notation, they are written as plain 32bit integers, which can have any value from `0` through `4294967295`, inclusive. >>> range(0, 1 << 32) range(0, 4294967296) For example, suppose only the values `0` through `9` were valid, and that you retrieved
def part_1(ranges: 'RangeSet') -> int: first_allowed = ranges.ranges[0].vmax + 1 print(f"part 1: first allowed IP address is {first_allowed}") return first_allowed
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_blocked_ips(logger, dashboard_log, firewall_ip_and_port):\n try:\n request = requests.get(f\"http://{firewall_ip_and_port}/firewall/blocked\")\n if request.ok:\n return request.json()\n else:\n logger.warning(f\"Getting blocked IPs on firewall failed with code ...
[ "0.65552336", "0.653822", "0.6169756", "0.60734904", "0.5952758", "0.59380877", "0.5932582", "0.5926422", "0.59197193", "0.58556575", "0.5747657", "0.5745601", "0.5732427", "0.5690625", "0.5681859", "0.565295", "0.5644264", "0.5615798", "0.5614454", "0.56106305", "0.56051016"...
0.53981274
39
How many IPs are allowed by the blacklist? >>> example_blacklist = RangeSet.from_file(data_path(__file__, 'example.txt')) >>> print(example_blacklist) 02, 48 >>> part_2(example_blacklist, total_ips_count=10)
def part_2(ranges: 'RangeSet', total_ips_count: int = 1 << 32) -> int: allowed_count = total_ips_count - len(ranges) print(f"part 2: there are total {allowed_count} allowed IPs") return allowed_count
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_count():\n\n config = configparser.ConfigParser()\n config.read('config.ini')\n\n while True:\n try:\n for user in get_count_request():\n ip, count, protocol = str(user[0][0]), user[1][0], str(user[2][0])\n if count >= int(config[protocol]['Count R...
[ "0.57934356", "0.5705135", "0.56226957", "0.5578852", "0.5336283", "0.5191611", "0.5136622", "0.51027375", "0.50659984", "0.5059147", "0.50535524", "0.49664873", "0.49608132", "0.49188912", "0.4906973", "0.48834145", "0.4876514", "0.48726276", "0.48689985", "0.48537868", "0.4...
0.80164754
0
Logical conjuction of two ranges. Result contains only items present in both. >>> Range(10, 20) & Range(1, 3) >>> Range(10, 20) & Range(1, 10) Range(10, 10) >>> Range(10, 20) & Range(1, 13) Range(10, 13) >>> Range(10, 20) & Range(1, 20) Range(10, 20) >>> Range(10, 20) & Range(1, 24) Range(10, 20) >>> Range(10, 20) & Range(10, 10) Range(10, 10) >>> Range(10, 20) & Range(10, 12) Range(10, 12) >>> Range(10, 20) & Range(10, 20) Range(10, 20) >>> Range(10, 20) & Range(10, 23) Range(10, 20) >>> Range(10, 20) & Range(12, 12) Range(12, 12) >>> Range(10, 20) & Range(12, 14) Range(12, 14) >>> Range(10, 20) & Range(12, 20) Range(12, 20) >>> Range(10, 20) & Range(12, 24) Range(12, 20) >>> Range(10, 20) & Range(20, 20) Range(20, 20) >>> Range(10, 20) & Range(20, 22) Range(20, 20) >>> Range(10, 20) & Range(23, 23) >>> Range(10, 20) & Range(23, 25)
def __and__(self, other): if not isinstance(other, Range): raise TypeError( f"unsupported operand types for &: " f"{type(self).__name__!r} and {type(other).__name__!r}" ) if self == other: return Range(self.vmin, self.vmax) elif self < other or self > other: return None return Range( vmin=max(self.vmin, other.vmin), vmax=min(self.vmax, other.vmax) )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ranges_overlap(start1, end1, start2, end2):\n return start1 <= end2 and end1 >= start2", "def range_overlap(range1, range2):\n return range(max(range1[0], range2[0]), min(range1[1], range2[1]))", "def _range_overapped(self, x, y):\n xs = set( range(x[0], x[1]))\n ys = set( range(y[0], y...
[ "0.72496474", "0.7158049", "0.7120407", "0.6979908", "0.68854594", "0.6853533", "0.67700535", "0.6710642", "0.6542877", "0.6497002", "0.64834404", "0.64154637", "0.639729", "0.63906246", "0.6287205", "0.6254796", "0.6190523", "0.6189412", "0.610187", "0.6071944", "0.60403895"...
0.6669906
8
Logical disjunction of two ranges. Contains items present in either. However if the two ranges are disjunct (no common items), `None` is returned. >>> Range(10, 20) | Range(1, 3) >>> Range(10, 20) | Range(1, 9) Range(1, 20) >>> Range(10, 20) | Range(1, 10) Range(1, 20) >>> Range(10, 20) | Range(1, 14) Range(1, 20) >>> Range(10, 20) | Range(1, 20) Range(1, 20) >>> Range(10, 20) | Range(1, 25) Range(1, 25) >>> Range(10, 20) | Range(9, 9) Range(9, 20) >>> Range(10, 20) | Range(9, 15) Range(9, 20) >>> Range(10, 20) | Range(9, 22) Range(9, 22) >>> Range(10, 20) | Range(10, 10) Range(10, 20) >>> Range(10, 20) | Range(10, 20) Range(10, 20) >>> Range(10, 20) | Range(10, 22) Range(10, 22) >>> Range(10, 20) | Range(14, 17) Range(10, 20) >>> Range(10, 20) | Range(14, 20) Range(10, 20) >>> Range(10, 20) | Range(14, 23) Range(10, 23) >>> Range(10, 20) | Range(20, 21) Range(10, 21) >>> Range(10, 20) | Range(21, 21) Range(10, 21) >>> Range(10, 20) | Range(21, 24) Range(10, 24) >>> Range(10, 20) | Range(22, 22) >>> Range(10, 20) | Range(22, 24)
def __or__(self, other): if not isinstance(other, Range): raise TypeError( f"unsupported operand types for |: " f"{type(self).__name__!r} and {type(other).__name__!r}" ) if self == other: return Range(self.vmin, self.vmax) elif self.vmax < other.vmin - 1: return None elif self.vmin > other.vmax + 1: return None return Range( vmin=min(self.vmin, other.vmin), vmax=max(self.vmax, other.vmax) )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ranges_overlap(start1, end1, start2, end2):\n return start1 <= end2 and end1 >= start2", "def overlap(start1, end1, start2, end2):\n return not (end1 < start2 or end2 < start1)", "def __and__(self, other):\n if not isinstance(other, Range):\n raise TypeError(\n f\"uns...
[ "0.66074175", "0.64702195", "0.6391564", "0.63127744", "0.6272544", "0.618147", "0.6166346", "0.60126203", "0.598657", "0.5985955", "0.58613884", "0.5857347", "0.5855965", "0.58527166", "0.5840612", "0.58333844", "0.5826907", "0.580981", "0.57973963", "0.5791664", "0.576489",...
0.6901047
0
AllOfCreateClaimResponseClaim a model defined in Swagger
def __init__(self, donor_participant: Object=None, id: str=None, status: str=None, resolution_period_end: datetime=None, completion_period_end: datetime=None, last_modified: datetime=None): # noqa: E501 self.swagger_types = { 'donor_participant': Object, 'id': str, 'status': str, 'resolution_period_end': datetime, 'completion_period_end': datetime, 'last_modified': datetime } self.attribute_map = { 'donor_participant': 'DonorParticipant', 'id': 'Id', 'status': 'Status', 'resolution_period_end': 'ResolutionPeriodEnd', 'completion_period_end': 'CompletionPeriodEnd', 'last_modified': 'LastModified' } self._donor_participant = donor_participant self._id = id self._status = status self._resolution_period_end = resolution_period_end self._completion_period_end = completion_period_end self._last_modified = last_modified
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def from_dict(cls, dikt) -> 'AllOfCreateClaimResponseClaim':\n return util.deserialize_model(dikt, cls)", "def post(self):\n dao = ClaimDao()\n return dao.create(api.payload)", "def post(self, request, *args, **kwargs):\n\n\t\tself.object = self.get_object()\n\t\tform_class = self.get_form...
[ "0.61444366", "0.5865234", "0.5225908", "0.5092452", "0.50891614", "0.50711375", "0.5046432", "0.4988137", "0.49762765", "0.49616015", "0.49274784", "0.48975945", "0.48603255", "0.48596394", "0.48490882", "0.48469844", "0.4788117", "0.4787606", "0.478167", "0.47453433", "0.47...
0.0
-1
Returns the dict as a model
def from_dict(cls, dikt) -> 'AllOfCreateClaimResponseClaim': return util.deserialize_model(dikt, cls)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def from_dict(cls, dikt) -> 'ModelClass':\n return util.deserialize_model(dikt, cls)", "def to_dict_model(self) -> dict:\n return dict((key, getattr(self, key)) for key in self.__mapper__.c.keys())", "def from_dict(cls, dikt):\n return util.deserialize_model(dikt, cls)", "def from_dict(cls, ...
[ "0.69416064", "0.6844471", "0.67740417", "0.67740417", "0.67740417", "0.67740417", "0.67740417", "0.67740417", "0.6739098", "0.66997623", "0.66997623", "0.66453665", "0.6639819", "0.66035503", "0.6600892", "0.65996236", "0.659477", "0.6580991", "0.65615076", "0.64162004", "0....
0.0
-1
Gets the donor_participant of this AllOfCreateClaimResponseClaim.
def donor_participant(self) -> Object: return self._donor_participant
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def donor_participant(self, donor_participant: Object):\n\n self._donor_participant = donor_participant", "def participant(self) -> AllOfCancelClaimRequestParticipant:\n return self._participant", "def participant(self) -> AllOfAcknowledgeClaimRequestParticipant:\n return self._participant...
[ "0.64143723", "0.62174505", "0.5898315", "0.50857437", "0.49990976", "0.48347864", "0.48060545", "0.46557683", "0.45774764", "0.45774764", "0.45192257", "0.4476471", "0.44539085", "0.4446725", "0.4414176", "0.43843213", "0.43202215", "0.43045747", "0.42562267", "0.42562267", ...
0.7721172
0
Sets the donor_participant of this AllOfCreateClaimResponseClaim.
def donor_participant(self, donor_participant: Object): self._donor_participant = donor_participant
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def participant(self, participant: AllOfCancelClaimRequestParticipant):\n if participant is None:\n raise ValueError(\"Invalid value for `participant`, must not be `None`\") # noqa: E501\n\n self._participant = participant", "def donor_participant(self) -> Object:\n return self._...
[ "0.60350543", "0.6025046", "0.55765235", "0.5541427", "0.515288", "0.4857232", "0.47399157", "0.4663719", "0.4635826", "0.45958862", "0.4552072", "0.44890487", "0.44712678", "0.44042704", "0.43036908", "0.426201", "0.42143816", "0.41979194", "0.41707268", "0.41660166", "0.416...
0.7887795
0
Gets the id of this AllOfCreateClaimResponseClaim.
def id(self) -> str: return self._id
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def claim_id(self) -> str:\n return self._claim_id", "def claim_id(self) -> str:\n return self._claim_id", "def post(self):\n dao = ClaimDao()\n return dao.create(api.payload)", "def participant(self) -> AllOfAcknowledgeClaimRequestParticipant:\n return self._participant", ...
[ "0.64186335", "0.64186335", "0.56785434", "0.5100735", "0.5089649", "0.49505824", "0.4929038", "0.478927", "0.47847793", "0.4719559", "0.46991652", "0.46991652", "0.46991652", "0.46991652", "0.46991652", "0.46991652", "0.46991652", "0.46991652", "0.46991652", "0.46991652", "0...
0.0
-1
Sets the id of this AllOfCreateClaimResponseClaim.
def id(self, id: str): if id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_id(self, id):\n self.data['id'] = id", "def id(self, _id):\n self.metadata[\"id\"] = _id", "def set_id(self, id):\n self.__id = id", "def set_id(self, id_):\n\n self.id_ = id_", "def claim_id(self, claim_id: str):\n if claim_id is None:\n raise ValueErr...
[ "0.54797524", "0.54327804", "0.5338967", "0.53236276", "0.529317", "0.529317", "0.5160128", "0.5160128", "0.5160128", "0.5160128", "0.5160128", "0.5097142", "0.5097142", "0.5097142", "0.5097142", "0.5097142", "0.5097142", "0.5097142", "0.5097142", "0.5097142", "0.5097142", ...
0.0
-1
Gets the status of this AllOfCreateClaimResponseClaim.
def status(self) -> str: return self._status
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def status(self):\n props = self.properties\n if props:\n if props.get('created'):\n return CREATED_STATUS", "def post(self):\n dao = ClaimDao()\n return dao.create(api.payload)", "def create(self):\n return (True == self.client.put(self.name).getBodyD...
[ "0.572883", "0.55275935", "0.54706526", "0.52699614", "0.5234164", "0.5156991", "0.48911265", "0.48664638", "0.48566645", "0.4801761", "0.48016563", "0.47769982", "0.47740877", "0.47602236", "0.47471672", "0.47409746", "0.47378886", "0.4730465", "0.47272745", "0.47255358", "0...
0.0
-1
Sets the status of this AllOfCreateClaimResponseClaim.
def status(self, status: str): allowed_values = ["OPEN", "WAITING_RESOLUTION", "CONFIRMED", "CANCELLED", "COMPLETED"] # noqa: E501 if status not in allowed_values: raise ValueError( "Invalid value for `status` ({0}), must be one of {1}" .format(status, allowed_values) ) self._status = status
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _create_status(self):\n if self.headers['Accept'] != CONTENT_TYPE_STATUS:\n raise NotAcceptable()\n\n body = self.server.status()\n self._write_response(\n 200, body,\n content_type='application/se.novafaen.smrt.status.v1+json'\n )\n self.serv...
[ "0.53387874", "0.524753", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "0.5092425", "...
0.4550052
73
Calculates the average value of the input Iterable
def mean(arr) -> float: return sum(arr) / len(arr)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def avg(iterable: Iterable[Num]) -> float:\n\t\n\tsum_nums = 0\n\tnums = 0\n\t\n\tfor num in iterable:\n\t\tsum_nums += num\n\t\tnums += 1\n\t\n\treturn sum_nums / nums", "def get_mean(iterable):\n return sum(iterable) / len(iterable)", "def avg():\n\n # call sum method to add up the values in the collec...
[ "0.82791936", "0.8164016", "0.7948333", "0.77014303", "0.76806027", "0.76771253", "0.76729006", "0.7657194", "0.7613426", "0.76085293", "0.7587937", "0.75077236", "0.75077236", "0.74497366", "0.74372065", "0.74268806", "0.7406749", "0.73995304", "0.7372481", "0.73616016", "0....
0.6803765
58
Converts the label data to the darkflow data format (i.e. PASCAL VOC XML).
def convert_to_frcnn(label: [], image_path: str, **_) -> []: # Get the label data in the dataset format unicode, xmin, ymin, abs_bb_width, abs_bb_height = label.split() # Make sure the class is a string class_name = str(unicode) # Cast each data to int xmin = int(xmin) ymin = int(ymin) abs_bb_width = int(abs_bb_width) abs_bb_height = int(abs_bb_height) # Calculate the top-right coordinates of the bounding box xmax = xmin + abs_bb_width ymax = ymin + abs_bb_height return [to_file_name(image_path, 'jpg'), xmin, ymin, xmax, ymax, class_name]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def y_to_label(self, data, Y):\n pass", "def load_data_labels(datasets):\n # Split by words\n x_text = datasets['data']\n x_text = [clean_str(sent) for sent in x_text]\n # Generate labels\n labels = []\n for i in range(len(x_text)):\n label = [0 for j in datasets['target_names']]\...
[ "0.6137673", "0.5961593", "0.59443146", "0.59186745", "0.584485", "0.5839062", "0.5764928", "0.57603544", "0.5754929", "0.5716596", "0.5684225", "0.5682574", "0.56750673", "0.5612308", "0.56088096", "0.5605491", "0.56001645", "0.5592615", "0.5586834", "0.558137", "0.5561916",...
0.5274742
53
Writes an annotation on file according to the darkflow format.
def write_as_frcnn(annotation: pd.DataFrame, path_to_annotations: str, image_id: str): annotation.to_csv(os.path.join(path_to_annotations, '..', 'annotations.txt'), header=None, index=None, mode='a', sep=',')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def writeAnnotations(b, f, ld, n=0):\n \n if args.format.lower() == 'kitti':\n writeKitty(b, os.path.join(ld, \"%06d.txt\" % n))\n elif args.format.lower() == 'voc':\n writeVOC(b, ld, f)\n elif args.format.lower() == 'darknet':\n writeDarknet(b, os.path.join(ld, \"%06d.txt\" % n))"...
[ "0.6668815", "0.6605532", "0.6497272", "0.6436646", "0.64314204", "0.6285113", "0.624797", "0.624234", "0.6178932", "0.6084837", "0.6082922", "0.6038828", "0.5981543", "0.59467894", "0.5830986", "0.5830986", "0.5819359", "0.5800235", "0.5796739", "0.57627714", "0.57070196", ...
0.67075735
0
Given an offset, plaintext, and oracle, forges a block with the proper padding.
def forge_block(offset, plaintext, oracle): b_size, _, _ = challenge_12.determine_block_stats(oracle) new_padding = b"A" * (b_size - offset) payload = new_padding + challenge_09.pkcs7(plaintext, b_size) ciphertext = oracle(payload) return challenge_07.as_blocks(ciphertext, b_size)[1]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def forge_padding_block(oracle):\n b_size, pt_size, padding = challenge_12.determine_block_stats(oracle)\n new_padding = b\"A\" * padding\n\n return challenge_07.as_blocks(oracle(new_padding), b_size)[-1]", "def encrypt(text, offset):\r\n\r\n return format_text(text, offset)", "def pkcs7_pad(blockl...
[ "0.7168934", "0.5863658", "0.5846171", "0.5747094", "0.574332", "0.5658577", "0.5591082", "0.5590468", "0.54089946", "0.53620017", "0.53189814", "0.5233698", "0.52017486", "0.517661", "0.51744473", "0.512005", "0.50064063", "0.49992564", "0.49891132", "0.4943387", "0.489504",...
0.7434226
0
Given an oracle, forges a block with all PKCS7 padding (which occurs when the length of a plaintext is an integer multiple of the block size)
def forge_padding_block(oracle): b_size, pt_size, padding = challenge_12.determine_block_stats(oracle) new_padding = b"A" * padding return challenge_07.as_blocks(oracle(new_padding), b_size)[-1]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def forge_block(offset, plaintext, oracle):\n b_size, _, _ = challenge_12.determine_block_stats(oracle)\n new_padding = b\"A\" * (b_size - offset)\n payload = new_padding + challenge_09.pkcs7(plaintext, b_size)\n ciphertext = oracle(payload)\n\n return challenge_07.as_blocks(ciphertext, b_size)[1]",...
[ "0.718337", "0.7012611", "0.6525299", "0.63634807", "0.6312443", "0.62574965", "0.6204864", "0.61596626", "0.6152799", "0.6040315", "0.5880037", "0.58678126", "0.581205", "0.5769569", "0.57621455", "0.57519305", "0.572222", "0.5710781", "0.5623784", "0.56190366", "0.5612416",...
0.7988467
0
Acts as an oracle for profile_for. This is the only function we're allowed to rely on.
def new_profile(email): key = challenge_12.deterministic_random_key() profile = bytes(profile_for(email.decode()), 'ascii') return challenge_11.AES_ECB(key).encrypt(profile)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getprofile(): # real signature unknown; restored from __doc__\n pass", "def profile(engine = sqlalchemy.engine.Engine, user_context_fn = None):\n def inner_profile(fn):\n def dec(*args, **kwargs):\n sqltap.start(engine, user_context_fn)\n retval = fn(*args, **kwargs)\n ...
[ "0.62559366", "0.62170845", "0.58034307", "0.5680892", "0.5522953", "0.541052", "0.5406572", "0.53861845", "0.5345342", "0.5325694", "0.5305106", "0.52333766", "0.5215422", "0.52097315", "0.5190378", "0.51885676", "0.513023", "0.5117824", "0.5116405", "0.51126146", "0.5085558...
0.4842415
45
Adapted from the original R version (below) by Sebastian Santibanez. The input is a multipolygon, The output is a "merged" version having an envelope that approximately follows the outer contours of the input multipolygon.
def poly_merge(s0, label): if s0.geom_type == 'Polygon': return s0 ff = copy(s0) try: nc = len(s0.geoms) buffer_size = 100.0 while ff.geom_type == 'MultiPolygon' and len(ff.geoms) > 1 and buffer_size <= 500.0: tmp0 = copy(s0) tmp1 = tmp0.buffer(+buffer_size) tmp2 = tmp1.buffer(-buffer_size) ff = shapely.ops.cascaded_union((tmp2, s0)) buffer_size += 50.0 except ValueError: print('!!! Error in poly_merge') return ff
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_merge_stitches_together_a_polygon_surrounding_another_polygon(self):\n topology = {\n \"type\": \"Topology\",\n \"objects\": {\n \"collection\": {\n \"type\": \"GeometryCollection\",\n \"geometries\": [\n ...
[ "0.6109439", "0.59702253", "0.58903515", "0.5820006", "0.5805046", "0.5776796", "0.5732157", "0.57090396", "0.5586127", "0.55370593", "0.54835206", "0.5433876", "0.5397951", "0.5393977", "0.5353541", "0.5344208", "0.5325601", "0.532044", "0.5295884", "0.52933997", "0.52924645...
0.58861524
3
Adapted from the original R version (below) by Sebastian Santibanez. The input is a multipolygon, The output is a "merged" version having an envelope that approximately follows the outer contours of the input multipolygon.
def ortho_merge(s0, label): if s0.geom_type == 'Polygon': return s0 ff = copy(s0) try: #print('### Input multipolygon has %d components' % len(s0.geoms)) nc = len(s0.geoms) buffer_size = 50.0 while ff.geom_type == 'MultiPolygon' and len(ff.geoms) > 1 and buffer_size < 501.0: #print(' running with buffer size %.1f' % buffer_size) tmp0 = copy(s0) tmp1 = tmp0.buffer(+buffer_size, resolution=4, cap_style=2, join_style=2, mitre_limit=2.5) tmp2 = tmp1.buffer(-buffer_size, resolution=4, cap_style=2, join_style=2, mitre_limit=2.5) ff = shapely.ops.cascaded_union((tmp2, s0)) buffer_size += 10.0 except ValueError: print('!!! Error in ortho_merge') # if buffer_size > 499.0: # print('!!! "%s": Orthogonal merge failed -- trying regular merge' % label) # ff = poly_merge(ff, label) return ff
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_merge_stitches_together_a_polygon_surrounding_another_polygon(self):\n topology = {\n \"type\": \"Topology\",\n \"objects\": {\n \"collection\": {\n \"type\": \"GeometryCollection\",\n \"geometries\": [\n ...
[ "0.61078644", "0.5971892", "0.5890539", "0.58850247", "0.5819157", "0.58058804", "0.57754225", "0.5730724", "0.570801", "0.5585666", "0.5536158", "0.54822874", "0.54315966", "0.53967315", "0.53926915", "0.5352254", "0.5344403", "0.53233576", "0.5319642", "0.52958554", "0.5292...
0.51724035
27
Split the dataset with train_percentage
def split_dataset(dataset, train_percentage, feature_headers, target_header): # Split dataset into train and test dataset train_x, test_x, train_y, test_y = train_test_split(dataset[feature_headers], dataset[target_header],train_size=train_percentage) return train_x, test_x, train_y, test_y
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def split_train_test_by_percentage(dataset, train_percentage=0.8):\n train_length = int(len(dataset) * train_percentage)\n return torch.utils.data.random_split(dataset, (train_length, len(dataset) - train_length))", "def split_dataset(dataset, train_percentage, valid_percentage):\n\n # Split dataset int...
[ "0.8460871", "0.8151334", "0.7983524", "0.7791796", "0.76440144", "0.7603226", "0.7581921", "0.7538712", "0.7538712", "0.7535976", "0.7356462", "0.7356462", "0.72785723", "0.72672325", "0.7246208", "0.7207059", "0.71712476", "0.7159764", "0.7064658", "0.7043388", "0.7031485",...
0.769264
4
Reads the file from fin and saves the file in wav format in fout
def convert_to_wav(fin, fout): temp = subprocess.run(["ffmpeg", "-i", fin, fout], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _to_wav(self):\n self._status = 0\n fname = fm.file2wav(self.get_filename()) \n if fname != self.get_filename(): # can change the name\n self._set_filename(fname) # in case of wave transcoding\n self._status = 1", "def convert_wav(src_wav, dst_wav, subtype='PCM_16'...
[ "0.6910893", "0.65897757", "0.6502043", "0.64688486", "0.6411844", "0.63927984", "0.62594163", "0.6213807", "0.61818516", "0.61807996", "0.6094217", "0.6085368", "0.6054992", "0.60524696", "0.603306", "0.602905", "0.6027152", "0.6003981", "0.59826803", "0.5968395", "0.5954145...
0.73223794
0
Accepts the wav audio file and list of segment time stamps. Chunks the audio and calculates CR for each segment.
def compress_segments(map_, wav_id, file_path, segments, outpath): try: audio = AudioSegment.from_wav(file_path) #print("\nSegments:", len(segments)) for _, row in segments.iterrows(): start = row[2] * 1000 end = row[3] * 1000 audio_chunk = audio[start:end] save_path = "{}/{}_chunk_{}_{}.wav".format(outpath, wav_id, start, end) audio_chunk.export(save_path, format='wav') compress_file(map_=map_, name=row[0], save_path=save_path) except Exception as e: print("ERR:",e) print("Failed files:", file_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def file_generator(files: list,\n segment_duration: float,\n sampleRate: int,\n db_thr: float or None = None,\n frame_length: int = 512,\n hop_length: int = 128,\n ) -> None:\n\n I = 0\n J = 0\n\n s...
[ "0.6238923", "0.61585885", "0.6075792", "0.6008546", "0.5894836", "0.56915575", "0.56830144", "0.56657094", "0.5599609", "0.5596106", "0.557374", "0.55563796", "0.5523089", "0.5482275", "0.546422", "0.54632944", "0.54610866", "0.54595274", "0.54484665", "0.5433095", "0.542854...
0.5404852
22
Compresses the file and calculates CR.
def compress_file(map_, name, save_path): size = os.path.getsize(save_path) temp = subprocess.run(["gzip", "-k", save_path]) cr_size = os.path.getsize(save_path+".gz") try: map_[name] = cr_size / size except Exception as e: print(f"File: {save_path}, Ori:{size}, Compr:{cr_size}") print(e) raise ZeroDivisionError temp = subprocess.run(["rm", save_path]) temp = subprocess.run(["rm", save_path+".gz"])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cr(self):\n self._write('\\x0d')", "def add_crc32_to_file(path):\n with open(path, 'rb+') as file:\n buf = file.read()\n print(\"CALCULATED CRC IS:\", crc32(buf))\n file.write(crc32(buf))", "def stripchar(self):\n self.error = 0\n regexobj = re.compile(self.cha...
[ "0.5394303", "0.53660804", "0.5343265", "0.52741724", "0.52679586", "0.514218", "0.51153815", "0.51048565", "0.5099235", "0.5065889", "0.5060104", "0.505069", "0.5048299", "0.4964655", "0.49524233", "0.49461827", "0.4944277", "0.4944277", "0.49384165", "0.492853", "0.49072182...
0.4581151
55
Main function run by each process.
def calc_CR_scp(pid, map_, file_, args, segments=None, start=None, end=None): tqdm_text = "#"+"{}".format(pid).zfill(3) data = file_[start:end] if segments: segments = pd.read_csv(segments, sep = ' ', header=None) with tqdm(total=end-start, desc=tqdm_text, position=pid+1) as pbar: for row in data: sep = ' ' if len(row.split(' ')) > 1 else '\t' for val in row.split(sep): if val[:3] == '/db': fpath = val.strip() args.extn = val.strip().split('.')[-1] break wav_id = row.split(sep)[0] save_path = "{}/{}.wav".format(args.res_dir, wav_id) if args.extn == 'wav': convert_to_wav(fin=fpath, fout=save_path) else: copyfile(fpath, save_path) fpath = save_path if isinstance(segments, pd.DataFrame): segs = segments[segments[1] == wav_id] compress_segments(map_=map_, wav_id=wav_id, file_path=fpath, segments=segs, outpath=args.res_dir) else: compress_file(map_=map_, name=wav_id, save_path=save_path) pbar.update(1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run():\n main()", "def main():\n run_program()", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():", "def main():",...
[ "0.77310705", "0.75580627", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", "0.7300096", ...
0.0
-1
Saves the mapping of utt_id to cr in a file.
def save_file(map_, args): if args.segments: p = os.path.join(args.res_dir, 'compression_'+args.db+"_seg") else: p = os.path.join(args.res_dir, 'compression_'+args.db) with open(p, 'w') as f: for file in map_: f.write("{} {}\n".format(file, map_[file]))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_mappings(self, id_to_char, id_to_radical, id_to_tag):\n self.id_to_char = id_to_char\n self.id_to_radical = id_to_radical\n self.id_to_tag = id_to_tag\n with open(self.mappings_path, 'wb') as f:\n mappings = {\n 'id_to_char': self.id_to_char,\n ...
[ "0.6199283", "0.6053604", "0.59984386", "0.59003353", "0.580108", "0.56833804", "0.5612732", "0.55598855", "0.5496063", "0.5485579", "0.5475674", "0.54297763", "0.54193443", "0.54166305", "0.535604", "0.53454244", "0.5330367", "0.5325239", "0.53230786", "0.5308686", "0.530128...
0.504211
52
Removes all files with certain pattern in the specified directory.
def clean_dir(dir): files = glob.glob(dir) for file in files: os.remove(file)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __clean(path, pattern = '.tiff'):\n for f in os.listdir(path):\n if re.search(pattern, f):\n os.remove(os.path.join(path, f))\n\n print(\"directory cleaned\")", "def rm(pattern, directory=False):\n def safe_remove(path):\n try:\n os.remove(path)\n except OS...
[ "0.785918", "0.77937955", "0.77867496", "0.7549224", "0.7169284", "0.7024768", "0.7019859", "0.700069", "0.6766278", "0.6718952", "0.6631863", "0.65959793", "0.64908284", "0.6448111", "0.6446606", "0.64305115", "0.6400635", "0.63825965", "0.63662213", "0.63377875", "0.6327625...
0.7156662
5
set the message data business_id to a specific value
def step_impl_the_ru_is_set_to(context, business_id): context.bdd_helper.message_data["business_id"] = business_id
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def business_id(self, business_id):\n\n self._business_id = business_id", "def business_phone(self, business_phone):\n\n self._business_phone = business_phone", "def business_phone_number(self, business_phone_number):\n\n self._business_phone_number = business_phone_number", "def bus_ob_...
[ "0.7509327", "0.6467309", "0.63252246", "0.6016918", "0.6016918", "0.59384924", "0.58963674", "0.5866777", "0.5703364", "0.5699451", "0.5621401", "0.56115365", "0.55243134", "0.54495156", "0.5436615", "0.5346349", "0.53436536", "0.53373826", "0.5327274", "0.5308453", "0.52264...
0.7794713
0
Initialize the deviantArt import API.
def __init__(self, useragent: str, **options): self.log = logging.getLogger('lapis.da') self.regex = re.compile(r'^(.*?\.)?((deviantart\.(com|net))|(fav\.me))$') self.regex_direct = re.compile(r'^((www\.)|(orig.*\.))?(deviantart\.net)$') self.useragent = useragent self.headers = {'User-Agent': self.useragent}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, import_: prof.Import) -> None:\n self._import: prof.Import = import_\n self._catalog_interface: Optional[CatalogInterface] = None\n self._catalog: Optional[cat.Catalog] = None", "def init_cloud_api(self, args=None):\n pass", "def setup_class(cls):\n ...
[ "0.6406454", "0.63509434", "0.6281837", "0.61503685", "0.6125607", "0.6073377", "0.60697615", "0.6066569", "0.60615736", "0.603731", "0.6010771", "0.59788716", "0.59780806", "0.594048", "0.5937811", "0.591756", "0.59109753", "0.58900535", "0.588914", "0.5885266", "0.5881022",...
0.0
-1
Download text from a URL.
def read_url(self, url: str) -> str: return requests.get(url, headers=self.headers).text
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def download (url):\n path, url = url\n r = requests.get (url, stream = True)\n content = r.text\n #print (content)\n with open (path + '.txt', 'w') as f:\n f.write (content)", "def download(self, url):\n if url is None:\n return\n user_agent = 'Mozilla/4.0 (compati...
[ "0.77389926", "0.7529618", "0.7323686", "0.72467035", "0.72413325", "0.7207661", "0.7192117", "0.7170477", "0.71116155", "0.7068313", "0.6998971", "0.69944054", "0.69440955", "0.6853805", "0.6850738", "0.6802725", "0.67733735", "0.67682064", "0.6735197", "0.6719944", "0.67052...
0.62080824
61
Import a submission from deviantArt. Ignores flash content. Uses a combination of the DA backend and HTML scraping.
def import_submission(self, submission: praw.objects.Submission) -> dict: try: if self.regex_direct.match(urlsplit(submission.url).netloc): r = requests.head(submission.url, headers=self.headers) mime_text = r.headers.get('Content-Type') mime = mimeparse.parse_mime_type(mime_text) if mime[0] == 'image': self.log.debug('DA link is a direct image') data = {'author': 'An unknown DA author', 'source': submission.url, 'import_urls': [submission.url], 'importer_display': {'header': 'Mirrored deviantArt image ' 'by an unknown author:\n\n'}} return data if not self.regex.match(urlsplit(submission.url).netloc): return None query_url = 'http://backend.deviantart.com/oembed?{}'.format( urlencode({'format': 'json', 'url': submission.url})) self.log.debug('%s is valid DA url.', submission.url) self.log.debug('Querying DA API %s', query_url) response = json.loads(self.read_url(query_url)) if response['type'] not in ('link', 'photo'): self.log.debug('Response is not link or photo') return None self.log.debug('Author name: %s', response['author_name']) # Using the official DA API data = {'author': response['author_name'], 'source': submission.url, 'importer_display': {'header': 'Mirrored deviantArt image by the author "{}":\n\n'.format( response['author_name'])}} if response['type'] == 'link': data['import_urls'] = [response['fullsize_url']] self.log.debug('Found DA API url %s', data['import_urls']) try: # Trying to scrape manually bs = BeautifulSoup(self.read_url(submission.url)) # Checking for flash animation, because mirroring a preview # for a flash animation is stupid is_flash = bool(bs.select('iframe[class~=flashtime]')) is_madefire = bool(bs.select('iframe[class~=madefire-player]')) if is_flash or is_madefire: self.log.info('DA url is flash, no preview needed.') return None # Seems to alternate between the two full_view = (bs.select('img[class~=fullview]') or bs.select('img[class~=dev-content-full]')) if full_view: full_url = full_view[0]['src'] self.log.debug('Found full DA image url: %s', full_url) data['import_urls'] = [full_url] except Exception as e: self.log.error(traceback.format_exc()) if 'import_urls' not in data: self.log.debug('No url found for DA image.') return None return data except Exception as e: self.log.error('Deviantart Error: %s', traceback.format_exc()) return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def scrape_submission(submission_url):\n\n\t'''\n\tScrape Data\n\t'''\n\n\t# Get submission dict\n\tsubmission_dict = reddit.extract_post_data(submission_url=submission_url)\n\n\t# Get list of comments_dicts\n\tsubmission_object = submission_dict.get('submission_object')\n\tcomments_dict = reddit.extract_post_comm...
[ "0.616191", "0.610111", "0.58288443", "0.5678453", "0.5619826", "0.5566439", "0.53977937", "0.5396064", "0.5394963", "0.53024304", "0.52641046", "0.5256734", "0.52327317", "0.5211399", "0.52003515", "0.5163786", "0.5095641", "0.50951064", "0.5082744", "0.50585926", "0.5019451...
0.6888236
0
Parse the url of each book from the book list page. The book's title and url will be stored in database.
def parse_books_from_html(html): root = lxml.html.fromstring(html) for a in root.cssselect("a"): if not 'href' in a.attrib: continue href = a.attrib['href'] if href.startswith("javascript"): continue if not href.startswith("http"): href = urljoin(base_url, href) book_title = a.text_content() d = parse_qs(urlparse(href).query) if 'M' in d and d['M'][0] in ('book', 'Share'): if 'P' in d: book_id = d['P'][0] book = {'id': book_id, 'url': href, 'title': book_title} save_bookpages(book)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_books_url(url):\n url_array = []\n nbr_pages = get_nbr_of_pages(url) \n if(nbr_pages == None):\n nbr_pages = 1\n formatted_url = split_url(url)\n formatted_url = formatted_url.split('page')\n for i in range(1, int(nbr_pages) + 1):\n if nbr_pages != 1:\n join_url =...
[ "0.6903227", "0.64504856", "0.63376325", "0.6297125", "0.6132663", "0.6110711", "0.6098223", "0.607932", "0.605915", "0.6037943", "0.60282815", "0.5987423", "0.5987423", "0.59660596", "0.5940519", "0.59073544", "0.5829715", "0.58157396", "0.57694906", "0.57678217", "0.571373"...
0.6719539
1
Find book id from the given string. The string actually is javascript function.
def find_volume_id(onclick): # find which kind of quote, ' or " quote = "'" start = onclick.find(quote) if start == -1: quote = '"' _id = '' start = onclick.find(quote) end = onclick.rfind(quote) if start != -1 and end != -1: _id = onclick[start+1:end] return _id
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_id(href):\n ID = idRE.search(href)\n if ID:\n return ID.group(1)", "def parse_id(string):\n return string.split('/')[-1]", "def get_id(share_url):\n url = get_redirect_url(share_url)\n id_num = re.findall('(\\d*)\\?', url)[0]\n if id_num.isnumeric():\n return id_num\n ...
[ "0.6068805", "0.59453595", "0.59003705", "0.5802223", "0.57018226", "0.56627494", "0.5654141", "0.56434435", "0.55524117", "0.5543802", "0.55279106", "0.5516342", "0.5503906", "0.54691756", "0.54668176", "0.54620844", "0.5462019", "0.5432368", "0.54040104", "0.5400788", "0.53...
0.54143405
18
Find book id from the given string. The string actually is javascript function. Regular expression version is slower than string find.
def find_volume_id_2(onclick): m = ONCLICK_PATTERN.search(onclick) if not m: return "" if m.group("_id"): return m.group("_id") return ""
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_id(href):\n ID = idRE.search(href)\n if ID:\n return ID.group(1)", "def parse_id(string):\n return string.split('/')[-1]", "def _get_ticket_id(self, str):\n pat = r'^\\s*#(\\d+)'\n try:\n return int(re.search(pat, str).group(1))\n except:\n re...
[ "0.64961225", "0.61931455", "0.6044607", "0.6030908", "0.6029827", "0.596755", "0.5901295", "0.581923", "0.57980543", "0.57835424", "0.573692", "0.5699297", "0.5691912", "0.56668764", "0.566233", "0.5661703", "0.5645024", "0.5621383", "0.5606953", "0.5588029", "0.55868894", ...
0.53995687
27
Find book id from the given string. Using ast to parse script
def find_volume_id_3(onclick): result = "" try: ast_tree = ast.parse(onclick) if ast_tree: result = ast_tree.body[0].value.args[0].s except Exception as ex: print("find_volume_id_3 cannot parse!") print(ex) return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_book(s):\n\n s = s.strip()\n if s == '': raise SyntaxError('The book identification string is empty')\n \n author = ''\n author_start = 0\n author_found = False \n for match in author_regex.finditer(s):\n author_found = True\n author_start = match.start()\n author...
[ "0.6374978", "0.61254185", "0.60788167", "0.58324826", "0.5669414", "0.56683874", "0.5599727", "0.55616546", "0.5541696", "0.5494473", "0.54870814", "0.54786295", "0.5475706", "0.546096", "0.54480183", "0.542894", "0.5400902", "0.53899586", "0.53829354", "0.53328824", "0.5329...
0.5139633
52
According book_id and book type to generate download url.
def convert_to_dl_url(_id, ext): result = list(urlparse(base_url)) result[4] = urlencode({ "M": "d", "P": "{0}.{1}".format(_id, ext)}) return urlunparse(result)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def book_url(cls, identifier, extension='epub', open_access=True, \n data_source=None):\n root = cls.content_root(open_access)\n args = [identifier.type, identifier.identifier]\n args = [urllib.quote(x) for x in args]\n if data_source:\n args.insert(0, urllib....
[ "0.64434534", "0.62948966", "0.62195915", "0.6213017", "0.6177216", "0.6155426", "0.6099401", "0.60772973", "0.6053919", "0.6032619", "0.60254294", "0.5994575", "0.5978039", "0.59481096", "0.57118636", "0.56738925", "0.56277704", "0.5625248", "0.5527539", "0.552491", "0.54898...
0.0
-1
There are sub pages in every category, need to append '1', '2' in P.
def get_suburl(url, page): pr = list(urlparse(url)) param = parse_qs(pr[4]) for k, v in list(param.items()): param[k] = v[0] param["P"] = "{0}-{1}".format(param["P"], page) pr[4] = urlencode(param) return urlunparse(pr)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _create_links_and_track(self, page_name, category_list):\n env = self.state.document.settings.env\n if not hasattr(env, \"categories\"):\n env.categories = {}\n\n link_rst = \"\"\n ncategs = 0\n for categ_name in category_list:\n #categ_name is the full ...
[ "0.60613567", "0.58690304", "0.5866792", "0.55765283", "0.550256", "0.5462847", "0.5384025", "0.5252675", "0.52189535", "0.5210292", "0.5188459", "0.51820177", "0.5163927", "0.5098598", "0.5069502", "0.5050013", "0.50203526", "0.50096536", "0.5005757", "0.49938416", "0.499182...
0.0
-1
This function is used to run / simulate the model.
def updater(environment, data_folder='output_data/', seed=0): # time loop for t in range(environment.parameters['time']): # accruing interest on all deposits for banks for bank in environment.banks: for tranx in bank.accounts: if tranx == "deposits": bank.accounts[tranx] = bank.accounts[tranx] + bank.accounts[tranx] * bank.interest_deposits # accruing interest on all deposits for firms for firm in environment.firms: for tranx in firm.accounts: if tranx == "deposits": firm.accounts[tranx] = firm.accounts[tranx] + firm.accounts[tranx] * environment.parameters["interest_deposits"] # record transaction transact(environment, t, firm, environment.banks[0], tranx, firm.accounts[tranx] * environment.parameters["interest_deposits"], 'interest deposits') # accruing interest on all deposits for households for household in environment.households: for tranx in household.accounts: if tranx == "deposits": household.accounts[tranx] = household.accounts[tranx] + household.accounts[tranx] * environment.parameters["interest_deposits"] # record transaction transact(environment, t, household, environment.banks[1], tranx, household.accounts[tranx] * environment.parameters["interest_deposits"], 'interest deposits') return environment
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run():\n\n # Set up environment and agent\n e = Environment() # create environment (also adds some dummy traffic)\n a = e.create_agent(LearningAgent) # create agent\n e.set_primary_agent(a, enforce_deadline=False) # set agent to track\n\n # Now simulate it\n sim = Simulator(e, update_delay...
[ "0.7496699", "0.742739", "0.73774093", "0.73715323", "0.7242828", "0.72417384", "0.7220512", "0.7125288", "0.7113064", "0.70834154", "0.70769376", "0.7070329", "0.7042441", "0.7035146", "0.69576263", "0.6933849", "0.6923323", "0.69135374", "0.68692625", "0.6793275", "0.679112...
0.0
-1
Post event to all rulesets
def all_events_request(): result = [] message = json.loads(request.stream.read().decode('utf-8')) for ruleset_name in host.list_rulesets(): result.append(host.post(ruleset_name, message)) return jsonify(result)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def post_events(ruleset_name):\n message = json.loads(request.stream.read().decode('utf-8'))\n result = host.post(ruleset_name, message)\n return jsonify(result)", "def __call__(self, event):\n post_event(event, self.baseUrl, self.filterName)", "def _do_rule_processing(self, line, events):\n\n ...
[ "0.5963852", "0.58948195", "0.5618622", "0.55938214", "0.5427861", "0.5391614", "0.53427666", "0.5329339", "0.53197384", "0.531575", "0.53121924", "0.530597", "0.5285532", "0.52750355", "0.52552474", "0.5246069", "0.5223859", "0.52142763", "0.51979613", "0.51774013", "0.51750...
0.59976584
0