query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Obtain the statistics of a NIC.
def get_nic_statistics(self, nic_id): return self._nic_mgmt.get_nic_statistics(nic_id)
[ "def net_if_stats():\n ret = {}\n rawdict = cext.net_if_stats()\n for name, items in rawdict.items():\n if not PY3:\n assert isinstance(name, unicode), type(name)\n name = py2_strencode(name)\n isup, duplex, speed, mtu = items\n if hasattr(_common, 'NicDuplex'):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the system id.
def get_system_id(self): return system.SystemManagement(self.client).get_system_id()
[ "def get_system_id(self):\n return self.machine_config_file_value(\"DEFAULT.SID\").strip('\"')", "def system_id(self) -> Optional[str]:\n return self.db_msg.system_pkid if self.db_msg is not None else None", "def file_system_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"file_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the system model name.
def get_system_model_name(self): return system.SystemManagement(self.client).get_system_model_name()
[ "def modelname(self):\n return self.descriptions[0].device_model_name", "def get_model_name(self) -> str:\n return self._get_string(openvr.Prop_RenderModelName_String)", "def model_name(self) -> str:\n return self.profile_device.model_name", "def model_name(self) -> str:\n return s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the system service tag.
def get_system_service_tag(self): return system.SystemManagement(self.client).get_system_service_tag()
[ "def service_tag(self) -> str:\n return pulumi.get(self, \"service_tag\")", "def get_service_tag():\n serialfile = '/etc/dxmini_serial'\n if os.path.isfile(serialfile):\n logger.info(\"Reading SERVICE_TAG...\")\n with open(serialfile,\"r\") as fi:\n serial = fi.read()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if the legacy, nonUEFI, boot protocol of a NIC is NONE, false otherwise.
def is_nic_legacy_boot_protocol_none(self, nic_id): return self._nic_cfg.is_nic_legacy_boot_protocol_none(nic_id)
[ "def is_nic_legacy_boot_protocol_pxe(self, nic_id):\n return self._nic_cfg.is_nic_legacy_boot_protocol_pxe(nic_id)", "def check_ethernet_network():\n default_iface = get_default_route()\n\n assert default_iface[1] == sc.conf.iface, \"incorrect sc.conf.iface\"\n iface_str = ''\n if sys.platform....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if the legacy, nonUEFI, boot protocol of a NIC is PXE, false otherwise.
def is_nic_legacy_boot_protocol_pxe(self, nic_id): return self._nic_cfg.is_nic_legacy_boot_protocol_pxe(nic_id)
[ "def is_ipxe_enabled(task):\n return 'ipxe_boot' in task.driver.boot.capabilities", "def __is_802_compatible(self):\n if self.__xbee_device.get_protocol() != XBeeProtocol.RAW_802_15_4:\n return False\n param = None\n try:\n param = self.__xbee_device.get_parameter(ATS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if the link status of a NIC is up, false otherwise.
def is_nic_link_up(self, nic_id): return self._nic_mgmt.is_nic_link_up(nic_id)
[ "def is_interface_up(self, interface_name):\n try:\n lines = subprocess.check_output(self.IP_LINK).splitlines()\n except subprocess.CalledProcessError as e:\n raise EnvironmentError('Failed to call \"ip link\": %r', e.message)\n\n for line in lines:\n if interface_name in line and 'LOWER_UP'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the list of integrated NICs.
def list_integrated_nics(self, sort=False): return self._nic_mgmt.list_integrated_nics(sort)
[ "def list():\n\n\treturn netifaces.interfaces()", "def list_nics(self, sort=False):\n return self._nic_mgmt.list_nics(sort)", "def find_nic():\n result = subprocess.run([\"iw\", \"dev\"], capture_output=True).stdout.decode()\n network_interface_controllers = wlan_code.findall(result)\n return ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the list of attribute settings of a NIC.
def list_nic_settings(self, nic_id): return self._nic_cfg.list_nic_settings(nic_id)
[ "def get_nic_attributes(cls, interface):\n return NodeNICInterfaceClusterPlugin.\\\n get_all_enabled_attributes_by_interface(interface)", "def get_nic_settings(bmc):\n nic_settings = bmc.list_nics()\n return nic_settings", "def get_attribute_list(self):\n return self.dp.get_attrib...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the list of NICs.
def list_nics(self, sort=False): return self._nic_mgmt.list_nics(sort)
[ "def list():\n\n\treturn netifaces.interfaces()", "def do_nic_list(cc, args):\n nics = cc.nic.list()\n names = ['%s (uuid) %s (mac)' % (nic.get('uuid'), nic.get('mac')) for nic in\n nics['nics']]\n cliutils.print_list(names, args.json)", "def ex_list_networks(self):\n list_networks =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedules jobs for execution in a specified order.
def schedule_job_execution(self, job_ids, start_time='TIME_NOW'): return self._job_mgmt.schedule_job_execution(job_ids, start_time)
[ "def schedule(self, jobs):\n assert(isinstance(jobs, list) or jobs is None)\n with self.__lock:\n for job in jobs:\n while True:\n try:\n self.__queue.put(job, False)\n self.__lock.notify_all()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the legacy, nonUEFI, boot protocol of a NIC. If successful, the pending value of the NIC's legacy boot protocol attribute is set. For the new value to be applied, a configuration job must be created and the node must be rebooted.
def set_nic_legacy_boot_protocol(self, nic_id, value): return self._nic_cfg.set_nic_legacy_boot_protocol(nic_id, value)
[ "def set_nic_legacy_boot_protocol_none(self, nic_id):\n return self._nic_cfg.set_nic_legacy_boot_protocol(nic_id, 'NONE')", "def set_nic_legacy_boot_protocol_pxe(self, nic_id):\n return self._nic_cfg.set_nic_legacy_boot_protocol(nic_id, 'PXE')", "def set_pending_boot_mode(self, boot_mode):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the legacy, nonUEFI, boot protocol of a NIC to NONE. If successful, the pending value of the NIC's legacy boot protocol attribute is set. For the new value to be applied, a configuration job must be created and the node must be rebooted.
def set_nic_legacy_boot_protocol_none(self, nic_id): return self._nic_cfg.set_nic_legacy_boot_protocol(nic_id, 'NONE')
[ "def set_nic_legacy_boot_protocol(self, nic_id, value):\n return self._nic_cfg.set_nic_legacy_boot_protocol(nic_id, value)", "def is_nic_legacy_boot_protocol_none(self, nic_id):\n return self._nic_cfg.is_nic_legacy_boot_protocol_none(nic_id)", "def set_nic_legacy_boot_protocol_pxe(self, nic_id):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the legacy, nonUEFI, boot protocol of a NIC to PXE. If successful, the pending value of the NIC's legacy boot protocol attribute is set. For the new value to be applied, a configuration job must be created and the node must be rebooted.
def set_nic_legacy_boot_protocol_pxe(self, nic_id): return self._nic_cfg.set_nic_legacy_boot_protocol(nic_id, 'PXE')
[ "def set_nic_legacy_boot_protocol(self, nic_id, value):\n return self._nic_cfg.set_nic_legacy_boot_protocol(nic_id, value)", "def set_pending_boot_mode(self, boot_mode):\n boot_mode = boot_mode.lower()\n if boot_mode not in ['uefi', 'legacy']:\n msg = 'Invalid Boot mode specified'\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modify a setting of a NIC. If successful, the pending value of the attribute is set. For the new value to be applied, a configuration job must be created and the node must be rebooted.
def set_nic_setting(self, nic_id, attribute_name, value): return self._nic_cfg.set_nic_setting(nic_id, attribute_name, value)
[ "def do_nic_update(cc, args):\n\n patch = utils.args_array_to_patch(args.attributes[0])\n result = cc.nic.update(args.uuid, patch)\n cliutils.print_dict(result)", "def icpw_update_metric(self, name, icpw_value):\n\n metric = self._get_metric_by_name(name)\n\n if metric:\n metric....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modify one or more settings of a NIC. If successful, the pending values of the attributes are set. For the new values to be applied, a configuration job must be created and the node must be rebooted.
def set_nic_settings(self, nic_id, settings): return self._nic_cfg.set_nic_settings(nic_id, settings)
[ "def set_nic_setting(self, nic_id, attribute_name, value):\n return self._nic_cfg.set_nic_setting(nic_id, attribute_name, value)", "def do_nic_update(cc, args):\n\n patch = utils.args_array_to_patch(args.attributes[0])\n result = cc.nic.update(args.uuid, patch)\n cliutils.print_dict(result)", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies all pending changes on a RAID controller ...by creating a config job.
def commit_pending_raid_changes(self, raid_controller, reboot=False, start_time='TIME_NOW'): return self._job_mgmt.create_config_job( resource_uri=ironic_uris.DCIM_RAIDService, cim_creation_class_name='DCIM_RAIDService', cim_name='DCIM:RAID...
[ "def apply_pending_config(node, **kwargs):\n\n raid_controller = None\n error_msgs = []\n\n # RAID controller validation\n raid_controller = drac_common.validate_required_string(kwargs,\n 'raid_controller',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate weightmaps for the images using the binary masks
def create_weightmaps(path, folders, w0=10., sigma=3., thresh_fn=lambda x:x>0, name_weights_folder=True): # set up some pipelines w_pipe = ImageWeightMap2(w0=w0, sigma=sigma) for d in folders: ...
[ "def create_train_data(self, wmap):\n\n i = 0\n print('-' * 30)\n print('Creating training images...')\n print('-' * 30)\n\n # original\n imgs = glob.glob(self.data_path + \"/*/*\")\n\n\n imgdatas = np.ndarray((len(imgs), self.out_rows, self.out_cols, 1), dtype=np.ui...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates current data with dataframe, stores old data in history
def update_current_data(self, data): if self.current_data is not None: current_results = self.get_results() self._history.append((self.current_data, current_results)) self.current_data = data
[ "def _update(self):\n self.history = pd.concat([self.history, self._check_stats()], ignore_index=True)", "def _update_from_latest_data(self):\n raise NotImplementedError", "def hdf_obj_update_dataframe(self,df,key=None,reset=True,**storer_attrs):\n #-- avoid error in python3 pandas HDF e.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aggregated history, i.e. in two single dataframes corresponding to "current data" attributes and results
def agg_history(self): cd_list, cr_list = zip(*self._history) return pd.concat(cd_list), pd.concat(cr_list)
[ "def _calculate_history(self, df: DataFrame) -> DataFrame:\n\n base_columns = {\"op\", \"id\", \"ts\"}\n data_columns = list(set(df.schema.names) - base_columns)\n\n window_spec = Window.partitionBy(\"id\").orderBy(\"ts\")\n agg_columns = [last(column, ignorenulls=True).over(window_spec)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function partly overrides the standard QFileSystemModel data function to return custom file and folder icons
def data(self, index, role): fileInfo = self.getFileInfo(index)[4] if role == QtCore.Qt.DecorationRole: if fileInfo.isDir(): return QtGui.QPixmap(os.path.join(ICONS_L, 'Folder.png')) elif fileInfo.isFile(): return QtGui.QPixmap(os.path.jo...
[ "def data(self, index, role):\r\n fileInfo = self.getFileInfo(index)[4]\r\n\r\n if role == QtCore.Qt.DecorationRole:\r\n if fileInfo.isDir():\r\n return QtGui.QPixmap(ICONS_L + 'Folder.png')\r\n elif fileInfo.isFile():\r\n return QtGui.QPixmap(ICONS_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The external fixed IPs of the router.
def external_fixed_ips(self) -> Sequence['outputs.GetRouterExternalFixedIpResult']: return pulumi.get(self, "external_fixed_ips")
[ "def fixed_ip_address(self):\n return self._fixed_ip_address", "def get_floating_ips(self):\n return self.router.get(l3_constants.FLOATINGIP_KEY, [])", "def ip_addresses(self):\n try:\n return socket.gethostbyaddr(self.fqdn)[-1]\n except socket.error as _:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The network UUID of an external gateway for the router.
def external_network_id(self) -> str: return pulumi.get(self, "external_network_id")
[ "def network_id(self) -> str:\n return pulumi.get(self, \"network_id\")", "def get_network_id(self):\n\t\treturn call_sdk_function('PrlVirtNet_GetNetworkId', self.handle)", "def network_address(self) -> str:\n return pulumi.get(self, \"network_address\")", "def get_device_id(self, network):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if attribute is a property.
def isprop(v): return isinstance(v, property)
[ "def _is_property(cls, member):\n return isinstance(member, property)", "def isproperty(object):\n return isinstance(object, property)", "def is_attribute(klass, attr, value=None):\n if value is None:\n value = getattr(klass, attr)\n assert getattr(klass, attr) == value\n\n if not insp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculates beam xy and other parameters.
def calculate_beam_xy(self): info = [] # Import relevant info pixel_size = self.info.pixel_size for i in [j.final for j in self.final_objects]: try: info.append( [ i, i["beamX"], ...
[ "def get_beam_origin(self):\n\n distance = self.dict[\"distance\"]\n beam = vec3(self.dict[\"beam\"])\n\n XDSdetector_X = vec3(self.dict[\"detector_X\"])\n XDSdetector_Y = vec3(self.dict[\"detector_Y\"])\n XDSdetector_Z = XDSdetector_X.cross(XDSdetector_Y)\n\n # Calculate t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls unit cell analysis module, which uses hierarchical clustering (Zeldin, et al, Acta D, 2015) to split integration results according to detected morphological groupings (if any). Most useful with preliminary integration without target unit cell specified.
def unit_cell_analysis(self): # Will not run clustering if only one integration result found or if turned off if not self.info.categories["integrated"]: util.main_log( self.info.logfile, "\n\n{:-^80}\n".format(" UNIT CELL ANALYSIS "), True ) util.main...
[ "def run_units(self):\n pass", "def unit_cell_info(sub_clusters):\n from libtbx.utils import plural_s\n # 3. print out some information that is useful.\n out_str = \"\\n\\n{:<16} {:<8} {:<13} {:<13} {:<13} {:<12} {:<12} {:<12}{:<8}\\n\".format(\n \"Cluster_id\",\n \"N_xtals\",\n \"Med_a\", \"Me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports default PRIME input parameters, modifies correct entries and prints out a starting PHIL file to be used with PRIME.
def make_prime_input(self, filename="prime.phil", run_zero=False): assert self.info pixel_size = self.info.pixel_size hres = self.info.stats["res"] lres = self.info.stats["lres"] # If symmetry / unit cell were not overridden from GUI, set from INFO if not self.best_pg: ...
[ "def help():\n\n sys.stdout.write(\"%s\\n\" % Version)\n\n # FIXME also needs to make reference to Phil input\n # FIXME ideally should move all command-line functionality over to Phil...\n # FIXME these should also be generated in automatic way #42\n\n sys.stdout.write(\"An expert system for automate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
根据识别出来的raw txt文件中的坐标点信息,查找水印区域 假定:水印区域(台标)的坐标在水平和垂直方向都是固定的,也就是具有(xmin, xmax, ymin, ymax)相对固定 根据坐标点信息,进行统计,将一直具有固定坐标的文本区域选出
def _detect_watermark_area(self): f = open(self.raw_subtitle_path, mode='r', encoding='utf-8') # 打开txt文件,以‘utf-8’编码读取 line = f.readline() # 以行的形式进行读取文件 # 坐标点列表 coordinates_list = [] # 帧列表 frame_no_list = [] # 内容列表 content_list = [] while line: ...
[ "def get_zone(text_reg):\n posi_zone = []\n gray_zone = []\n for txt in text_reg:\n x1, y1, x2, y2 = txt[0], txt[1], txt[2], txt[3]\n x3, y3, x4, y4 = txt[4], txt[5], txt[6], txt[7]\n line_1_2_len = np.sqrt(np.square(x1 - x2) + np.square(y1 - y2))\n line_1_4_len = np.sqrt(np.squ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
给定一个坐标列表,将这个列表中相似的坐标统一为一个值 e.g. 由于检测框检测的结果不是一致的,相同位置文字的坐标可能一次检测为(255,123,456,789),另一次检测为(253,122,456,799) 因此要对相似的坐标进行值的统一
def _unite_coordinates(self, coordinates_list): # 将相似的坐标统一为一个 index = 0 for coordinate in coordinates_list: # TODO:时间复杂度n^2,待优化 for i in coordinates_list: if self.__is_coordinate_similar(coordinate, i): coordinates_list[index] = i inde...
[ "def closest_coord(self, list, coord):\n\n closest = (0,0)\n second_closest = (0,0)\n for c in list:\n if self.distance(c, coord) < self.distance(closest, coord) and (c != coord):\n second_closest = closest\n closest = c\n #print(closest, coord)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This main function allows you to run the backup manually.
def main(): parser = init_parser() args = parser.parse_args() # Set up logging. level = logging.INFO if args.debug: level = logging.DEBUG logging.basicConfig(format='%(asctime)s %(levelname)s %(filename)s:' \ '%(lineno)s %(message)s ', level=level) logging.info("Logging started") message = "B...
[ "def run_backup():\n\n from common.models import InvenTreeSetting\n\n if not InvenTreeSetting.get_setting('INVENTREE_BACKUP_ENABLE', False, cache=False):\n # Backups are not enabled - exit early\n return\n\n interval = int(InvenTreeSetting.get_setting('INVENTREE_BACKUP_DAYS', 1, cache=False))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a function which takes Paths into the user data and returns csums.
def reverser(num_segs=3): r = re.compile("((\/([0-9]|[a-f])+){%d})$" % (num_segs+1)) def checksum_from_link(link): """Takes a path into the userdata, returns the matching csum.""" m = r.search(safetype(link)) if (m): csum_slash = m.group()[1:] csum = _remove_sep_(csum_slash) return csu...
[ "def CalculateHostMd5Sums(paths):\n if isinstance(paths, basestring):\n paths = [paths]\n\n out = cmd_helper.GetCmdOutput(\n [os.path.join(constants.GetOutDirectory(), 'md5sum_bin_host')] +\n [p for p in paths])\n return [HashAndPath(*l.split(None, 1)) for l in out.splitlines()]", "def _md5sum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return absolute Path to a blob given a csum
def csum_to_path(self, csum): #TODO remove callers so we can make internal. return Path(self._csum_to_name(csum), self.root)
[ "def link_to_blob(self, path, csum):\n new_link = self.csum_to_path(csum)\n ensure_symlink(path, new_link)\n ensure_readonly(path)", "def getBlobFilePath(self, oid, tid):\n oid_path = self.oid_to_path(oid)\n filename = \"{}{}\".format(utils.tid_repr(tid), BLOB_SUFFIX)\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a csum, and removes it from the blobstore
def delete_blob(self, csum): blob_path = self.csum_to_path(csum) blob_path.unlink(clean=self.root)
[ "def rm_data(self, data):\n pass", "def perform_remove(self, addr, length):\n\t\treturn 0", "def remove(self, obj):\n self.bin_list.remove(obj)\n self.sum -= obj", "def _remove_node_from_hash_ring(self):", "def remove(self, obj):\n self.size -= 1\n obj.hash_reference.entry...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Forces path into a symlink to csum
def link_to_blob(self, path, csum): new_link = self.csum_to_path(csum) ensure_symlink(path, new_link) ensure_readonly(path)
[ "def symlink(self, path, target, *args, **kwargs): # pragma: no cover", "def relink(f):\n if os.path.islink(f):\n linkto = os.path.join(NEW_LINK_BASE, os.path.basename(os.readlink(f)))\n #print 'Relinking %s-> %s from \\n %s' % (f, linkto, os.readlink(f))\n #print 'removing %s' % f\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True when the blob's checksum matches. Returns False when there is a checksum corruption.
def verify_blob_checksum(self, blob): path = self.csum_to_path(blob) csum = path.checksum() return csum != blob
[ "def validate_checksum(self):\n return self.calculate_checksum() == self.checksum()", "def has_consistent_checksum(self):\n\t\treturn True if (self.pe_object.get_opptional_header_checksum() == self.pe_object.recalculate_checksum()) else False", "def verify_checksum(self):\n return self.generate_he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True when the blob's permissions is read only. Returns False when the blob is mutable.
def verify_blob_permissions(self, blob): path = self.csum_to_path(blob) return is_readonly(path)
[ "def is_read_only(self):\n\t\treturn bool(call_sdk_function('PrlShare_IsReadOnly', self.handle))", "def is_read_only(self):\n return self._is_read_only", "def has_read_access():\n return api.is_admin() or api.is_group_member('groups-readonly-access')", "def storage_can_read(self):\n return True...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterator across all blobs
def blobs(self): def blob_iterator(): with s3conn(self.access_id, self.secret) as s3: key_iter = s3.list_bucket(self.bucket, prefix=self.prefix+"/") for key in key_iter: blob = key[len(self.prefix)+1:] yield blob return ...
[ "def blob_generator(self):\n for blob in self.data:\n yield blob", "def blob_stats(self):\n def blob_iterator():\n with s3conn(self.access_id, self.secret) as s3:\n key_iter = s3.list_bucket2(self.bucket, prefix=self.prefix+\"/\")\n for head in key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterator across all blobs, retaining the listing information
def blob_stats(self): def blob_iterator(): with s3conn(self.access_id, self.secret) as s3: key_iter = s3.list_bucket2(self.bucket, prefix=self.prefix+"/") for head in key_iter: blob = head[LIST_BUCKET_KEY][len(self.prefix)+1:] h...
[ "def blobs(self):\n def blob_iterator():\n with s3conn(self.access_id, self.secret) as s3:\n key_iter = s3.list_bucket(self.bucket, prefix=self.prefix+\"/\")\n for key in key_iter:\n blob = key[len(self.prefix)+1:]\n yield blob\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reload a module, either larch or python
def _reload(mod,larch=None,**kw): if isinstance(mod, str): return larch.import_module(mod, do_reload=True) for k,v in chain(larch.symtable._sys.modules.iteritems(), sys.modules.iteritems()): if v == mod: modname = k break try: return larch.import_module(modn...
[ "def reload_module(module_name):\n try:\n reload(eval(module_name))\n except:\n pass", "def reloadModule(module):\n\ttry:\n\t\treload # Python 2.7\n\texcept NameError:\n\t\ttry:\n\t\t\tfrom importlib import reload # Python 3.4+\n\t\texcept ImportError:\n\t\t\tfrom imp import reload # Python...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show lines of text in the style of more
def show_more(text,filename=None,writer=None,pagelength=30,prefix=''): # pragma: no cover pager(text)
[ "def MoreMessage(self):\r\n self.Input(\"[--more--]\")\r\n self.HomeCursor()", "def MoreMessage(self):\r\n \r\n OldRow = WConio.wherey()\r\n OldColumn = WConio.wherex()\r\n WConio.textattr(self.A_MORE)\r\n WConio.cputs(\"[--more--]\")\r\n WConio.textattr(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
class that maintains all data related to the regulatory on the FContact
def __init__(self, contact = None): try: self.__contact = contact if not self.__contact: FRegulatoryLogger.ERROR(logger, "The name on the contact is the unique identifier of the contact. Kindly provide a valid acm.FContact object") return None ...
[ "def RegulatoryInfo(self):\n conactRegInfo = FContactRegulatoryInfo(self)\n return conactRegInfo", "def Attributes(self):\n return FRegulatoryUtils.log_attributes('FContactRegulatoryInfo', self)", "def init(self):\n self.contacts_changed = False\n self.refresh_contacts = False \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NationalId of the concerned natural person
def NationalId(self, reg_national_id = VALUE_NOT_SET): if reg_national_id != VALUE_NOT_SET: self.__reg_national_id = reg_national_id try: self.__contact.AdditionalInfo().NationalId(self.__reg_national_id) except: pass else: ...
[ "def unique_id(dn):\n dn_parts = explode_dn(dn)\n reg = re.compile('uniqueIdentifier=(.*)', re.IGNORECASE)\n for part in dn_parts:\n matcher = reg.match(part)\n if matcher:\n return matcher.groups()[0]\n raise INVALID_PERSON_DN(dn)", "def person_id(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An optional unique name, if specified there can only be one contact with this name for each party.
def UniqueName(self, unique_name = VALUE_NOT_SET): if unique_name != VALUE_NOT_SET: try: if FIntegrationUtils.FIntegrationUtils.get_acm_version_override() >= 2017.2: self.__contact.UniqueName(unique_name) else: is_unique, contac...
[ "async def contact_self_name(self, name: str) -> None:", "def addName(self, *args):\n return _yarp.Contact_addName(self, *args)", "def upgrade_unique_name(self, contact):\n try:\n if self.integration_utils.get_acm_version_override() >= 2017.2 and contact.AdditionalInfo().UniqueName():\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the ClientType based on where the CrmId is found on the linked objects
def ClientType(self): self.__client_type = FRegulatoryUtils.getClientType(self.__contact) return self.__client_type
[ "def client_type(self) -> Optional[str]:\n return pulumi.get(self, \"client_type\")", "def getRelType(self):\n return self.type", "def contact_type(self):\n return self._contact_type", "def GetReferenceIdTypeInfo(item):\r\n\r\n assert item.ReferencedObject.children\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Committing this instance will automatically commit all the RegulatorySupport related attributes on the contact
def Commit(self): try: acm.BeginTransaction() self.__contact.Commit() if FIntegrationUtils.FIntegrationUtils.get_acm_version_override() < 2015.4: self.__integration_utils.set_additional_info('DateOfBirth', self.__contact, self.__reg_date_of_birth) ...
[ "def commit(self):\n self.__target.commit()", "def commit(self):\n self.success = True\n self.close()", "def commit(self):\n self.DB.commit()", "def __save_contact_information(self):\n try:\n ContactInformation.objects.create(user=self.user, **self.contact_info)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deleting this instance automatically deletes all the attributes related to the reporting on the instrument or on the ContactRegulatoryInfo in the ADS
def Delete(self): FRegulatoryUtils.Delete(self.__contact, "Contact") FRegulatoryLogger.DEBUG(logger, "Deleted all AdditionalInfos on Contact related to Regulatory Reporting")
[ "def cleanup_aai(cls):\n logger.info(\"####################### Start to clean up AAI settings\")\n aai = Customer.get_by_global_customer_id(\"5GCustomer\")\n aai.delete()", "def delete_contact_reg_info(self, contact):\n add_info_specs = ['dateOfBirth', 'firstName', 'lastName', 'nationa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the attributes on the FContactRegulatoryInfoBase instance
def Attributes(self): return FRegulatoryUtils.log_attributes('FContactRegulatoryInfo', self)
[ "def RegulatoryInfo(self):\n conactRegInfo = FContactRegulatoryInfo(self)\n return conactRegInfo", "def get_attributes(self):\r\n\r\n return(self.mechanism_id, self.load_id, self.description,\r\n self.damage_model, self.priority)", "def get_attributes(self):\n\n _attributes = (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the FContactRegulatoryInfoBase instance for the given contact
def RegulatoryInfo(self): conactRegInfo = FContactRegulatoryInfo(self) return conactRegInfo
[ "def __init__(self, contact = None):\n try:\n self.__contact = contact\n if not self.__contact:\n FRegulatoryLogger.ERROR(logger, \"The name on the contact is the unique identifier of the contact. Kindly provide a valid acm.FContact object\")\n return None\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to print a header with satellite info for the satellite number
def print_satellite_header(st): # Retrieve TLE data print "Satellite Number/Launch Year/Launch Number of Year: %s/20%s/%s" % \ (st.get_satellite_number(), st.get_launch_year(), \ st.get_launch_year_number()) year = 2000 + int(st.get_epoch_year()) fracyear = timedelta(float(st.get_ep...
[ "def print_header_information():\n\t\tprint \"Elijah Molloy\"\n\t\tprint \"70-510 - Spring 1 - 2018\"\n\t\tprint \"PROGRAMMING ASSIGNMENT #4\\n\"", "def PrintHeader(self):", "def print_the_header():\n print('-------------------')\n print(' Weather APP')\n print('-------------------')\n print()",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to print the inviews
def print_inviews(gs, inviews): #print "Number of inviews from %s to %s: %d" % \ # (today_start.isoformat(), today_end.isoformat(),len(inviews)) for i in range(0, len(inviews)): #print "%s to %s" % (inviews[i][0].isoformat(), inviews[i][1].isoformat()) print_inview(inviews[i][0], invi...
[ "def print_details(self):\n self.view.print_details()", "def _print_inwards(middleware_name):\n if _VERBOSE_MODE:\n print('{}--->'.format(middleware_name))", "def showContents(self):\n if self.exposures.__len__() > 0:\n for i,exp in enumerate(self.exposures):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to print a table of time, azimuth, elevation for each inview
def print_azeltables(inviews, ic): for i in range(0, len(inviews)): print " " print "Az/El for inview %s to %s" % (inviews[i][0], inviews[i][1]) azels = ic.compute_azels(inviews[i][0], inviews[i][1], 15) for j in range(0, len(azels)): print "At %s, azimuth=%8.2f, elevatio...
[ "def info(self):\n tline = \"\"\n for (ii, projection) in enumerate(self._ProjectionList):\n tiltAngle = projection._tiltAngle\n transX = -projection._alignmentTransX\n transY = -projection._alignmentTransY\n rot = -(projection._alignmentRotation + 90.)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use as a decorator to print info about the function and its result. Follows deferred results.
def showResult(f): def substitute(self, *args, **kw): def msg(result, callInfo): resultInfo = str(result) if len(callInfo) + len(resultInfo) > 70: callInfo += "\n" print("\n{} -> {}".format(callInfo, resultInfo)) return result SR_STUFF...
[ "def result_logger(fct):\n\n\t\tdef wrapper(*args, **kw):\n\t\t\tret = fct(*args, **kw)\n\t\t\tlogger.debug(\"%s %s %s return %s\" % (\n\t\t\t\targs[0].__class__.__name__,\n\t\t\t\targs[0].__class__.__module__[len('metric_'):],\n\t\t\t\tfct.__name__, ret))\n\t\t\treturn ret\n\n\t\treturn wrapper", "def debug(func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the fully qualified name of the supplied string if it can be imported and then reflected back into the FQN, or C{None} if not.
def strToFQN(self, x): try: obj = reflect.namedObject(x) fqn = reflect.fullyQualifiedName(obj) except: return return fqn
[ "def eval_fully_qualified_name(name):\n if name is None:\n return None\n if isinstance(name, str):\n if \".\" in name:\n module_name, object_name = name.rsplit(\".\", 1)\n module = __import__(module_name, fromlist=[object_name])\n return getattr(module, object_na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the fully qualified name of the supplied object if it can be reflected into an FQN and back again, or C{None} if not.
def objToFQN(self, x): try: fqn = reflect.fullyQualifiedName(x) reflect.namedObject(fqn) except: return return fqn
[ "def full_object_name(obj):\n\n try:\n module = obj.__module__\n if module is None or module == str.__class__.__module__:\n return obj.__name__ # Avoid reporting __builtin__\n else:\n return module + '.' + obj.__name__\n except Exception:\n return None", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to convert the supplied object to a pickle and, failing that, to a fully qualified name.
def processObject(self, x): pickled = self.objToPickle(x) if pickled: return pickled return self.objToFQN(x)
[ "def pickle_object(obj, ofname: \"Path|str\"):\n ofname = Path(ofname)\n maybe_make_output_dir(ofname)\n with ofname.open(\"wb\") as f:\n pickle.dump(obj, f)", "def download_pickle(self, object_name):\n self.exists_object(object_name, raise_err=True)\n obj = self.download_object(obje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets my current fargskw tuple, returning a reference to myself to allow easy method chaining. The function I{f} must be an actual callable object if you want to use L{nn}. Otherwise it can also be a string depicting a callable. You can specify I{args} with a second argument (as a list or tuple), and I{kw} with a third ...
def setCall(self, *metaArgs, **kw): if metaArgs: equiv = True if self.lastMetaArgs is None: equiv = False elif len(metaArgs) != len(self.lastMetaArgs): equiv = False else: for k, arg in enumerate(metaArgs): ...
[ "def call(f):\n def g(*args, **kwds):\n return (f, args, kwds)\n return g", "def __call__(self, f: Callable[..., int]) -> LabelingFunction:\n name = self.name or f.__name__\n return LabelingFunction(name=name, f=f, resources=self.resources, pre=self.pre)", "def SetParseFn(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a unique ID for my current callable.
def ID(self): if hasattr(self, 'currentID'): return self.currentID if hasattr(self, 'callDict'): thisID = hashIt(self.callDict) if hasattr(self, 'pastInfo'): self.pastInfo[thisID] = {'callDict': self.callDict} else: thisID = None ...
[ "def get_id(function: Callable) -> str:\n return f\"{function.__module__}:{function.__name__}\"", "def get_ident():\r\n return id(greenthread.getcurrent())", "def func_id(self, function_name):\n id_number = self.id_dictionary[function_name]\n self.id_dictionary[function_name] += 1\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this whenever info won't be needed anymore for the specified call ID, to avoid memory leaks.
def forgetID(self, ID): if ID in getattr(self, 'pastInfo', {}): del self.pastInfo[ID]
[ "def refresh_usage(self, file_id: int):\n\t\tif file_id in self._temp_files:\n\t\t\tself._last_used.remove(file_id)\n\t\tself._last_used.append(file_id)", "def _validate_call_id(self, call_id):\n\n self._validate_required_data(call_id, self.CALL_ID)\n\n query = CallRecord.objects.filter(call_id=call...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Context manager for setting and getting call info. Call this context manager method with info about a particular call (same format as L{setCall} uses) and it yields an L{InfoHolder} object keyed to that call. It lets you get info about the call inside the context, without worrying about the ID or calling L{forgetID}, e...
def context(self, *metaArgs, **kw): if not hasattr(self, 'pastInfo'): raise Exception( "Can't use a context manager without saving call info") ID = self.setCall(*metaArgs, **kw).ID yield InfoHolder(self, ID) self.forgetID(ID)
[ "def aboutCall(self, ID=None, nowForget=False):\n if ID:\n pastInfo = self.getInfo(ID, 'aboutCall', nowForget)\n if pastInfo:\n return pastInfo\n callDict = self.getInfo(ID, 'callDict')\n if not callDict:\n return \"\"\n func, args, kw = [c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provides info about a call. If the supplied name is 'callDict', returns the fargskwinstance dict for my current callable. The value of I{ID} is ignored in such case. Otherwise, returns the named information attribute for the previous call identified with the supplied ID.
def getInfo(self, ID, name, nowForget=False): def getCallDict(): if hasattr(self, 'callDict'): result = self.callDict if nowForget: del self.callDict else: result = None return result if hasa...
[ "def aboutCall(self, ID=None, nowForget=False):\n if ID:\n pastInfo = self.getInfo(ID, 'aboutCall', nowForget)\n if pastInfo:\n return pastInfo\n callDict = self.getInfo(ID, 'callDict')\n if not callDict:\n return \"\"\n func, args, kw = [c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an informative string describing my current function call or a previous one identified by ID.
def aboutCall(self, ID=None, nowForget=False): if ID: pastInfo = self.getInfo(ID, 'aboutCall', nowForget) if pastInfo: return pastInfo callDict = self.getInfo(ID, 'callDict') if not callDict: return "" func, args, kw = [callDict[x] for ...
[ "def _function_name(func):\n return \"Calling the function: def {}()\".format(func.__name__)", "def get_call_string(self) -> Optional[str]: # noqa\n call_repr = get_call_string(self.func_name, self.args, self.kwargs, max_length=75)\n return call_repr", "def Detail(self):\n if self.hook_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an informative string describing an exception raised from my function call or a previous one identified by ID, or one you supply (as an instance, not a class).
def aboutException(self, ID=None, exception=None, nowForget=False): if ID: pastInfo = self.getInfo(ID, 'aboutException', nowForget) if pastInfo: return pastInfo if exception: lineList = ["Exception '{}'".format(repr(exception))] else: ...
[ "def __str__(self):\n return \"FigoException: {} ({})\".format(self.error_description, self.error)", "def __str__(self):\n return \"FigoPinException: {}({})\".format(self.error_description, self.error)", "def GetLoggingText():\r\n return '%s raised exception %s' % (util.FormatFunctionCall(ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this method is invoked on the first turn. first player can puts only one stone on board. this method should return 2tuple, default is (10, 10)
def firstMove(self): return (10, 10)
[ "def secondMove(board):\r\n # Get position of first tile\r\n (y1, x1) = board.black[0]\r\n\r\n if y1 <= board.size / 2:\r\n y2 = 1\r\n else:\r\n y2 = -1\r\n\r\n if x1 <= board.size / 2:\r\n x2 = 1\r\n else:\r\n x2 = -1\r\n return (y1 + y2, x1 + x2)", "def run(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize neural net and check output layer shape.
def test_init() -> None: neural_net = NeuralNetwork() assert neural_net.model.get_layer('output_layer').output_shape, (None, 4)
[ "def build_neural_net(self):\n if self.nn_type == '0':\n self.neural_net = tf.keras.Sequential([\n tfp.layers.DenseFlipout(256, activation=tf.nn.relu),\n tf.keras.layers.Dropout(rate=self.dropout_p),\n tfp.layers.DenseFlipout(256, activation=tf.nn.relu)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update the list of d_bison_obs
def update_d_bison_obs(bison_i): for i in range(obs_n): d_bison_obs[i][bison_i] = calculate_d(bison_x[bison_i], bison_y[bison_i], obstacles[i][0], obstacles[i][1])
[ "def setBoBs(self, bobs: list):\n self._bobarray = bobs", "def update_grating_obs_list():\n obs_dict = get_obsdate()\n\n tyear = int(time.strftime('%Y', time.gmtime()))\n tmon = int(time.strftime('%m', time.gmtime()))\n lyear = tyear + 1\n\n pyear = tyear\n pmon = tmon - 6\n if pmon ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if the distance between bison_i and obs_i less than 2.5, it should elude this obstacle
def elude_obstacles(bison_i, k): # Ax+By+C=0 global predict_wolf r = obstacles[k][2] xk = obstacles[k][0] yk = obstacles[k][1] a = (bison_y[bison_i] - wolf_y[0]) / (bison_x[bison_i] - wolf_x[0]) b = -1 c = bison_y[bison_i] - (a * bison_x[bison_i]) d_obs_dir = math.fabs(a * xk + b * y...
[ "def check_for_obstacles(self):\n obs = False\n obs_p = []\n for point in self.obstacles:\n if -0.15 <= point[1] <= 0.15: # robot is 178mm wide\n # Obstacles should be less than or equal to 0.2 m away before being detected\n if 0 <= point[0] <= .2:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find the index of minimum distance in list of d
def find_min_distance(): return np.argmin(d)
[ "def minDistance(self, dist, sptSet):\n\t\tminimum = sys.maxint\n\n\t\tfor v in range(self.V):\n\t\t\tif dist[v] < minimum and sptSet[v] == False:\n\t\t\t\tminimum = dist[v]\n\t\t\t\tmin_index = v\n\n\t\treturn min_index", "def calculate_arg_min_list(list):\n return list.index(min(list))", "def min_distance(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
runs a community detection algorithm on graph and returns a coloring of the nodes based on the found communities
def node_community_colors(graph, communities): colors = nx_helpers.generate_colors(len(communities)) def which_color(node): """finds which community node is in and returns its corresponding color """ for i, com in enumerate(communities): if node in com: ...
[ "def community_detection(net_G):\r\n if list(nx.isolates(net_G)) == []:\r\n part = community.best_partition(net_G)\r\n #values = [part.get(node) for node in net_G.nodes()]\r\n #nx.draw_spring(net_G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finds which community node is in and returns its corresponding color
def which_color(node): for i, com in enumerate(communities): if node in com: return colors[i] return nx_helpers.rgb_to_hex((0, 0, 0))
[ "def node_community_colors(graph, communities):\n colors = nx_helpers.generate_colors(len(communities))\n\n def which_color(node):\n \"\"\"finds which community node is in and returns\n its corresponding color\n \"\"\"\n for i, com in enumerate(communities):\n if node in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a list of colors for coloring nodes based on which set each node is in
def node_set_colors(nodes, spanset, gapset, preset, postset): node_colors = [] for n in nodes: if n in preset: node_colors.append(nx_helpers.rgb_to_hex((255, 0, 0))) elif n in postset: node_colors.append(nx_helpers.rgb_to_hex((255, 255, 0))) ## reads now may be m...
[ "def get_groups(nodes):\n return list(set([node.color for node in nodes]))", "def node_color(self):\n\n colors = [] # Empty colors list\n # print(self.board.content)\n for node in itertools.chain(*self.board.content): # Iterate over the board\n color = ''\n if node !=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates and returns overlap graph from .paf files
def generate_graph(params): alignedreads = read_paf(params, should_filter_paf=True) aligned = [(t, h) for t, h, _ in alignedreads] graph = nx.Graph() graph.add_edges_from(aligned) return graph
[ "def check_overlap(gfa_, path, external_file):\n if external_file:\n fasta_dict = fasta_reader(path, external_file)\n if not fasta_dict:\n return None\n\n eid_dict = dict()\n node_dict = dict()\n\n count_consistency = 0\n count_no_defined = 0\n edges_no_consistency = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes nodes from graph in they are in communities smaller than n
def drop_small_communities(graph, communities, n=4): for community in communities: if len(community) < n: nx_helpers.remove_nodes(graph, community) communities = [c for c in communities if len(c) >= n] return graph, communities
[ "def remove_node(self, n):\r\n keys = self.d.keys()\r\n #check for node in graph\r\n if n not in keys:\r\n raise KeyError(str(n) + \" is not in graph\")\r\n self.d.pop(n)\r\n #discard each occurence of node in the values of others\r\n for k in keys:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the quality of the mapping (assignment of edges) based on the "ground truth" of spanset and gapset. Sums up number of edges between spanset and gapset. Assumes undirected graph see comments
def mapping_quality(graph, spanset, gapset): the_sum = sum(sum(1 for edge in graph.edges(node) if edge[1] in gapset) for node in spanset) # if directed graph, uncomment this: #the_sum += sum(sum(1 for edge in graph.edges(node) if edge[1] in spanset) for node in gapset) return the_sum
[ "def calc_overlap_of_graphs(edges1, edges2):\n stats = statstools.calculate_overlap_scores(edges1, edges2)\n stats['interactions1'] = stats['set1_size']\n stats['interactions2'] = stats['set2_size']\n del stats['set1_size']\n del stats['set2_size']\n return stats", "def community_quality(communi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the quality of the communities based on the "ground truth" of spanset and gapset. First, determines which community corresponds to gapset and spanset. Then, returns number of wrong nodes.
def community_quality(communities, spanset, gapset): if len(communities) != 2: return -1 com_sets = [set(c) for c in communities] spanset = set(spanset) gapset = set(gapset) spanset_0 = len(com_sets[0].difference(spanset)) spanset_1 = len(com_sets[1].difference(spanset)) gapset_0 =...
[ "def mapping_quality(graph, spanset, gapset):\n the_sum = sum(sum(1 for edge in graph.edges(node) if edge[1] in gapset) for node in spanset)\n # if directed graph, uncomment this:\n #the_sum += sum(sum(1 for edge in graph.edges(node) if edge[1] in spanset) for node in gapset)\n return the_sum", "def c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a producer. Calls pykafka.topic.Topic.get_producer to create the producer Returns pykafka.producer.Producer
def create(self): topic = self.__conn__.create_topic(self.__topic__) return topic.get_producer(*self.__args__, **self.__kargs__)
[ "def init_producer():\n producer = KafkaProducer(bootstrap_servers=KAFKA_SERVER,\n api_version=KAFKA_API_VERSION,\n value_serializer=lambda v: json.dumps(v).encode('utf-8'),\n key_serializer=lambda v: json.dumps(v).encode('utf-8'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that broken __unicode__/__str__ actually raises an error.
def test_force_text_exception(self): class MyString(object): def __str__(self): return b'\xc3\xb6\xc3\xa4\xc3\xbc' __unicode__ = __str__ # str(s) raises a TypeError on python 3 if the result is not a text type. # python 2 fails when it tries converting f...
[ "def _validate_unicode(data, err=\"Input not valid unicode\"):\n try:\n if not isinstance(data, str) and not isinstance(data, str):\n raise UnicodeError(err)\n # In some cases we pass the above, but it's still inappropriate utf-8.\n str(data)\n except UnicodeError:\n rai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that force_bytes knows how to convert to bytes an exception containing nonASCII characters in its args.
def test_force_bytes_exception(self): error_msg = "This is an exception, voilà" exc = ValueError(error_msg) result = force_bytes(exc) self.assertEqual(result, error_msg.encode('utf-8'))
[ "def test_nonASCIIBytesToString(self):\n self.assertRaises(UnicodeError, nativeString, b\"\\xFF\")", "def test_py2_transaction_exception_message_bytes_implicit_encoding_non_english():\n try:\n\n # Bytes literal with non-ascii compatible characters only allowed in\n # python 2\n\n ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get response from Cloud Vision API.
def get_response_from_cv_api(data): url = 'https://vision.googleapis.com/v1/images:annotate?key={}'.format(API_KEY) response = requests.post(url=url, data=data, headers={'Content-Type': 'application/json'}) return response
[ "def get_response(image):\n encoded = base64.b64encode(image.read())\n GOOGLE_CLOUD_VISION_API_URL = 'https://vision.googleapis.com/v1/images:annotate?key='\n API_KEY = 'AIzaSyCKFsYnfYoLFeD2OHpvcjky9opfhHKFnP0'\n api_url = GOOGLE_CLOUD_VISION_API_URL + API_KEY\n header = {'Content-Type': 'application...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether a given user from the authentication server has a certain right or not.
def has_right(self, username: str, right: str) -> bool: form: str = urlencode({'username': username, 'right': right}) headers: dict = { 'Content-type': 'application/x-www-form-urlencoded' } connection: HTTPConnection = self.__get_connection() connection.request('GET',...
[ "def userHasRight(self, userName, rightName):\n\t\t\t\n\t\tuserId = self.getIdFromUserName(userName)\n\t\t\n\t\tif userId == None:\n\t\t\treturn False\n\t\t\n\t\tfor a in self.SuperAdmins:\n\t\t\ttry:\n\t\t\t\tif userId == self.users[a]:\n\t\t\t\t\treturn True\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\t\t\n\t\trigh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write data to transport.
def send_data(self, data): self._transport.write(data)
[ "def write(self, data: str) -> None:\n if self.transport is not None:\n self.transport.write(data.encode(\"utf-8\"))", "def writedata(self, data):\n if self.closed:\n return\n #self.log(\"Sending %r\" % (data,))\n try:\n self.sock.send(data)\n ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pause writing callback from transport.
def pause_writing(self): self._stream.pause_writing()
[ "def pause_writing(self):\n self._paused = True\n\n if self._sending_handle:\n self._sending_handle.cancel()\n self._sending_handle = None", "def resume_writing(self):\n self._paused = False\n self._sending_handle = self._loop.call_soon(self._try_sending)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resume writing callback from transport.
def resume_writing(self): self._stream.resume_writing()
[ "def resume_writing(self):\n self._paused = False\n self._sending_handle = self._loop.call_soon(self._try_sending)", "def resume_reading(self):\n raise NotImplementedError", "def resume_reading(self):\n self._ssl_protocol._resume_reading()", "def resume(self):\n self.log.inf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Report the member's replica set state Submit a service check. Create an event on state change.
def _report_replica_set_state(self, state, clean_server_name, replset_name, agentConfig): last_state = self._last_state_by_server.get(clean_server_name, -1) self._last_state_by_server[clean_server_name] = state if last_state != state and last_state != -1: return self.create_event(las...
[ "def query_member_status():\n notify_member_status()\n logger.info('signal sent for status report')", "def _on_update_status(self, _):\n try:\n status = self.api.status()\n logger.info(\n \"alertmanager %s is up and running (uptime: %s); \"\n \"clus...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a reasonable hostname for a replset membership event to mention.
def hostname_for_event(self, clean_server_name, agentConfig): uri = urlsplit(clean_server_name) if '@' in uri.netloc: hostname = uri.netloc.split('@')[1].split(':')[0] else: hostname = uri.netloc.split(':')[0] if hostname == 'localhost': hostname = sel...
[ "def _get_hostname(self):\n\n hostname = self.attrs(\"hostname\")\n\n if hostname:\n return hostname[0].value\n else:\n return self.entity.name", "def hostname(self) -> str:\n _args: list[Arg] = []\n _ctx = self._select(\"hostname\", _args)\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an event with a message describing the replication state of a mongo node
def create_event(self, last_state, state, clean_server_name, replset_name, agentConfig): status = self.get_state_description(state) short_status = self.get_state_name(state) last_short_status = self.get_state_name(last_state) hostname = self.hostname_for_event(clean_server_name, agentCo...
[ "def replication_status(self):\n psql = postgresql_svc.PSQL()\n try:\n query_out = psql.execute(self.replication_status_query)\n except PopenError, e:\n if 'function pg_last_xact_replay_timestamp() does not exist' in str(e):\n raise BaseException('This versi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build the metric list to collect based on the instance preferences.
def _build_metric_list_to_collect(self, additional_metrics): metrics_to_collect = {} # Defaut metrics for default_metrics in self.DEFAULT_METRICS.itervalues(): metrics_to_collect.update(default_metrics) # Additional metrics metrics for option in additional_metrics: ...
[ "def _build_metric_list_to_collect(self):\n metrics_to_collect = {}\n\n # Default metrics\n for default_metrics in itervalues(metrics.DEFAULT_METRICS):\n metrics_to_collect.update(default_metrics)\n\n # Additional metrics metrics\n for option in self._config.additional_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the submit method and the metric name to use.
def _resolve_metric(self, original_metric_name, metrics_to_collect, prefix=""): submit_method = metrics_to_collect[original_metric_name][0] \ if isinstance(metrics_to_collect[original_metric_name], tuple) \ else metrics_to_collect[original_metric_name] metric_name = metrics_to_c...
[ "def metric_name(self):\n pass", "def metric_name(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"metric_name\")", "def _RecordSubmissionMetrics(self):\n if not self._run.config.master:\n return\n\n build_id, db = self._run.GetCIDBHandle()\n if db:\n my_actions = db.GetA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace casesensitive metric name characters, normalize the metric name, prefix and suffix according to its type.
def _normalize(self, metric_name, submit_method, prefix): metric_prefix = "mongodb." if not prefix else "mongodb.{0}.".format(prefix) metric_suffix = "ps" if submit_method == RATE else "" # Replace case-sensitive metric name characters for pattern, repl in self.CASE_SENSITIVE_METRIC_NAM...
[ "def _sanitize_metric_name(self, s):\n return re.sub(\"[^\\w-]\", self.opts.replacement_char, s)", "def sanitize_metric_name(name: str) -> str:\n name = name.replace(\":\", \"-\")\n return name", "def normalize_key(metric_key):\n metric_key = SPACES.sub(\"_\", metric_key)\n metric_key = SLASH...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collect indexes statistics for all collections in the configuration. This use the "$indexStats" command.
def _collect_indexes_stats(self, instance, db, tags): for coll_name in instance.get('collections', []): try: for stats in db[coll_name].aggregate([{"$indexStats": {}}], cursor={}): idx_tags = tags + [ "name:{0}".format(stats.get('name', 'un...
[ "def get_index_stats(self):\n self.loggit.debug('Getting index stats -- BEGIN')\n self.empty_list_check()\n fields = ['size_in_bytes', 'docs', 'primary_size_in_bytes']\n # This ensures that the index state is populated\n self.get_index_state()\n # Don't populate working_lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for upload_area
def test_upload_area(self): area = areamsg query_string = [('deliveryAckEndPoint', 'https://localhost:8002')] response = self.client.open('/area', method='POST', data=area, query_string=qu...
[ "def test_multi_area(self):\n pass", "def test_upload_file(self):\n pass", "def test_upload(self):\n pass", "def test_upload_file(self):", "def test_upload_file1(self):\n pass", "def test_form_crop(self):\n\n photo_id = 1\n\n post_dict = {'crop': 'true', 'coords':...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for upload_area cleanup
def test_upload_area_cleanup(self): vis2_uvid='urn:mrn:stm:service:instance:furuno:vis2' p = Path('import') files = list(p.glob('**/urn:mrn:s124:*')) for item in files: print(item) os.remove(str(item)) pass
[ "def cleanup_from_tests(self) -> None:", "def post_cleanup(self):\n pass", "def cleanup_submission(self, submission):\n # if we are deleting files we add then we would have moved the file instead of copying it\n pass", "def tearDown(self):\n self.image.delete()", "def test_delete...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in a trajectory file and uploads it to the database
def upload_trajectory(cls, trajectory_file): # extract the attributes from the file name pitch, roll, u0 = cls.extract_pitch_roll_velocity( trajectory_file) # get or create a database object with those attributes trajectory, created = SolvedTrajectory.objects.get_or_create(...
[ "def save_trajectory(trajectory):\n query = \"INSERT INTO trajectories (idUser, startTime, endTime) VALUES (%(id_user)s, %(start_time)s, %(end_time)s)\"\n\n trajectory_data = {\n 'id_user': trajectory.id_user,\n 'start_time': trajectory.start_time,\n 'end_time': trajectory.end_time\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates through every trajectory that has been solved for and then uploads the trajectory that has been solved for
def sync_dir(self): # mark the trajectories that we have seen trajectories = os.listdir(self.trajectory_dir) for trajectory_file in trajectories: if trajectory_file not in self.seen_trajectories: created = self.upload_trajectory(trajectory_file) ...
[ "def process_trajectory(topology, trajlist, dt, step, ncores, mask1, mask2, core):\n\n input_system = mda.Universe(topology, trajlist, dt=dt)\n partial_traj = u.load_partial_traj(input_system, step, ncores, core)\n domain1 = input_system.select_atoms(mask1, updating=True)\n domain2 = input_system.select...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a list of classes and titles, parsing through 'html'
def get_classes(html): # elements = html.find_all("span", "code") # titles = html.find_all("span", "title") # classes = [] # for i in range(len(elements)): # item = elements[i] # tit = titles[i] # classes += [(item.text.replace('\xa0', ' '), tit.text.replace('\xa0', ' '))] # ...
[ "def EnrolledClasses(self,html): \n classes = []\n soup = BeautifulSoup(html)\n for element in soup.find_all(\"input\"):\n if element[\"name\"] == \"TITLE\" and element[\"value\"]:\n classes.append(element.get(\"value\"))\n return classes", "def get_tags1(self, html_class, soup):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download master cdf file from cdaweb for 'dataset'
def _download_metafile(dataset, path=None): if not path: path = sunpy.config.get('downloads', 'sample_dir') base_url = 'https://spdf.gsfc.nasa.gov/pub/software/cdawlib/0MASTERS/' fname = dataset.lower() + '_00000000_v01.cdf' url = base_url + fname try: downloaded_file = pooch.retriev...
[ "def downloadFile()-> None:\n logging.info(f\"Downloading current data set {getTime()}\")\n with open(DATA_FILE,\"wb\") as f:\n f.write(get(\"https://covid.ourworldindata.org/data/owid-covid-data.csv\").text.encode())\n logging.info(f\"Finished Downloading current data set {getTime()}\")", "def do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Downloads Wind/3DP CDF files via SunPy/Fido from CDAWeb
def wind3dp_download_fido(dataset, startdate, enddate, path=None, max_conn=5): trange = a.Time(startdate, enddate) cda_dataset = a.cdaweb.Dataset(dataset) try: result = Fido.search(trange, cda_dataset) filelist = [i[0].split('/')[-1] for i in result.show('URL')[0]] filelist.sort() ...
[ "def download_engine(fcsd): #fcsd = first comic strip date\n\n url_list = get_comic_strip_url(fcsd)\n\n for url in url_list:\n session = requests.Session()\n response = session.get(url)\n download_url = get_image_comic_url(session, response)\n# download_dilbert(session, download_ur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download a single Wind/3DP level 2 data file from SRL Berkeley to local path
def wind3dp_single_download(file, path=None): # add a OS-specific '/' to end end of 'path' if path: if not path[-1] == os.sep: path = f'{path}{os.sep}' else: path = sunpy.config.get('downloads', 'download_dir') + os.sep data = file.split('_')[1] # e.g. 'sfsp' year = fi...
[ "def download_hess_dr1_data():\n download_data_files(FILENAMES_HESS_DR1)", "def download():\r\n reader = GSODDataReader()\r\n year_list = range(2001, 2012)\r\n austin = reader.collect_data(year_list, exact_station=True,\r\n station_name='AUSTIN CAMP MABRY', state='TX', country='US')\r\n hous...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current state of the gameboard and the two player's colors. Returns np.ndarray a flat 1D representation of the gameboard appended by the two players' colors
def get_state(self): return np.append(self.game.game_board.get_board(), [self.game.player_1.color, self.game.player_2.color])[None, :]
[ "def _board_from_player_perspective(self, state, player):\n board = state #.board.encode() # apparently states returned from env.reset and env.step are the np arrays\n if player != self.env.player_color:\n tmp = board[0]\n board[0] = board[1]\n board[1] = tmp\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the possible color options that can be played. Returns list a list of the possible color options (as integers)
def get_color_options(self): mask = (self.all_colors != self.player_1.color) & (self.all_colors != self.player_2.color) return self.all_colors[mask]
[ "def get_player_colors() -> List[Tuple[float, float, float]]:\n return PLAYER_COLORS", "def supported_color_modes(self) -> set[str] | None:\n color_modes = [COLOR_MODE_ONOFF]\n if self.dp_code_bright in self.tuya_device.status:\n color_modes.append(COLOR_MODE_BRIGHTNESS)\n\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Completes a single turn by showing the gameboard, playing each of the players' turns, and printing the result. The former and latter are only done if the game type is RL.
def play_single_turn(self, action=None): self.turn_count += 1 if self.save_images_suffix: self.game_board.graphical_output(save=True, display=False, image_suffix=f'{self.save_images_suffix}_{self.turn_count}') if self.game_type == self.gam...
[ "def show_game_result(self):\n winner = \"with a DRAW\"\n if self.winner is not None:\n winner = \" \" + self.winner.get_type() + \" wins\"\n print \" _____________________________ \"\n print \"| |\"\n print \"| Game finished |\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }