_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q239700
get_entity_info
train
def get_entity_info(pdb_id): """Return pdb id information Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest Returns ------- out : dict A dictionary containing a description the entry Examples -------- >>> get_entity_inf...
python
{ "resource": "" }
q239701
get_ligands
train
def get_ligands(pdb_id): """Return ligands of given PDB ID Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest Returns ------- out : dict A dictionary containing a list of ligands associated with the entry Examples -------- ...
python
{ "resource": "" }
q239702
get_gene_onto
train
def get_gene_onto(pdb_id): """Return ligands of given PDB_ID Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest Returns ------- out : dict A dictionary containing the gene ontology information associated with the entry Examples ...
python
{ "resource": "" }
q239703
get_seq_cluster
train
def get_seq_cluster(pdb_id_chain): """Get the sequence cluster of a PDB ID plus a pdb_id plus a chain, Parameters ---------- pdb_id_chain : string A string denoting a 4 character PDB ID plus a one character chain offset with a dot: XXXX.X, as in 2F5N.A Returns ------- out...
python
{ "resource": "" }
q239704
get_pfam
train
def get_pfam(pdb_id): """Return PFAM annotations of given PDB_ID Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest Returns ------- out : dict A dictionary containing the PFAM annotations for the specified PDB ID Examples --...
python
{ "resource": "" }
q239705
get_clusters
train
def get_clusters(pdb_id): """Return cluster related web services of given PDB_ID Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest Returns ------- out : dict A dictionary containing the representative clusters for the specified PDB ...
python
{ "resource": "" }
q239706
find_results_gen
train
def find_results_gen(search_term, field='title'): ''' Return a generator of the results returned by a search of the protein data bank. This generator is used internally. Parameters ---------- search_term : str The search keyword field : str The type of information to recor...
python
{ "resource": "" }
q239707
parse_results_gen
train
def parse_results_gen(search_term, field='title', max_results = 100, sleep_time=.1): ''' Query the PDB with a search term and field while respecting the query frequency limitations of the API. Parameters ---------- search_term : str The search keyword field : str The type...
python
{ "resource": "" }
q239708
find_papers
train
def find_papers(search_term, **kwargs): ''' Return an ordered list of the top papers returned by a keyword search of the RCSB PDB Parameters ---------- search_term : str The search keyword max_results : int The maximum number of results to return Returns ------- ...
python
{ "resource": "" }
q239709
find_authors
train
def find_authors(search_term, **kwargs): '''Return an ordered list of the top authors returned by a keyword search of the RCSB PDB This function is based on the number of unique PDB entries a given author has his or her name associated with, and not author order or the ranking of the entry in the k...
python
{ "resource": "" }
q239710
list_taxa
train
def list_taxa(pdb_list, sleep_time=.1): '''Given a list of PDB IDs, look up their associated species This function digs through the search results returned by the get_all_info() function and returns any information on taxonomy included within the description. The PDB website description of each en...
python
{ "resource": "" }
q239711
list_types
train
def list_types(pdb_list, sleep_time=.1): '''Given a list of PDB IDs, look up their associated structure type Parameters ---------- pdb_list : list of str List of PDB IDs sleep_time : float Time (in seconds) to wait between requests. If this number is too small the...
python
{ "resource": "" }
q239712
remove_dupes
train
def remove_dupes(list_with_dupes): '''Remove duplicate entries from a list while preserving order This function uses Python's standard equivalence testing methods in order to determine if two elements of a list are identical. So if in the list [a,b,c] the condition a == b is True, then regardless of wh...
python
{ "resource": "" }
q239713
GoogleDriveDownloader.download_file_from_google_drive
train
def download_file_from_google_drive(file_id, dest_path, overwrite=False, unzip=False, showsize=False): """ Downloads a shared file from google drive into a given folder. Optionally unzips it. Parameters ---------- file_id: str the file identifier. ...
python
{ "resource": "" }
q239714
handle_connection
train
def handle_connection(stream): ''' Handle a connection. The server operates a request/response cycle, so it performs a synchronous loop: 1) Read data from network into wsproto 2) Get next wsproto event 3) Handle event 4) Send data from wsproto to network :param stream: a socket st...
python
{ "resource": "" }
q239715
Connection.receive_data
train
def receive_data(self, data): # type: (bytes) -> None """ Pass some received data to the connection for handling. A list of events that the remote peer triggered by sending this data can be retrieved with :meth:`~wsproto.connection.Connection.events`. :param data: The d...
python
{ "resource": "" }
q239716
Connection.events
train
def events(self): # type: () -> Generator[Event, None, None] """ Return a generator that provides any events that have been generated by protocol activity. :returns: generator of :class:`Event <wsproto.events.Event>` subclasses """ while self._events: ...
python
{ "resource": "" }
q239717
server_extensions_handshake
train
def server_extensions_handshake(requested, supported): # type: (List[str], List[Extension]) -> Optional[bytes] """Agree on the extensions to use returning an appropriate header value. This returns None if there are no agreed extensions """ accepts = {} for offer in requested: name = off...
python
{ "resource": "" }
q239718
H11Handshake.initiate_upgrade_connection
train
def initiate_upgrade_connection(self, headers, path): # type: (List[Tuple[bytes, bytes]], str) -> None """Initiate an upgrade connection. This should be used if the request has already be received and parsed. """ if self.client: raise LocalProtocolError( ...
python
{ "resource": "" }
q239719
H11Handshake.send
train
def send(self, event): # type(Event) -> bytes """Send an event to the remote. This will return the bytes to send based on the event or raise a LocalProtocolError if the event is not valid given the state. """ data = b"" if isinstance(event, Request): ...
python
{ "resource": "" }
q239720
H11Handshake.receive_data
train
def receive_data(self, data): # type: (bytes) -> None """Receive data from the remote. A list of events that the remote peer triggered by sending this data can be retrieved with :meth:`events`. """ self._h11_connection.receive_data(data) while True: ...
python
{ "resource": "" }
q239721
net_send
train
def net_send(out_data, conn): ''' Write pending data from websocket to network. ''' print('Sending {} bytes'.format(len(out_data))) conn.send(out_data)
python
{ "resource": "" }
q239722
net_recv
train
def net_recv(ws, conn): ''' Read pending data from network into websocket. ''' in_data = conn.recv(RECEIVE_BYTES) if not in_data: # A receive of zero bytes indicates the TCP socket has been closed. We # need to pass None to wsproto to update its internal state. print('Received 0 byte...
python
{ "resource": "" }
q239723
WinDivert.check_filter
train
def check_filter(filter, layer=Layer.NETWORK): """ Checks if the given packet filter string is valid with respect to the filter language. The remapped function is WinDivertHelperCheckFilter:: BOOL WinDivertHelperCheckFilter( __in const char *filter, ...
python
{ "resource": "" }
q239724
WinDivert.recv
train
def recv(self, bufsize=DEFAULT_PACKET_BUFFER_SIZE): """ Receives a diverted packet that matched the filter. The remapped function is WinDivertRecv:: BOOL WinDivertRecv( __in HANDLE handle, __out PVOID pPacket, __in UINT packetLen, ...
python
{ "resource": "" }
q239725
WinDivert.send
train
def send(self, packet, recalculate_checksum=True): """ Injects a packet into the network stack. Recalculates the checksum before sending unless recalculate_checksum=False is passed. The injected packet may be one received from recv(), or a modified version, or a completely new packet. ...
python
{ "resource": "" }
q239726
WinDivert.get_param
train
def get_param(self, name): """ Get a WinDivert parameter. See pydivert.Param for the list of parameters. The remapped function is WinDivertGetParam:: BOOL WinDivertGetParam( __in HANDLE handle, __in WINDIVERT_PARAM param, __out UINT64...
python
{ "resource": "" }
q239727
WinDivert.set_param
train
def set_param(self, name, value): """ Set a WinDivert parameter. See pydivert.Param for the list of parameters. The remapped function is DivertSetParam:: BOOL WinDivertSetParam( __in HANDLE handle, __in WINDIVERT_PARAM param, __in UIN...
python
{ "resource": "" }
q239728
_init
train
def _init(): """ Lazy-load DLL, replace proxy functions with actual ones. """ i = instance() for funcname in WINDIVERT_FUNCTIONS: func = getattr(i, funcname) func = raise_on_error(func) setattr(_module, funcname, func)
python
{ "resource": "" }
q239729
_mkprox
train
def _mkprox(funcname): """ Make lazy-init proxy function. """ def prox(*args, **kwargs): _init() return getattr(_module, funcname)(*args, **kwargs) return prox
python
{ "resource": "" }
q239730
IPHeader.src_addr
train
def src_addr(self): """ The packet source address. """ try: return socket.inet_ntop(self._af, self.raw[self._src_addr].tobytes()) except (ValueError, socket.error): pass
python
{ "resource": "" }
q239731
IPHeader.dst_addr
train
def dst_addr(self): """ The packet destination address. """ try: return socket.inet_ntop(self._af, self.raw[self._dst_addr].tobytes()) except (ValueError, socket.error): pass
python
{ "resource": "" }
q239732
Packet.icmpv4
train
def icmpv4(self): """ - An ICMPv4Header instance, if the packet is valid ICMPv4. - None, otherwise. """ ipproto, proto_start = self.protocol if ipproto == Protocol.ICMP: return ICMPv4Header(self, proto_start)
python
{ "resource": "" }
q239733
Packet.icmpv6
train
def icmpv6(self): """ - An ICMPv6Header instance, if the packet is valid ICMPv6. - None, otherwise. """ ipproto, proto_start = self.protocol if ipproto == Protocol.ICMPV6: return ICMPv6Header(self, proto_start)
python
{ "resource": "" }
q239734
Packet.tcp
train
def tcp(self): """ - An TCPHeader instance, if the packet is valid TCP. - None, otherwise. """ ipproto, proto_start = self.protocol if ipproto == Protocol.TCP: return TCPHeader(self, proto_start)
python
{ "resource": "" }
q239735
Packet.udp
train
def udp(self): """ - An TCPHeader instance, if the packet is valid UDP. - None, otherwise. """ ipproto, proto_start = self.protocol if ipproto == Protocol.UDP: return UDPHeader(self, proto_start)
python
{ "resource": "" }
q239736
Packet._payload
train
def _payload(self): """header that implements PayloadMixin""" return self.tcp or self.udp or self.icmpv4 or self.icmpv6
python
{ "resource": "" }
q239737
Packet.matches
train
def matches(self, filter, layer=Layer.NETWORK): """ Evaluates the packet against the given packet filter string. The remapped function is:: BOOL WinDivertHelperEvalFilter( __in const char *filter, __in WINDIVERT_LAYER layer, __in PVOI...
python
{ "resource": "" }
q239738
init
train
def init(project_name): """ Initialize new project at the current path. After this you can run other FloydHub commands like status and run. """ project_obj = ProjectClient().get_by_name(project_name) if not project_obj: namespace, name = get_namespace_from_name(project_name) c...
python
{ "resource": "" }
q239739
status
train
def status(id): """ View status of all jobs in a project. The command also accepts a specific job name. """ if id: try: experiment = ExperimentClient().get(normalize_job_name(id)) except FloydException: experiment = ExperimentClient().get(id) print_e...
python
{ "resource": "" }
q239740
print_experiments
train
def print_experiments(experiments): """ Prints job details in a table. Includes urls and mode parameters """ headers = ["JOB NAME", "CREATED", "STATUS", "DURATION(s)", "INSTANCE", "DESCRIPTION", "METRICS"] expt_list = [] for experiment in experiments: expt_list.append([normalize_job_name...
python
{ "resource": "" }
q239741
clone
train
def clone(id, path): """ - Download all files from a job Eg: alice/projects/mnist/1/ Note: This will download the files that were originally uploaded at the start of the job. - Download files in a specific path from a job Specify the path to a directory and download all its files and sub...
python
{ "resource": "" }
q239742
info
train
def info(job_name_or_id): """ View detailed information of a job. """ try: experiment = ExperimentClient().get(normalize_job_name(job_name_or_id)) except FloydException: experiment = ExperimentClient().get(job_name_or_id) task_instance_id = get_module_task_instance_id(experiment...
python
{ "resource": "" }
q239743
follow_logs
train
def follow_logs(instance_log_id, sleep_duration=1): """ Follow the logs until Job termination. """ cur_idx = 0 job_terminated = False while not job_terminated: # Get the logs in a loop and log the new lines log_file_contents = ResourceClient().get_content(instance_log_id) ...
python
{ "resource": "" }
q239744
logs
train
def logs(id, url, follow, sleep_duration=1): """ View the logs of a job. To follow along a job in real time, use the --follow flag """ instance_log_id = get_log_id(id) if url: log_url = "{}/api/v1/resources/{}?content=true".format( floyd.floyd_host, instance_log_id) ...
python
{ "resource": "" }
q239745
output
train
def output(id, url): """ View the files from a job. """ try: experiment = ExperimentClient().get(normalize_job_name(id)) except FloydException: experiment = ExperimentClient().get(id) output_dir_url = "%s/%s/files" % (floyd.floyd_web_host, experiment.name) if url: fl...
python
{ "resource": "" }
q239746
stop
train
def stop(id): """ Stop a running job. """ try: experiment = ExperimentClient().get(normalize_job_name(id)) except FloydException: experiment = ExperimentClient().get(id) if experiment.state not in ["queued", "queue_scheduled", "running"]: floyd_logger.info("Job in {} sta...
python
{ "resource": "" }
q239747
delete
train
def delete(names, yes): """ Delete a training job. """ failures = False for name in names: try: experiment = ExperimentClient().get(normalize_job_name(name)) except FloydException: experiment = ExperimentClient().get(name) if not experiment: ...
python
{ "resource": "" }
q239748
version
train
def version(): """ View the current version of the CLI. """ import pkg_resources version = pkg_resources.require(PROJECT_NAME)[0].version floyd_logger.info(version)
python
{ "resource": "" }
q239749
init
train
def init(dataset_name): """ Initialize a new dataset at the current dir. Then run the upload command to copy all the files in this directory to FloydHub. floyd data upload """ dataset_obj = DatasetClient().get_by_name(dataset_name) if not dataset_obj: namespace, name = get...
python
{ "resource": "" }
q239750
upload
train
def upload(resume, message): """ Upload files in the current dir to FloydHub. """ data_config = DataConfigManager.get_config() if not upload_is_resumable(data_config) or not opt_to_resume(resume): abort_previous_upload(data_config) access_token = AuthConfigManager.get_access_token()...
python
{ "resource": "" }
q239751
status
train
def status(id): """ View status of all versions in a dataset. The command also accepts a specific dataset version. """ if id: data_source = get_data_object(id, use_data_config=False) print_data([data_source] if data_source else []) else: data_sources = DataClient().get_a...
python
{ "resource": "" }
q239752
get_data_object
train
def get_data_object(data_id, use_data_config=True): """ Normalize the data_id and query the server. If that is unavailable try the raw ID """ normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config) client = DataClient() data_obj = client.get(normalized_data_...
python
{ "resource": "" }
q239753
print_data
train
def print_data(data_sources): """ Print dataset information in tabular form """ if not data_sources: return headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"] data_list = [] for data_source in data_sources: data_list.append([data_source.name, ...
python
{ "resource": "" }
q239754
clone
train
def clone(id, path): """ - Download all files in a dataset or from a Job output Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/ Using /output will download the files that are saved at the end of the job. Note: This will download the files that are sa...
python
{ "resource": "" }
q239755
listfiles
train
def listfiles(data_name): """ List files in a dataset. """ data_source = get_data_object(data_name, use_data_config=False) if not data_source: if 'output' in data_name: floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.") ...
python
{ "resource": "" }
q239756
getfile
train
def getfile(data_name, path): """ Download a specific file from a dataset. """ data_source = get_data_object(data_name, use_data_config=False) if not data_source: if 'output' in data_name: floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait f...
python
{ "resource": "" }
q239757
output
train
def output(id, url): """ View the files from a dataset. """ data_source = get_data_object(id, use_data_config=False) if not data_source: sys.exit() data_url = "%s/%s" % (floyd.floyd_web_host, data_source.name) if url: floyd_logger.info(data_url) else: floyd_logg...
python
{ "resource": "" }
q239758
delete
train
def delete(ids, yes): """ Delete datasets. """ failures = False for id in ids: data_source = get_data_object(id, use_data_config=True) if not data_source: failures = True continue data_name = normalize_data_name(data_source.name) suffix = da...
python
{ "resource": "" }
q239759
add
train
def add(source): """ Create a new dataset version from the contents of a job. This will create a new dataset version with the job output. Use the full job name: foo/projects/bar/1/code, foo/projects/bar/1/files or foo/projects/bar/1/output """ new_data = DatasetClient().add_data(source) pri...
python
{ "resource": "" }
q239760
login
train
def login(token, apikey, username, password): """ Login to FloydHub. """ if manual_login_success(token, username, password): return if not apikey: if has_browser(): apikey = wait_for_apikey() else: floyd_logger.error( "No browser found...
python
{ "resource": "" }
q239761
check_cli_version
train
def check_cli_version(): """ Check if the current cli version satisfies the server requirements """ should_exit = False server_version = VersionClient().get_cli_version() current_version = get_cli_version() if LooseVersion(current_version) < LooseVersion(server_version.min_version): ...
python
{ "resource": "" }
q239762
FloydHttpClient.request
train
def request(self, method, url, params=None, data=None, files=None, json=None, timeout=5, headers=None, skip_auth=False): """ Execute the request using requests ...
python
{ "resource": "" }
q239763
FloydHttpClient.download
train
def download(self, url, filename, relative=False, headers=None, timeout=5): """ Download the file from the given url at the current path """ request_url = self.base_url + url if relative else url floyd_logger.debug("Downloading file from url: {}".format(request_url)) # A...
python
{ "resource": "" }
q239764
FloydHttpClient.download_tar
train
def download_tar(self, url, untar=True, delete_after_untar=False, destination_dir='.'): """ Download and optionally untar the tar file from the given url """ try: floyd_logger.info("Downloading the tar file to the current directory ...") filename = self.download(u...
python
{ "resource": "" }
q239765
FloydHttpClient.check_response_status
train
def check_response_status(self, response): """ Check if response is successful. Else raise Exception. """ if not (200 <= response.status_code < 300): try: message = response.json()["errors"] except Exception: message = None ...
python
{ "resource": "" }
q239766
cli
train
def cli(verbose): """ Floyd CLI interacts with FloydHub server and executes your commands. More help is available under each command listed below. """ floyd.floyd_host = floyd.floyd_web_host = "https://dev.floydhub.com" floyd.tus_server_endpoint = "https://upload-v2-dev.floydhub.com/api/v1/uploa...
python
{ "resource": "" }
q239767
get_unignored_file_paths
train
def get_unignored_file_paths(ignore_list=None, whitelist=None): """ Given an ignore_list and a whitelist of glob patterns, returns the list of unignored file paths in the current directory and its subdirectories """ unignored_files = [] if ignore_list is None: ignore_list = [] if whi...
python
{ "resource": "" }
q239768
ignore_path
train
def ignore_path(path, ignore_list=None, whitelist=None): """ Returns a boolean indicating if a path should be ignored given an ignore_list and a whitelist of glob patterns. """ if ignore_list is None: return True should_ignore = matches_glob_list(path, ignore_list) if whitelist is N...
python
{ "resource": "" }
q239769
matches_glob_list
train
def matches_glob_list(path, glob_list): """ Given a list of glob patterns, returns a boolean indicating if a path matches any glob in the list """ for glob in glob_list: try: if PurePath(path).match(glob): return True except TypeError: pass ...
python
{ "resource": "" }
q239770
get_files_in_current_directory
train
def get_files_in_current_directory(file_type): """ Gets the list of files in the current directory and subdirectories. Respects .floydignore file if present """ local_files = [] total_file_size = 0 ignore_list, whitelist = FloydIgnoreManager.get_lists() floyd_logger.debug("Ignoring: %s...
python
{ "resource": "" }
q239771
DataCompressor.__get_nfiles_to_compress
train
def __get_nfiles_to_compress(self): """ Return the number of files to compress Note: it should take about 0.1s for counting 100k files on a dual core machine """ floyd_logger.info("Get number of files to compress... (this could take a few seconds)") paths = [self.source_...
python
{ "resource": "" }
q239772
DataCompressor.create_tarfile
train
def create_tarfile(self): """ Create a tar file with the contents of the current directory """ floyd_logger.info("Compressing data...") # Show progress bar (file_compressed/file_to_compress) self.__compression_bar = ProgressBar(expected_size=self.__files_to_compress, fill...
python
{ "resource": "" }
q239773
DataClient.create
train
def create(self, data): """ Create a temporary directory for the tar file that will be removed at the end of the operation. """ try: floyd_logger.info("Making create request to server...") post_body = data.to_dict() post_body["resumable"] = Tru...
python
{ "resource": "" }
q239774
get_command_line
train
def get_command_line(instance_type, env, message, data, mode, open_notebook, command_str): """ Return a string representing the full floyd command entered in the command line """ floyd_command = ["floyd", "run"] if instance_type: floyd_command.append('--' + INSTANCE_NAME_MAP[instance_type]) ...
python
{ "resource": "" }
q239775
restart
train
def restart(ctx, job_name, data, open_notebook, env, message, gpu, cpu, gpup, cpup, command): """ Restart a finished job as a new job. """ # Error early if more than one --env is passed. Then get the first/only # --env out of the list so all other operations work normally (they don't # expect an...
python
{ "resource": "" }
q239776
filter_user
train
def filter_user(user, using='records', interaction=None, part_of_week='allweek', part_of_day='allday'): """ Filter records of a User objects by interaction, part of week and day. Parameters ---------- user : User a bandicoot User object type : str, default 'records' ...
python
{ "resource": "" }
q239777
positions_binning
train
def positions_binning(records): """ Bin records by chunks of 30 minutes, returning the most prevalent position. If multiple positions have the same number of occurrences (during 30 minutes), we select the last one. """ def get_key(d): return (d.year, d.day, d.hour, d.minute // 30) ...
python
{ "resource": "" }
q239778
_group_range
train
def _group_range(records, method): """ Yield the range of all dates between the extrema of a list of records, separated by a given time delta. """ start_date = records[0].datetime end_date = records[-1].datetime _fun = DATE_GROUPERS[method] d = start_date # Day and week use timede...
python
{ "resource": "" }
q239779
group_records
train
def group_records(records, groupby='week'): """ Group records by year, month, week, or day. Parameters ---------- records : iterator An iterator over records groupby : Default is 'week': * 'week': group all records by year and week * None: records are not grouped. This ...
python
{ "resource": "" }
q239780
infer_type
train
def infer_type(data): """ Infer the type of objects returned by indicators. infer_type returns: - 'scalar' for a number or None, - 'summarystats' for a SummaryStats object, - 'distribution_scalar' for a list of scalars, - 'distribution_summarystats' for a list of SummaryStats objects ...
python
{ "resource": "" }
q239781
grouping
train
def grouping(f=None, interaction=['call', 'text'], summary='default', user_kwd=False): """ ``grouping`` is a decorator for indicator functions, used to simplify the source code. Parameters ---------- f : function The function to decorate user_kwd : boolean If us...
python
{ "resource": "" }
q239782
kurtosis
train
def kurtosis(data): """ Return the kurtosis for ``data``. """ if len(data) == 0: return None num = moment(data, 4) denom = moment(data, 2) ** 2. return num / denom if denom != 0 else 0
python
{ "resource": "" }
q239783
skewness
train
def skewness(data): """ Returns the skewness of ``data``. """ if len(data) == 0: return None num = moment(data, 3) denom = moment(data, 2) ** 1.5 return num / denom if denom != 0 else 0.
python
{ "resource": "" }
q239784
median
train
def median(data): """ Return the median of numeric data, unsing the "mean of middle two" method. If ``data`` is empty, ``0`` is returned. Examples -------- >>> median([1, 3, 5]) 3.0 When the number of data points is even, the median is interpolated: >>> median([1, 3, 5, 7]) 4....
python
{ "resource": "" }
q239785
entropy
train
def entropy(data): """ Compute the Shannon entropy, a measure of uncertainty. """ if len(data) == 0: return None n = sum(data) _op = lambda f: f * math.log(f) return - sum(_op(float(i) / n) for i in data)
python
{ "resource": "" }
q239786
advanced_wrap
train
def advanced_wrap(f, wrapper): """ Wrap a decorated function while keeping the same keyword arguments """ f_sig = list(inspect.getargspec(f)) wrap_sig = list(inspect.getargspec(wrapper)) # Update the keyword arguments of the wrapper if f_sig[3] is None or f_sig[3] == []: f_sig[3], f...
python
{ "resource": "" }
q239787
percent_records_missing_location
train
def percent_records_missing_location(user, method=None): """ Return the percentage of records missing a location parameter. """ if len(user.records) == 0: return 0. missing_locations = sum([1 for record in user.records if record.position._get_location(user) is None]) return float(missi...
python
{ "resource": "" }
q239788
percent_overlapping_calls
train
def percent_overlapping_calls(records, min_gab=300): """ Return the percentage of calls that overlap with the next call. Parameters ---------- records : list The records for a single user. min_gab : int Number of seconds that the calls must overlap to be considered an issue. ...
python
{ "resource": "" }
q239789
antennas_missing_locations
train
def antennas_missing_locations(user, Method=None): """ Return the number of antennas missing locations in the records of a given user. """ unique_antennas = set([record.position.antenna for record in user.records if record.position.antenna is not None]) return sum([1 for a...
python
{ "resource": "" }
q239790
bandicoot_code_signature
train
def bandicoot_code_signature(): """ Returns a unique hash of the Python source code in the current bandicoot module, using the cryptographic hash function SHA-1. """ checksum = hashlib.sha1() for root, dirs, files in os.walk(MAIN_DIRECTORY): for filename in sorted(files): if...
python
{ "resource": "" }
q239791
_AnsiColorizer.supported
train
def supported(cls, stream=sys.stdout): """ A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ if not stream.isatty(): return False # auto color only on TTYs try: ...
python
{ "resource": "" }
q239792
_AnsiColorizer.write
train
def write(self, text, color): """ Write the given text to the stream in the given color. """ color = self._colors[color] self.stream.write('\x1b[{}m{}\x1b[0m'.format(color, text))
python
{ "resource": "" }
q239793
percent_at_home
train
def percent_at_home(positions, user): """ The percentage of interactions the user had while he was at home. .. note:: The position of the home is computed using :meth:`User.recompute_home <bandicoot.core.User.recompute_home>`. If no home can be found, the percentage of interactions ...
python
{ "resource": "" }
q239794
entropy_of_antennas
train
def entropy_of_antennas(positions, normalize=False): """ The entropy of visited antennas. Parameters ---------- normalize: boolean, default is False Returns a normalized entropy between 0 and 1. """ counter = Counter(p for p in positions) raw_entropy = entropy(list(counter.value...
python
{ "resource": "" }
q239795
churn_rate
train
def churn_rate(user, summary='default', **kwargs): """ Computes the frequency spent at every towers each week, and returns the distribution of the cosine similarity between two consecutives week. .. note:: The churn rate is always computed between pairs of weeks. """ if len(user.records) == 0: ...
python
{ "resource": "" }
q239796
User.describe
train
def describe(self): """ Generates a short description of the object, and writes it to the standard output. Examples -------- >>> import bandicoot as bc >>> user = bc.User() >>> user.records = bc.tests.generate_user.random_burst(5) >>> user.describ...
python
{ "resource": "" }
q239797
User.recompute_home
train
def recompute_home(self): """ Return the antenna where the user spends most of his time at night. None is returned if there are no candidates for a home antenna """ if self.night_start < self.night_end: night_filter = lambda r: self.night_end > r.datetime.time( ...
python
{ "resource": "" }
q239798
User.set_home
train
def set_home(self, new_home): """ Sets the user's home. The argument can be a Position object or a tuple containing location data. """ if type(new_home) is Position: self.home = new_home elif type(new_home) is tuple: self.home = Position(location=...
python
{ "resource": "" }
q239799
interevent_time_recharges
train
def interevent_time_recharges(recharges): """ Return the distribution of time between consecutive recharges of the user. """ time_pairs = pairwise(r.datetime for r in recharges) times = [(new - old).total_seconds() for old, new in time_pairs] return summary_stats(times)
python
{ "resource": "" }