query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Normalize and set the timestamp.
def set_timestamp(self, timestamp): self.timestamp = LogEntry.normalize_timestamp(timestamp)
[ "def set_to_timestamp_safe(self, value):\n try:\n if value is not None:\n self.to_timestamp = int(value)\n except:\n # do nothing, value will not have changed\n pass", "def setTimeStamp(self, ts):\r\n \tself.timeStamp = ts", "def set_from_timestam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the timestamp from dashdelimited string.
def set_timestamp_from_string(self, timestamp_str): try: ts = [int(n) for n in timestamp_str.split("-")] self.timestamp = datetime(*ts) except (TypeError, ValueError): return False return True
[ "def set_timestamp(self, timestamp):\n self.timestamp = LogEntry.normalize_timestamp(timestamp)", "def parse_timestamp(self, timestamp):\n dd = datetime.datetime.fromtimestamp(timestamp)\n self.set('year', dd.year)\n self.set('month', dd.month)\n self.set('day', dd.day)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set duration from tuple. hours the number of hours minutes the number of minutes seconds the number of seconds
def set_duration(self, hours, minutes, seconds): self.duration = (hours, minutes, seconds)
[ "def duration(self, duration):\n self._duration = duration", "def set_duration(self, duration):\n pass", "def duration_minutes(self, duration: int) -> None:\n self._duration = duration", "async def tempChannelsDuration(self, ctx: Context, hours: int, minutes: int):\n if (hours >= 100) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set duration from colondelimited string.
def set_duration_from_string(self, duration_str): try: duration = [int(n) for n in duration_str.split(":")] self.set_duration(*duration) except (TypeError, ValueError): return False return True
[ "def set_duration(self, duration):\n pass", "def set_duration(self, hours, minutes, seconds):\n self.duration = (hours, minutes, seconds)", "def duration(self, duration):\n self._duration = duration", "def set_duration(self, duration):\n self.__test_result[TestResult.__DURATION] = roun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve timestamp as dashdelimited string.
def timestamp_as_string(self): return ( f"{self.timestamp.year}-{self.timestamp.month}-" f"{self.timestamp.day}-{self.timestamp.hour}-" f"{self.timestamp.minute}-{self.timestamp.second}" )
[ "def _timestr():\n return '%s' % time.strftime(\"%Y-%m-%d %H:%M:%S\")", "def timestamp() -> str:\n return str(math.floor(time.time()))", "def get_time_display(self):\n return str(self.time)[11: 19]", "def discord_timestamp(timestamp: Timestamp, format: TimestampFormats = TimestampFormats.DATE_TIM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the time log from file.
def load(cls, force=False): # If we've already loaded, don't reload unless forced to. if not force and cls._log is not None: return # Retrieve the path from settings path = Settings.get_logpath() logging.debug(f"Loading time log from {path}") # Initialize ...
[ "def load_file(path):\n with path.open() as loaded_file:\n entry = frontmatter.load(loaded_file)\n\n log_file.process_datetimes(entry.metadata)\n\n return log_file.Entry(entry.metadata[log_file.MetaKeys.TIME], MIME_TYPE, entry.metadata, entry.content, path,\n entry.content)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the time log to file.
def save(cls): # Retrieve the save directory from settings logdir = Settings.get_logdir() # Create the save directory if necessary if not logdir.exists(): os.makedirs(logdir) # Retrieve the full save path from settings logpath = Settings.get_logpath() ...
[ "def log(self):\n \tdata = ser.readline()\n \tf = open(savefile, 'a')\n \tf.write(str(time.strftime(\"%Y%m%d-%H:%M:%S\"))+\",\"+str(data))\n \tf.close()", "def save_to_time_file(self, content, output_file, type=\"wb\", formator='YYYY-MM-DD-HH'):\n local_path = settings.LOCAL_DATAFILE_DIRS\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an entry in the log based on timestamp, loading from file if necessary.
def retrieve_from_log(cls, timestamp): try: return cls._log[timestamp] except KeyError: logging.warning("Cannot access entry at invalid timestamp.") return None
[ "def load_file(path):\n with path.open() as loaded_file:\n entry = frontmatter.load(loaded_file)\n\n log_file.process_datetimes(entry.metadata)\n\n return log_file.Entry(entry.metadata[log_file.MetaKeys.TIME], MIME_TYPE, entry.metadata, entry.content, path,\n entry.content)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an entry to the log. If an entry with the timestamp is already in the log, one or more seconds will be added to the timestamp to resolve the conflict before creating and storing the entry. timestamp the timestamp as a datetime object hours the number of elapsed hours minutes the number of elapsed minutes seconds th...
def add_to_log(cls, timestamp, hours, minutes, seconds, notes): timestamp = LogEntry.normalize_timestamp(timestamp) # If/While the timestamp is already in the log... while timestamp in cls._log: # Resolve collision by incrementing it by one second. timestamp = cls.increme...
[ "def add(self, timestamp: datetime, entry: LogLine):\n if len(self.entries) == 0:\n self.entries.appendleft((timestamp, entry))\n return self\n\n i = 0\n curr_entry_time, _ = self.entries[0]\n while timestamp < curr_entry_time:\n i += 1\n if i ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an entry from the log. timestamp the index of the item to remove
def remove_from_log(cls, timestamp): try: del cls._log[timestamp] except KeyError: logging.warning("Cannot delete entry at invalid timestamp.")
[ "def pop_record (self, timestamp):\n if self.editable:\n inttime = timestamp\n\n # Move from timetree to changed_timetree\n year = str(gmtime(inttime).tm_year)\n month = str(gmtime(inttime).tm_mon)\n mday = str(gmtime(inttime).tm_mday)\n self.changed_timetree [year] = {month : ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new place, given a name, location, latitude, longitude, and pin color.
def __init__(self, place_name="", loc="", lat=0, long=0, col="black"): self.name = place_name self.location = loc self.latitude = lat self.longitude = long self.color = col
[ "def place_pin(self):\n\n pin = turtle.Turtle()\n pin.penup()\n pin.color(self.color) # Set the pin to user's chosen color\n pin.shape(\"circle\") # Sets the pin to a circle shape\n\n # Logically, the denominator for longitude should be 360; lat should be 180.\n # These v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Projection of a vector x on the set of postive vectors whose coefficient sum to sum. This is a slight modification of Chen and Ye's algorithm (see their "projection onto a simplex" article)
def pseudo_simplex_projection(x, sum): n = x.size x_sorted = np.sort(x) i = n - 2 t_i = (np.sum(x_sorted[i + 1:n]) - sum) / (n - (i + 1)) while t_i < x_sorted[i] and i >= 0: i = i - 1 t_i = (np.sum(x_sorted[i + 1:n]) - sum) / (n - (i + 1)) if i < 0: t_hat = (np.sum(x)...
[ "def project_vector(self,x) :\n\n n_dofs = 4*self.param.n_cells\n projection = np.zeros(4*self.param.n_mom*self.param.n_cells)\n coarse_n_mom = x.shape[0]/(4*self.param.n_cells)\n if self.param.galerkin==True :\n skip = (-1+np.sqrt(1+2*self.param.n_mom))/2-1\n tmp_end = coarse_n_mom-(skip-1)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Projection of a coupling matrix P on the set of positive matrices whose rows' sum are given by hist
def coupling_matrix_projection(P, hist): projection = np.copy(P) for i in range(P.shape[0]): projection[i] = pseudo_simplex_projection(P[i], hist[i]) return projection
[ "def row_sum_constraints(prob, X, values):\n for i in range(len(values)):\n prob += pp.lpSum(X[i,:]) == values[i]", "def column_sum_constraints(prob, X, values):\n for i in range(len(values)):\n prob += pp.lpSum(X[:,i]) == values[i]", "def logprobtable(self,P,S=None):\n if S is None: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compose network service protobuf from URI. Parses the URI string into host, scheme, port, ip address, and ip address family. Then uses the above information to compose the network endpoint.
def build_uri_network_service(uri_string: str) -> NetworkService: uri = urlparse(uri_string) hostname = uri.hostname scheme = uri.scheme validate_scheme(scheme) port = sanitize_port(uri.port, scheme) address_info = socket.getaddrinfo(hostname, port)[0] ip_address = address_info[4][0] address_family = g...
[ "def parse_address(addr, strict=False):\n if not isinstance(addr, six.string_types):\n raise TypeError(\"expected str, got %r\" % addr.__class__.__name__)\n scheme, sep, loc = addr.rpartition(\"://\")\n if strict and not sep:\n msg = (\n \"Invalid url scheme. \"\n \"Must include prot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build the root url for web application service.
def build_web_application_root_url(network_service: NetworkService) -> str: if not is_web_service(network_service): raise ValueError("Invalid network service: %s" % network_service) return build_web_protocol( network_service) + build_web_uri_authority( network_service) + build_web_app_root_path(...
[ "def get_root_url(self):\n if self.http_proxy_state_manager is None:\n return None\n http_config = self.get_http_config()\n if http_config.root_url == \"\":\n if SERVE_ROOT_URL_ENV_KEY in os.environ:\n return os.environ[SERVE_ROOT_URL_ENV_KEY]\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates URI authority using the network service.
def build_web_uri_authority(network_service: NetworkService) -> str: uri_authority = network_endpoint_utils.to_uri_authority( network_service.network_endpoint) if is_plain_http_service(network_service) and uri_authority.endswith( ":80"): return uri_authority.replace(":80", "") if not is_plain_http...
[ "def _create_uri(self, path, operation, **kwargs):\n\n path_param = path\n\n #setup the parameter represent the WebHDFS operation\n operation_param = '?op={operation}'.format(operation=operation)\n\n #configure authorization based on provided credentials\n auth_param = str()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the point in position idx of not_visited list to the solution
def add(self, idx): self.g += graph[self.visited[-1], self.not_visited[idx]] self.visited.append(self.not_visited.pop(idx))
[ "def adding_nodes(self):\n \n for node in self.vertex:\n i = 0\n if node not in self.queue:\n self.queue.append(node)\n\n for neigbor in self.neighbors:\n if node == neigbor[0]:\n if neigbor[-1] not in self.queue:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generalized annotation of variants with a new column. get_val_fn takes a list of annotations in a region and returns the value for that region to update the database with. Separates selection and identification of values from update, to avoid concurrent database access errors from sqlite3, especially on NFS systems. Th...
def _annotate_variants(args, conn, get_val_fn, col_names=None, col_types=None, col_ops=None): # For each, use Tabix to detect overlaps with the user-defined # annotation file. Update the variant row with T/F if overlaps found. anno = pysam.Tabixfile(args.anno_file) naming = guess_contig_naming(anno) ...
[ "def _annotate_variants(args, conn, get_val_fn):\n # For each, use Tabix to detect overlaps with the user-defined\n # annotation file. Update the variant row with T/F if overlaps found.\n annos = pysam.Tabixfile(args.anno_file)\n naming = guess_contig_naming(annos)\n select_cursor = conn.cursor()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Annotate gemini database with extra columns from processed chunks, if available.
def add_extras(gemini_db, chunk_dbs): extra_files = [] header_files = [] for chunk in chunk_dbs: extra_file, header_file = get_extra_files(chunk) if os.path.exists(extra_file): extra_files.append(extra_file) assert os.path.exists(header_file) header_files....
[ "def annotate_all(self):\n logger.info(\"Annotating data\")\n self.genomic_df = self.genomic_df.merge(\n self.annotation_df, how=\"left\", on=[\"IDENTIFIER\"]\n )\n self.genomic_df = self._string_split(self.genomic_df, \"GENE\", \",\")\n self.annotate = True", "def ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge BED files into a final sorted output file.
def _merge_beds(in_beds, final_db): if len(in_beds) == 1: out_file = in_beds[0] else: out_file = "%s.bed" % os.path.splitext(final_db)[0] cmd = "cat %s | sort -k1,1 -k2,2n > %s" % (" ".join(in_beds), out_file) subprocess.check_call(cmd, shell=True) subprocess.check_call(["bgz...
[ "def merge_bam_files(input_files,output,path_to_samtools=\"\"):\n f=open(\"header.sam\",'w')\n subprocess.check_call(shlex.split(path_to_samtools+\"samtools view -H \"+input_files[0]),stdout=f)\n for filen in input_files:\n f.write(\"@RG\\tID:\" + filen[:filen.rindex(\".bam\")] + \"\\tLB:\" + filen[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert JSON output into a BED file in preparation for annotation.
def _json_to_bed(fname, header): out_file = "%s.bed" % os.path.splitext(fname)[0] with open(fname) as in_handle: with open(out_file, "w") as out_handle: for line in in_handle: cur_info = json.loads(line) parts = [str(cur_info.get(h, "")) for h in ["chrom", "st...
[ "def _preprocess_BDD100K_json(self):\n if not os.path.exists(self.result_out_path):\n os.makedirs(self.result_out_path)\n filename = self.label_path\n if filename[-5:] == \".json\" and 'val' in filename and os.path.exists(filename): # assign file is val\n with open(file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge a set of header files into a single final header for annotating.
def _merge_headers(header_files): ignore = set(["chrom", "start", "end"]) ctype_order = ["text", "float", "integer", None] out = {} for h in header_files: with open(h) as in_handle: header = json.loads(in_handle.read()) for column, ctype in header.items(): ...
[ "def file_merge(infiles, outfile=None, header=1, verbose=1):\n outfile = outfile or \"_merged\".join(os.path.splitext(infiles[0]))\n out_f, outfile = safewfile(outfile)\n if verbose:\n print(\"Merging...\")\n cnt = 0\n for i, fn in enumerate(infiles):\n print(os.path.split(fn)[1], \"......
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve extra file names associated with a gemini database, for flexible loading.
def get_extra_files(gemini_db): extra_file = "%s-extra.json" % os.path.splitext(gemini_db)[0] extraheader_file = "%s-extraheader.json" % os.path.splitext(gemini_db)[0] return extra_file, extraheader_file
[ "def add_extras(gemini_db, chunk_dbs):\n extra_files = []\n header_files = []\n for chunk in chunk_dbs:\n extra_file, header_file = get_extra_files(chunk)\n if os.path.exists(extra_file):\n extra_files.append(extra_file)\n assert os.path.exists(header_file)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to make the request to the specified endpoint.
def _make_request(self, endpoint: str, params: dict): response = get( endpoint, params=params, headers=self.HEADERS, proxies=self.PROXIES ) return self._validate_response(response)
[ "def api_call(self, endpoint: str, kwargs: dict) -> Response:\n url = self.__url_builder(endpoint, **kwargs)\n res = get(url)\n return res", "def make_request(endpoint, params=None):\n\n headers = {\"content-type\": \"application/json\"}\n try:\n response = requests.get(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the volume_id of this Brick2.
def volume_id(self, volume_id): self._volume_id = volume_id
[ "def set_volume_level(self, volume):\n self.soco.volume = str(int(volume * 100))", "def set_volume(self, zone: int, volume: int):\n raise NotImplemented()", "def set_volume(self, speaker: Speaker, volume: int):\n raise NotImplementedError()", "def change_volume(self, volume):\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the volume_name of this Brick2.
def volume_name(self, volume_name): self._volume_name = volume_name
[ "def set_volume_level(self, volume):\n self.soco.volume = str(int(volume * 100))", "def volume_rename(self, volume, new_volume_name):\n return self.request( \"volume-rename\", {\n 'volume': [ volume, 'volume', [ basestring, 'None' ], False ],\n 'new_volume_name': [ new_volume_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the peer_id of this Brick2.
def peer_id(self, peer_id): self._peer_id = peer_id
[ "def set_id_receiver(self, id_receiver):\n self.id_receiver = id_receiver", "def set_participant_id(self, pid):\n self.participant_id = pid", "def partner_id(self, partner_id: UserId):\n\n self._partner_id = partner_id", "def match_relationship_peer_id(self, peer_id=None, match=None):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a service by its name/index or a list of services via a slice
def get_service(self, key, access=gdef.MAXIMUM_ALLOWED): if isinstance(key, int_types): return self.enumerate_services()[key] if isinstance(key, slice): # Get service list servlist = self.enumerate_services() # Extract indexes matching the slice ...
[ "def fetch_by_name(self, name):\n service = self.name_index.get(name)\n if not service:\n raise ServiceNotFound\n return Service(service)", "def get_service(self):\n\n print \"\\nLooking up services for pod\\n\"\n\n api_url = \"/api/v1/services\"\n if (str(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The generator code behind __iter__. Allow to iter over the services on the system
def _enumerate_services_generator(self): size_needed = gdef.DWORD() nb_services = gdef.DWORD() counter = gdef.DWORD() try: windows.winproxy.EnumServicesStatusExW(self.handle, SC_ENUM_PROCESS_INFO, SERVICE_TYPE_ALL, SERVICE_STATE_ALL, None, 0, ctypes.byref(size_needed), ctyp...
[ "def services(self):\n for service_id in self.service_ids():\n yield self._get_service_from_graph(service_id)", "def __iter__(self):\n return self.iter_hosts()", "def iter_procs(self):\n for row in self:\n if row.service_def:\n yield row", "def __iter_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The description of the service
def description(self): return ServiceManager().get_service_display_name(self.name)
[ "def _description_string(self) -> str:", "def service_def(self):\n return self.get(\"service_def\", decode=True)", "def desc(self):\n doc = inspect.getdoc(self.endpoint_class)\n if not doc: doc = u''\n return doc", "def get_description(cls):\n if cls.__doc__ is None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The security descriptor of the service
def security_descriptor(self): return security.SecurityDescriptor.from_service(self.name)
[ "def getSecurity(self):\n return self._security", "def security_definitions(self):\n return None", "def security_credential(self):\n return self._security_credential", "def advapi32_GetSecurityInfo(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"handle\", \"ObjectType\", \"Securi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure parent/child equality of is_archived is maintained.
def test_inheritance(self): self.assertEqual(Document.objects.filter(is_archived=True).count(), 0) # Set up a child and a parent and an orphan (all false) and something # true. TranslatedRevisionFactory() TranslatedRevisionFactory() DocumentFactory() DocumentFacto...
[ "def test_miscounting_archived(self):\n locale = \"nl\"\n parent1 = DocumentFactory(category=CANNED_RESPONSES_CATEGORY, is_archived=False)\n translation1 = DocumentFactory(parent=parent1, locale=locale)\n parent2 = DocumentFactory(category=CANNED_RESPONSES_CATEGORY, is_archived=True)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Put all available languages into the DB
def _load_languages(): choices = [(k, v) for k, v in sorted(LANGUAGES.items()) if v in AVAILABLE_MODELS] print(f"Loading languages: {', '.join([i[0] for i in choices])}...") for longname, short in choices: try: Language(name=longname, short=short).save() except IntegrityError: ...
[ "def update_languages(self) -> None:\n logger.info(\"Updating language list\")\n\n for lang in import_json(LANGUAGE_JSON_PATH):\n language_obj = Language.objects.filter(name=lang[\"name\"]).first()\n if language_obj is not None:\n logger.info(\"Updating language: %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load contents of corpora.json into DB as Corpus objects
def _load_corpora(corpora_file): with open(corpora_file) as fo: data = json.load(fo) for name, meta in data.items(): modelled = Corpus.from_json(meta, name) modelled.save()
[ "def parse_corpus(self, **kwargs) -> None:\n self._load_resource(\"nlp_base\")\n logger.info(\"Parsing external corpus\")\n (\n self._entities,\n self._failed_entity_lookups,\n self._annotations,\n ) = self._parse_corpus(**kwargs)\n\n # Serialize e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run freesasa on a PDB file, output using the NACCESS RSA format.
def run_freesasa(infile, outfile, include_hetatms=True, outdir=None, force_rerun=False): if not outdir: outdir = '' outfile = op.join(outdir, outfile) if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile): if op.exists(outfile): os.remove(outfile) if include_het...
[ "def read_dbSNP(args, db):\n db[\"dbsnp\"] = {}\n dbsnpfiles = [\"/\" + db[\"freq_main\"]]\n for dbsnpfile in dbsnpfiles:\n with open(dbsnpfile, \"r\") as fin:\n for line in fin:\n allele = {}\n line_l = line.strip().split()\n chrom, pos, rs, c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process a NACCESS or freesasa RSA output file. Adapted from Biopython NACCESS modele.
def parse_rsa_data(rsa_outfile, ignore_hets=True): naccess_rel_dict = OrderedDict() with open(rsa_outfile, 'r') as f: for line in f: if line.startswith('RES'): res_name = line[4:7] chain_id = line[8] resseq = int(line[9:13]) i...
[ "def get_nucl2prot_accession():\n reg_exp = regex.compile(r\"gpprotdata.jsp\\?seqAccno=([0-9A-Z]+).+?\"\n \"gbnucdata.jsp\\?seqAccno=([0-9A-Z]+)\", \n regex.DOTALL|regex.MULTILINE|regex.VERBOSE)\n accession = reg_exp.findall(driver.page_source)\n acce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
QWidget for file paths. Includes "browse" button and list of recent file paths.
def __init__( self, parent=None, settings_name="_DefaultQtPathWidgetSettings", start_dir="", file_filter="", use_directory_dialog=False, relative_to_path="", recent_paths_amount=30, only_show_existing_recent_path...
[ "def __showRecentFilesMenu(self):\n self.recentFiles = []\n self.rsettings.sync()\n self.__loadRecentFiles()\n \n self.recentFilesMenu.clear()\n \n idx = 1\n for rf in self.recentFiles:\n if idx < 10:\n formatStr = '&{0:d}. {1}'\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set path display in ComboBox and store in settings
def set_path(self, path, emit_change_signal=True): self._settings.add_recent_path(path) # store full path in settings, then convert to relative if desired # convert to relative path path_drive = os.path.splitdrive(path)[0] if self.relative_to_path and path_drive == self.relative_to_pat...
[ "def _browseModulePath(self):\n\t\tselectedDir = str(QtGui.QFileDialog.getExistingDirectory(self,\"Browse\"))\n\t\tif selectedDir:\n\t\t\twritObj = utils.ReadWriteCustomPathsToDisk()\n\t\t\tif not writObj._entryExist(selectedDir):\n\t\t\t\twritObj.updateXml()\n\t\t\tself.addPathEdit.setText(selectedDir)\n\t\t\tself...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get recent paths from settings
def get_recent_paths(self, full_paths=False, only_existing=False): paths = self.value(self.key_recent_paths) if not isinstance(paths, list): if paths: # QSettings ini sometimes has trouble reading data types paths = str(paths).split(", ") else: ...
[ "def get_paths_triggering_build(config_settings=None):", "def get_settings_path() -> Path:\n with open(root_path / 'deeppavlov/paths.json', encoding='utf8') as f:\n paths = json.load(f)\n settings_paths = Path(paths['settings_path']).resolve() if paths['settings_path'][0] == '/' \\\n else root...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
open implements a generic API for opening connections to a LMDB database where it's local or remote (conn, type), where conn is the connection helper to interact with db type is 1 for the local LMDB, 2 for the remote LMDB
def open(uri): if uri is None: raise ValueError("lmdb data store uri missing") # employ the remote version if remote_url is set logger.info(f"connect to remote LMDB @{uri}") return LMDBHelperProxy(uri)
[ "def open_connect(self):\n\n try:\n self.conn = sqlite3.connect(self.database_name)\n self.cursor = self.conn.cursor()\n except sqlite3.Error:\n print(\"Error connecting to database!\")", "def _open(self, dbServer=None, dbHost=None, dbName=None, dbUser=None, dbPw=Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a model and an HTTP method, return the list of permission codes that the user is required to have.
def get_required_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } return [perm % kwargs for perm in self.perms_map[method]]
[ "def get_required_object_permissions(self, method, model_cls):\n\n kwargs = {\n \"app_label\": model_cls._meta.app_label,\n \"model_name\": model_cls._meta.model_name,\n }\n\n if method not in self.perms_map:\n raise exceptions.MethodNotAllowed(method)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call this before rendering to bind the Python matrix to the GLSL uniform mat4. You will need different methods for different types of uniform, but for now this will do for the PVM matrix
def bind_matrix(self, M=None, number=1, transpose=True): if M is not None: self.value = M if self.value.shape[0] == 4 and self.value.shape[1] == 4: glUniformMatrix4fv(self.location, number, transpose, self.value) elif self.value.shape[0] == 3 and self.value.shape[1] == 3:...
[ "def setUniformBindings(self, wireframe=False):\n normalMatrix = self._transform.normalMatrix()\n self._active_shader.setUniformValue(\"modelMatrix\", self._transform)\n self._active_shader.setUniformValue(\"viewMatrix\", self._scene.camera.viewMatrix)\n self._active_shader.setUniformVal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call this function to compile the GLSL codes for both shaders.
def compile(self, attributes): print('Compiling GLSL shaders....') try: self.program = glCreateProgram() glAttachShader(self.program, shaders.compileShader(self.vertex_shader_source, shaders.GL_VERTEX_SHADER)) glAttachShader(self.program, shaders.compileShader(self.fr...
[ "def compile(self, shader_type):\n shader = gl.glext_arb.glCreateShaderObjectARB(shader_type)\n gl.glext_arb.glShaderSourceARB(shader, 1)\n gl.glext_arb.glCompileShaderARB(shader)\n gl.glext_arb.glAttachObjectARB(self.program, shader)\n gl.glext_arb.glDeleteObjectARB(shader)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export given rows to csv file
def csv_export(filename, rows): if not filename or not rows: return with open(filename, 'wb') as f: f_writer = csv.writer(f) f_writer.writerows(rows)
[ "def save_csv(path, rows):\n with open(path, \"w\", newline=\"\", encoding=\"utf-8\") as file:\n writer = csv.writer(file)\n for row in rows:\n if \",\" in row:\n row = row.split(\",\")\n try:\n writer.writerow(row)\n except IndexError:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load all image inside the given image_dir as grayscale and store them in self._images in sorted order.
def _loadImages(self, imageDir, cvLoadFlags=cv2.IMREAD_GRAYSCALE): if isinstance(imageDir, str): if imageDir.startswith("~") and 'linux' in sys.platform.lower(): imageDir = os.path.expanduser(imageDir) if os.path.exists(imageDir): self.logger.debug('Loadin...
[ "def load_images(image_folder_path):\n\n image_list = []\n for img in os.listdir(image_folder_path):\n image = plt.imread(image_folder_path + img)\n image = image.astype(np.float32)\n image = image / 255.\n image_list.append(image)\n\n return image_list", "def collect_imgs(dir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes the path to annotations and to the root dir of the arrays, if transforms are passed as an argument they will be applied.
def __init__(self, annotations, root_dir, transforms = None): self._path_to_annotations = Path(".") / annotations self.annotations = pd.read_csv(self._path_to_annotations) self.root_dir = Path(root_dir) self.transform = transforms
[ "def parse_annotations(anno_dir):\n global annotations, frame_names\n anno_dir = anno_dir.replace(\"'\", \"\")\n # For each annotation the sistem has we are going to parse it\n for f in listdir(anno_dir):\n file_path = anno_dir + '/' + f\n # frame_names.append(f.replace(\".json\", \"\"))\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new order for the given inmate
def order_create(request, inmate_pk): try: # look at the request to find the current inmate inmate = Inmate.objects.get(pk=inmate_pk) # create a new order object for this inmate order = Order() order.inmate = inmate order.status = 'OPEN' order.save() # save this order in the session ...
[ "def create_order(self, order):\n return self.post(cc_urls['order'], {'order': json.dumps(order)})", "def make_order(order_json, seating_id):\n order_contents = [Menu.objects.get(pk=key) for key in order_json]\n total_price = sum([item.price * order_json[str(item.id)] for item in order_conten...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same as order_add_book_asin except it does additional ISBN format checking
def order_add_book_isbn(request): if isbn.isValid(isbn.isbn_strip(request.POST['ISBN'])): # try: book = Book.get_book(isbn.isbn_strip(request.POST['ISBN'])) if not book: raise Http404('No book with that ISBN found') order_add_book(request, book) return order_render_as_response(request) els...
[ "def amazon_by_isbn(isbn):\n ecs.setLicenseKey(license_key)\n ecs.setSecretKey(secret_key)\n ecs.setLocale('us')\n try:\n books = ecs.ItemLookup(isbn, IdType='ISBN', SearchIndex='Books',\n ResponseGroup='Medium')\n return format_output(books)\n except ecs.InvalidParameterValue:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the book to the current session order Saves the book to do so
def order_add_book(request, book): try: # now add this book to the current order and save it book.order = request.session['order'] book.save() except KeyError: # there is no current order print("Tried to add a book to current order, but there isn't a current order") raise KeyError
[ "def add_book(self, book: Book):\n self.books.append(book)", "def buy_book(self, book):\r\n self._balance += books[book]\r\n self._library += Book(book)", "def add_book_to_db(book: dict) -> None:\n if \"title\" in book:\n title = request.form['title']\n else:\n title = \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the given book from the current order and delete it
def order_remove_book(request, book_pk): try: book = get_object_or_404(Book, pk=book_pk) if book.order == request.session['order']: book.delete() else: raise Exception("Tried to remove a book from the current order that wasn't in the current order") except KeyError: logging.info("Tried t...
[ "def remove_book(self, book: Book):\n self.books.remove(book)", "def remove_book(self):\n \n try:\n self.clr_scr()\n serial_no=input(\"Enter serial number of book:\\t\\t\") #enter serial_no of book you want to delete.\n Library.library.pop(serial_no,\"No suc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add book to the current order with a custom title & author. Used for the AJAX book adds of books with custom titles and/or authors.
def order_add_book_custom(request): # If this is a non-unique book, fill in what attributes we can and continue if request.POST.get('Title', False): book = Book() book.title = request.POST.get('Title', '') book.author = request.POST.get('Author', '') order_add_book(request, book) else: # The t...
[ "def add_book_author(self, book):\r\n self.validate_data_class_Book(book)\r\n self.author_books.append(book)", "def add_book(self, book: Book):\n self.books.append(book)", "def order_add_book(request, book):\n try:\n # now add this book to the current order and save it\n book.order =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wraps the current order snippet in an HTTP Response for return by view functions (the AJAX ones; its a reponse for the clientside AJAX call)
def order_render_as_response(request): return HttpResponse(json.dumps( {'summary': order_get_summary_html(request), 'snippet': order_get_snippet_html(request), 'warnings': order_get_warnings_html(request), }))
[ "def order():\n return render_template('order.html', purchases={})", "def ordersent(request):\n return render(request, \"ordersent.html\")", "def render_issue_response(self, request, context):\n return render(request, self.response_template, context)", "def json_response(func):\n\n @functools.wr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the current order summary as a snippet of HTML
def order_get_summary_html(request): return render_to_string('LemurApp/order_summary.html', context_instance=RequestContext(request))
[ "def get_merit_summary():\n title = 'Summary'\n return render_template('summary.html', page_title=title)", "def formatted(self):\n print(f\"{self.order_number}\")\n print(f\"{self.order_description}\")", "def show_summary(self):\n length = self.sum_length.first()\n coef = self.sum_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the current order's warnings in a list as a snippet of HMTL
def order_get_warnings_html(request): return render_to_string('LemurApp/order_warnings.html', context_instance=RequestContext(request))
[ "def render_warning():\n screen = pygame.display.get_surface()\n\n # Split the warning into separate lines\n lines = word_wrap(current_warning, width_warning, font_warning)\n\n # Render each line using a dark gray color\n lines = [font_warning.render(l, True, (50, 50, 50)) for l in lines]\n\n # Th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initial view for the order build page. Initializes all the forms for that page. This view also handles forms that submited back to the page, which is only the true search form for now because the title form and the ISBN form are both handled by clientside AJAX functions that make requests to other views (order_add_book...
def order_build(request): context_dict = { 'errors': [], 'formISBN': forms.BookForm(auto_id='isbn_id_%s'), 'formTitle': forms.BookForm(auto_id='title_id_%s'), 'formSearch': forms.BookForm(auto_id='search_id_%s') } # If it's a real search, do a Google search and display the results if request.G...
[ "def search_form(request):\r\n if request.method == 'GET':\r\n # A GET request was sent to the search page, load the value and\r\n # validate it.\r\n search_form = SearchForm(request.GET)\r\n if search_form.is_valid():\r\n # If the input is good, send them to the results pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display a page allowing the user to mark an order as sent out. Mark the current order as sent if the form is submitted.
def order_send_out(request): # if request.method == 'POST': # If the form has been submitted... # form = forms.SendOutForm(request.POST) # A form bound to the POST data # if form.is_valid(): # All validation rules pass # currentOrder = request.session['order'] # currentOrder.sender = form.clean...
[ "def ordersent(request):\n return render(request, \"ordersent.html\")", "def checkout_success(request, order_number):\n order = get_object_or_404(Order, order_number=order_number)\n messages.success(request, f'Order complete, {order.tokens} tokens \\\n have been added to your account')\n\n mess...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unset the current order in session and redirect to the list of open orders where another can be selected.
def order_unset(request): request.session['order'] = None return redirect(reverse('order-oldlist'))
[ "def order_send_out(request):\n # if request.method == 'POST': # If the form has been submitted...\n # form = forms.SendOutForm(request.POST) # A form bound to the POST data\n # if form.is_valid(): # All validation rules pass\n # currentOrder = request.session['order']\n # currentOrder.sender = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select the given order and set it as the current order in session, then redirect to the order_build page.
def order_set(request, order_pk): request.session['order'] = get_object_or_404(Order, pk=order_pk) return redirect(reverse('order-build'))
[ "def place_order(self, order):\n return self.make_request('/orders', order, method='POST')", "def order_unset(request):\n request.session['order'] = None\n return redirect(reverse('order-oldlist'))", "def save(self):\n order = self.context['order']\n order.issue_order()", "def save(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the status of the given order to open and sets this order to current.
def order_reopen(request, order_pk): order = get_object_or_404(Order, pk=order_pk) order.status = 'OPEN' order.date_closed = None order.save() return order_set(request, order_pk)
[ "def openOrder(self, orderId, contract, order, orderstate):\n self.log.info(__name__ + \": \" + str(orderId) + ', ' + str(contract.symbol) + \n '.' + str(contract.currency) + ', ' + str(order.action) + ', ' + \n str(order.totalQuantity))\n if orderId in self.context.portfolio.openOrderBo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expand a list of blueprint configurations with a list of variants. Helps documenting the available hosts better
def expandBlueprints(data): from lib import blueprints for blueprint in data['blueprints']: errors = validate_dict(['configName', 'variants'], blueprint) if len(errors) > 0: for key, error in errors.iteritems(): log.error('can not expand blueprints, %s: %s!' % (error, key)) exit(1) t...
[ "def complete_hosts(cfg):\n dflt = cfg.get('defaults', {}) # default inst params\n dflt_probes = dflt.get('probes', [])\n # dflt_schedule = dflt.get('schedule', None)\n # dflt_notifiers = dflt.get('notifiers', [])\n probes = dict(cfg['probes'])\n hosts = cfg['hosts']\n # schedules = cfg['sched...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a string representation of the nature, and return it. This is achieved by putting the name, along with the name of the boosted stat with a +, and the reduced stat with a .
def text(self): txt = self.name # Only add the details of the boosted and reduced stats if this is not a reducing nature. if self.value != [1] * 6: boosted_index = self.value.index(1.1) reduced_index = self.value.index(0.9) txt += " (+" + stats_names...
[ "def get_stat_description(name: str) -> str:\n if not isinstance(name, str):\n raise TypeError(\"Statistic's name should be a string.\")\n\n if name in profiles:\n return profiles[name]\n\n if name in \"mean_trend10_zscore\":\n return \"Significance of (rolling) trend in means of featu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the IV ranges of a Pokemon, and return them. Note that this does not take into account any other ranges calculated; it just gives the minimum and maximum possible IVs for each stat given the stats at this level.
def calc_iv_range(level, base_stats, stats, evs, nature): ivs = [[0, 31]] * 6 nature_list = nature.value # Loop over every IV range. for index, iv_range in enumerate(ivs): min, max, min_found, max_found = 0, 31, False, False # Loop over every possible ID in this stat. ...
[ "def calculate_spe_range(pokemon_name):\n speed_base_stat = POKEMON_DATA[pokemon_name][\"baseStats\"][\"spe\"]\n\n # Slowest possible opponent's pokemon\n min_speed = calculate_stat(speed_base_stat, 0, 100)*0.9\n\n # Fastest possible opponent's pokemon\n max_speed = calculate_stat(speed_base_stat, 25...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a representation of a range as the minimum and maximum separated by a dash.
def display_range(range): return str(range[0]) + "-" + str(range[1])
[ "def _form_range_string(minimum, maximum):\n return f'{minimum}-{maximum}' if minimum < maximum else maximum", "def __repr__(self):\n\n repr_ = ','.join([f\"'{val.start}-{val.stop - 1}'\" if val.stop - val.start > 1 else f\"'{val.start}'\"\n for val in self.ranges])\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the immediate aurora forecast.
def parse_nowcast(text): time = datetime.max # forecast time remains far in the future if time not found in the file data = [] for line in map(lambda l: l.decode('utf_8').strip(), text): if line: if not line.startswith('#'): for p in line.split(): da...
[ "def forecast(response):\n\n soup = BeautifulSoup(response, \"lxml\")\n hourly = ForecastHourlyExtractor.extract(soup)\n twoday = ForecastTwodayExtractor.extract(soup)\n tenday = ForecastTendayExtractor.extract(soup)\n return (hourly, twoday, tenday)", "def forecasts() -> []:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the threeday global Kp index forecast.
def parse_three_day_forecast(text): lines = itertools.imap(lambda l: l.strip(), text) def fetch_line(iter, matcher): cont = itertools.dropwhile(lambda l: not matcher(l), iter) return cont, cont.next() def parse_date(str, format): return datetime.strptime(str, format) def pars...
[ "def kalman_filter(y, model, everything=False):\n TT, RR, C, ZZ, D, QQ, EE = [v.value for v in model.System.values()]\n\n if model.model_type == 'HANK':\n # Adjust TT to account for continuous time discretization\n TT = np.eye(TT.shape[0]) + TT * 1/model.settings['state_simulation_freq'].value\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reassign `event` to `ax`.
def _reassigned_axes_event(event, ax): event = copy.copy(event) event.xdata, event.ydata = ( ax.transData.inverted().transform_point((event.x, event.y))) return event
[ "def reposition(self, event):\n self.__events.remove(event)\n self.add(event)", "def set_event(self, event):\n self._event = event\n if len(self._buffer) > 0:\n event.set()\n else:\n event.clear()", "def change_axis(self, index):\n self.x_idx = index\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The tuple of selectable artists.
def artists(self): return tuple(filter(None, (ref() for ref in self._artists)))
[ "def artists(self, artists):\n\n tlist = [self._get_id(\"artist\", a) for a in artists]\n return self._get(\"artists/?ids=\" + \",\".join(tlist))", "def selections(self):\n return tuple(self._selections)", "def get_artist_list(data_set):\n\n\treturn [dictio['artist'] for dictio in data_set]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The tuple of current `Selection`\\s.
def selections(self): return tuple(self._selections)
[ "def selected(self):\n selected = self._selected\n if self.multisel:\n return tuple(self._pos[index] for index in selected)\n\n return self._pos[selected]", "def _get_selections(self):\n item_ids = self.Tree.GetSelections() if self.multi_select else [self.Tree.GetSelection()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an annotation for a `Selection` and register it. Returns a new `Selection`, that has been registered by the `Cursor`,
def add_selection(self, pi): # pi: "pick_info", i.e. an incomplete selection. ann = pi.artist.axes.annotate( _pick_info.get_ann_text(*pi), xy=pi.target, **default_annotation_kwargs) ann.draggable(use_blit=True) extras = [] if self._highlight: ...
[ "def get_selector(selection):\n width = max(30, (term.width/2) - 10)\n xloc = min(0, (term.width/2)-width)\n selector = Selector (yloc=term.height-1, xloc=xloc, width=width,\n left='utf8', right='cp437')\n selector.selection = selection\n return selector", "def co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create, add and return a highlighting artist. It is up to the caller to register the artist with the proper `Selection` in order to ensure cleanup upon deselection.
def add_highlight(self, artist): hl = copy.copy(artist) hl.set(**default_highlight_kwargs) artist.axes.add_artist(hl) return hl
[ "def add_selection(self, pi):\n # pi: \"pick_info\", i.e. an incomplete selection.\n ann = pi.artist.axes.annotate(\n _pick_info.get_ann_text(*pi),\n xy=pi.target,\n **default_annotation_kwargs)\n ann.draggable(use_blit=True)\n extras = []\n if sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect a callback to a `Cursor` event; return the callback id. Two classes of event can be emitted, both with a `Selection` as single
def connect(self, event, func=None): if event not in ["add", "remove"]: raise ValueError("Invalid cursor event: {}".format(event)) if func is None: return partial(self.connect, event) return self._callbacks.connect(event, func)
[ "def bind_for_id(self, event, callback):\n if event not in TK_MOUSE_EVENTS:\n return\n\n self.bind(event, lambda e: callback(self.xy_to_grid((e.x, e.y)), e))", "def addSelectionCallback(self, *args):\n return _coin.SoSelection_addSelectionCallback(self, *args)", "def addSelection...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all `Selection`\\s and disconnect all callbacks.
def remove(self): for disconnect_cid in self._disconnect_cids: disconnect_cid() while self._selections: self._remove_selection(self._selections[-1])
[ "def _clear_selection():\r\n\r\n for ob in bpy.data.objects:\r\n ob.select = False", "def removeSelectionCallback(self, *args) -> \"void\":\n return _coin.SoSelection_removeSelectionCallback(self, *args)", "def clear_selection(self):\n for node in self._selected:\n node.desele...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Relative path to folder.
def relative_folder_path(self): return copy.deepcopy(self.__PROJECT.RELATIVE_PATH_TO_OUTPUT_FOLDER)
[ "def short_relative_path_to_here(self):\n return self.short_relative_path_to(os.getcwd())", "def relative_path(self):\n if self.parent is not None:\n root = self.parent\n while True:\n if root.parent:\n root = root.parent\n else:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add lambda permission for all api gateway resources (or routes if apigv2) to access the lambda function
def add_lambda_permissions(session, lambda_function, lambda_alias, lambda_region, resource_arns): lambda_client = session.client("lambda", lambda_region) params = { "FunctionName": lambda_function, "Action": "lambda:InvokeFunction", "Principal": "apigateway.amazonaws.com", } ...
[ "def _add_function_permission(appName, _lambda, config):\n\n funcName = appName+'-uxy-app-'+config['app:stage']\n resp = _lambda.add_permission(\n FunctionName = funcName,\n StatementId = '1',\n Principal = 'apigateway.amazonaws.com',\n Action = 'lambda:InvokeFunction'\n )\n return r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of (resourcepatharns, statementid)
def get_apig_resource_arns(session, apig_id, apig_region, apig_account_id): resp = session.client("apigateway", apig_region).get_resources(restApiId=apig_id, limit=50) if check_response(resp) is False: raise Exception("Failed to retrieve api gateway resource paths. Aborted") apig_base_url = f"arn:a...
[ "def _get_children_resource_ids(self):\n resource_ids = []\n pnode = self._pnode\n\n # get resource_ids of immediate sub-platforms:\n for subplatform_id in pnode.subplatforms:\n sub_pnode = pnode.subplatforms[subplatform_id]\n sub_agent_config = sub_pnode.CFG\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare layout information dictionary with sbml model. Input Dictionary with layout information, sbml model. Output Dictionary with cofactors; keys are reaction nodes and values are a dictionaries with the species that are substrates/products of that reaction according to the model, but are not listed in the input dict...
def get_cofactors_from_sbml(d, sbml_file): # change labels of some cofactors (for yeast consensus model) alt_lab = {'carbon dioxide [cytoplasm]': 'CO2', 'phosphate [cytoplasm]': 'Pi', 'diphosphate [cytoplasm]': 'PPi', 'ammonium [cytoplasm]': 'NH4+'} model = cbm.CBRead.readSBML3FBC(sbml_file) # get reagen...
[ "def create_dicts(self):\n print(\"There are \" + str(self.matrix.shape[1]) + \" features and \")\n print(str(self.matrix.shape[0]) + \" instances to consider\")\n possible_labels = list(set(self.labels))\n matricies = {}\n ig_dict = {}\n indexes_dict = {}\n sums = {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the `InteractiveBrokersAuthentication` client.
def __init__(self, ib_client: object, ib_session: InteractiveBrokersSession) -> None: from ibc.client import InteractiveBrokersClient self.client: InteractiveBrokersClient = ib_client self.session: InteractiveBrokersSession = ib_session self.authenticated = False self.server_pr...
[ "def _init_client(self):\n pass", "def initialize(self):\n self.logger.info(\"Initializing connection to the MQTT broker.\")\n self.client = AWSIoTMQTTClient(self.client_id)\n self.client.configureEndpoint(self.endpoint, portNumber=8883)\n self.client.configureCredentials(CAFile...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When using the CP Gateway, this endpoint provides a way to reauthenticate to the Brokerage system as long as there is a valid SSO session, see /sso/validate. Returns
def reauthenticate(self) -> dict: # Make the request. content = self.session.make_request( method='post', endpoint='/api/iserver/reauthenticate' ) return content
[ "def authenticate(self) -> None:\n response = requests.post(\n 'https://sso.wis.ntu.edu.sg/webexe88/owa/sso.asp',\n headers=self.get_headers(),\n data={\n 'Domain': 'STUDENT',\n 'PIN': self.password,\n 'UserName': self.username,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the file name in file_name_format.html for the given TLObject. Only its name may also be given if the full TLObject is not available
def get_file_name(tlobject, add_extension=False): if isinstance(tlobject, TLObject): name = tlobject.name else: name = tlobject # Courtesy of http://stackoverflow.com/a/1176023/4759433 s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) result = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1)...
[ "def get_file_name(tlobject, add_extension=False):\n\n # Courtesy of http://stackoverflow.com/a/1176023/4759433\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', tlobject.name)\n result = re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n if add_extension:\n return result + '.p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the file path (and creates the parent directories) for the given 'tlobject', relative to nothing; only its local path
def get_create_path_for(tlobject): # Determine the output directory out_dir = 'methods' if tlobject.is_function else 'constructors' if tlobject.namespace: out_dir = os.path.join(out_dir, tlobject.namespace) # Ensure that it exists os.makedirs(out_dir, exist_ok=True) # Return the resu...
[ "def _get_path_for(tlobject):\n out_dir = pathlib.Path('methods' if tlobject.is_function else 'constructors')\n if tlobject.namespace:\n out_dir /= tlobject.namespace\n\n return out_dir / _get_file_name(tlobject)", "def relative_path(self):\n if self.parent is not None:\n root = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns "true" if the type is considered a core type
def is_core_type(type_): return type_.lower() in { 'int', 'long', 'int128', 'int256', 'double', 'vector', 'string', 'bool', 'true', 'bytes', 'date' }
[ "def has_core_type(self, value):\n return isinstance(value, self.core_types)", "def is_component_type(self):\n return True", "def isOfType(self, type: 'SoType') -> \"SbBool\":\n return _coin.SoField_isOfType(self, type)", "def isOfType(self, type: 'SoType') -> \"SbBool\":\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the dictionary of 'original' paths to relative paths starting from the given 'relative_to' file
def get_relative_paths(original, relative_to): return {k: get_relative_path(v, relative_to) for k, v in original.items()}
[ "def _relative(from_file: Path, to_file: Path) -> str:\n return os.path.relpath(str(to_file), str(from_file.parent))", "def _relativePath(fromdir, tofile):\n if not tofile:\n return tofile\n f1name = os.path.abspath(tofile)\n if os.path.splitdrive(f1name)[0]:\n hasdrive = True\n else:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds the menu using the given DocumentWriter up to 'filename', which must be a file (it cannot be a directory)
def build_menu(docs, filename, relative_main_index): # TODO Maybe this could be part of DocsWriter itself, "build path menu" docs.add_menu('API', relative_main_index) items = filename.split('/') for i in range(len(items) - 1): item = items[i] link = '../' * (len(items) - (i + 2)) ...
[ "def _build_menu(docs):\n\n paths = []\n current = docs.filename\n top = pathlib.Path('.')\n while current != top:\n current = current.parent\n paths.append(current)\n\n for path in reversed(paths):\n docs.add_menu(path.stem.title() or 'API', link=path / 'index.html')\n\n if d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates the index file for the specified folder
def generate_index(folder, original_paths): # Determine the namespaces listed here (as sub folders) # and the files (.html files) that we should link to namespaces = [] files = [] for item in os.listdir(folder): if os.path.isdir(os.path.join(folder, item)): namespaces.append(ite...
[ "def _generate_index(folder, paths,\n bots_index=False, bots_index_paths=()):\n # Determine the namespaces listed here (as sub folders)\n # and the files (.html files) that we should link to\n namespaces = []\n files = []\n INDEX = 'index.html'\n BOT_INDEX = 'botindex.html'\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates the documentation HTML files from from scheme.tl to /methods and /constructors, etc.
def generate_documentation(scheme_file): original_paths = { 'css': 'css/docs.css', 'arrow': 'img/arrow.svg', '404': '404.html', 'index_all': 'index.html', 'index_types': 'types/index.html', 'index_methods': 'methods/index.html', 'index_constructors': 'construc...
[ "def _write_html_pages(tlobjects, methods, layer, input_res):\n # Save 'Type: [Constructors]' for use in both:\n # * Seeing the return type or constructors belonging to the same type.\n # * Generating the types documentation, showing available constructors.\n paths = {k: pathlib.Path(v) for k, v in (\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read MA observations of source files.
def read_ma_source_file(f): cols = ['affiliations', 'countries', "author"] df = pd.read_csv(f, encoding="utf8", usecols=cols) df["ma"] = (df["affiliations"].str.find(";") != -1).astype("uint8") df = (df.drop("affiliations", axis=1) .sort_values("ma", ascending=False)) return df.drop_dupl...
[ "def _Read_atmo(self, atmo_fln):\n f = open(atmo_fln,'r')\n lines = f.readlines()\n self.atmo_grid = []\n self.atmo_doppler = []\n for line in lines:\n if (line[0] != '#') and (line[0] != '\\n'):\n tmp = line.split()\n self.atmo_grid.append...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the remote configuration service proxy class. A collector should have retrieved the configuration service proxy based upon the collector's ICollectorPreferences implementation. a proxy object for the remote configuration service
def getRemoteConfigServiceProxy(self):
[ "def proxy_service(self):\n return self.data.get(\"http_proxy\")", "def get_configuration_lookup_session(self, proxy):\n return # osid.configuration.ConfigurationLookupSession", "def get_server_proxy():\n cp = get_configparser() # assuming it's already loaded at this point\n address = 'http...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the collector's property items.
def getPropertyItems(self, prefs):
[ "def propertyCollection(self):\n return self._environment.propertyCollection()", "def get_properties(self):\n return self._properties", "def getProperties(self):\n return self.properties", "def getProperties(self):\n props = list(self._db.keys())\n return props", "def coll...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the collector's required threshold classes.
def getThresholdClasses(self, prefs):
[ "def getThresholds(self, prefs):", "def get_threshold(self):\n pass", "def get_toxicity_classes(preds, threshold=0.6, classes=None):\n if classes is None:\n classes = ['toxic', 'severe_toxic', 'obscene',\n 'threat', 'insult', 'identity_hate']\n\n if sum(preds > threshold) >...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the collector's threshold definitions.
def getThresholds(self, prefs):
[ "def getThresholdClasses(self, prefs):", "def get_threshold(self):\n pass", "def threshold(self):\n return self._get('detector', 'config/threshold/1/energy')['value']", "def get_thresholds() -> (float, float):\n threshold_bottom = random.randrange(250, 850, 1)\n thr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove tasks from scheduler.
def removeTasks(self, taskNames):
[ "def removeTasks(self):\r\n taskMgr.remove('mouse-task')\r\n taskMgr.remove('move-task')", "def removeAllTasks(self):\n for taskInfo in self._tasks.values():\n task = taskInfo[0]\n task.remove()\n self._tasks = {}", "def removeTasksForConfig(self, configId):", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all tasks associated with the specified identifier.
def removeTasksForConfig(self, configId):
[ "def clear_tasks(except_task_id=None):\n from contentcuration.celery import app\n\n # remove any other tasks\n qs = TaskResult.objects.all()\n if except_task_id:\n qs = qs.exclude(task_id=except_task_id)\n for task_id in qs.values_list(\"task_id\", flat=True):\n app.control.revoke(task_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pauses, but does not stop, all tasks associated with the provided configuration identifier.
def pauseTasksForConfig(self, configId):
[ "def resumeTasksForConfig(self, configId):", "def pause(taskID):\r\n _activeScheduler.pause(taskID)", "def removeTasksForConfig(self, configId):", "def cluster_pause(cluster_id):\n cluster_manager = get_cluster_manager()\n for c in cluster_id:\n print(f\"Pausing cluster `{c}`...\")\n cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resumes all paused asks associated with the provided configuration identifier.
def resumeTasksForConfig(self, configId):
[ "def resume(self, config_info):\n cfg = self._getcfg(config_info)\n try:\n ret = self._resume(cfg[0], cfg[1])\n except Exception as err:\n if self._user == \"UT\":\n raise err\n LOGGER.error(\"%s.%s: %s\", self.__class__.__name__,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called after a task has been scheduled. The scheduler instance is passed so that the scheduled task can manipulate it's (or another task's) schedule.
def scheduled(self, scheduler):
[ "def handle(self):\n finished = self.scheduler.wait_for_exit(self.task, self.tid)\n self.task.sendval = finished\n if finished:\n self.scheduler.schedule(self.task)", "def new_scheduler(self, ruta_tasks):\n self.del_scheduler()\n self.sched = scheduler(ruta_tasks)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the value provided for the specified metric to Redis
def writeMetric( self, path, metric, value, timestamp, metricType, metricId, min, max, hasThresholds, threshEventData, allowStaleDatapoint, ):
[ "def write_to_redis(json_file):\n redis_data=json_file\n redis_data_dict=json.loads(redis_data) \n r.hmset('sample1',redis_data_dict)", "def _write_metric(metric, filename):\n with open(filename, \"w\") as metric_file:\n metric_file.write(str(metric))", "def save_value(self, key, value):\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the value provided in the command to the RRD file specified in path. If the RRD file does not exist, use the rrdType, rrdCommand, min and max parameters to create the file.
def writeRRD( self, path, value, rrdType, rrdCommand=None, cycleTime=None, min="U", max="U", threshEventData=None, timestamp="N", allowStaleDatapoint=True, ):
[ "def save_rr_file(filename, probs, domain, sequence,\n method='dm-contacts-resnet'):\n assert len(sequence) == probs.shape[0]\n assert len(sequence) == probs.shape[1]\n with tf.io.gfile.GFile(filename, 'w') as f:\n f.write(RR_FORMAT.format(domain, method, sequence))\n for i in range(probs.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the framework's implementation of the IConfigurationProxy interface.
def getConfigurationProxy(self):
[ "def get_configuration_lookup_session(self, proxy):\n return # osid.configuration.ConfigurationLookupSession", "def get_configuration_admin_session(self, proxy):\n return # osid.configuration.ConfigurationAdminSession", "def proxy_config(self) -> Optional['outputs.MustGatherSpecProxyConfig']:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the framework's buildOptions method.
def getFrameworkBuildOptions(self):
[ "def get_framework_build_config(self) -> Optional[Dict[str, str]]:\n raise NotImplementedError", "def buildOptions(self):\n return self.buildDict.keys()", "def GetBuildOptions(self, config):\n options = self._GetOptions(self.build_options, config)\n\n version_string = self._GetXcodeVersionSt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when a configuration is deleted from the collector
def deleted(self, configurationId):
[ "def process_delete_config_command(self, message: dict) -> None:\n status = True\n trigger_id = int(message.get('triggerId'))\n self.log.info(f'feature=service, event=delete-config, trigger_id={trigger_id}')\n\n # unregister config apiToken\n self.token.unregister_token(trigger_id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }