repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
nsfmc/swatch
swatch/writer.py
chunk_for_folder
def chunk_for_folder(obj): """produce a byte-chunk for a folder of colors the structure is very similar to a color's data: • Header b'\xC0\x01' + Big Endian Unsigned Int == len(Bytes in the Header Block) note _only_ the header, this doesn't include the length of color data ...
python
def chunk_for_folder(obj): """produce a byte-chunk for a folder of colors the structure is very similar to a color's data: • Header b'\xC0\x01' + Big Endian Unsigned Int == len(Bytes in the Header Block) note _only_ the header, this doesn't include the length of color data ...
[ "def", "chunk_for_folder", "(", "obj", ")", ":", "title", "=", "obj", "[", "'name'", "]", "+", "'\\0'", "title_length", "=", "len", "(", "title", ")", "chunk_body", "=", "struct", ".", "pack", "(", "'>H'", ",", "title_length", ")", "# title length", "chu...
produce a byte-chunk for a folder of colors the structure is very similar to a color's data: • Header b'\xC0\x01' + Big Endian Unsigned Int == len(Bytes in the Header Block) note _only_ the header, this doesn't include the length of color data • Big Endian Unsigned Short == ...
[ "produce", "a", "byte", "-", "chunk", "for", "a", "folder", "of", "colors" ]
8654edf4f1aeef37d42211ff3fe6a3e9e4325859
https://github.com/nsfmc/swatch/blob/8654edf4f1aeef37d42211ff3fe6a3e9e4325859/swatch/writer.py#L85-L121
train
produce a byte - chunk for a folder of colors
tapilab/brandelion
brandelion/cli/collect.py
iter_lines
def iter_lines(filename): """ Iterate over screen names in a file, one per line.""" with open(filename, 'rt') as idfile: for line in idfile: screen_name = line.strip() if len(screen_name) > 0: yield screen_name.split()[0]
python
def iter_lines(filename): """ Iterate over screen names in a file, one per line.""" with open(filename, 'rt') as idfile: for line in idfile: screen_name = line.strip() if len(screen_name) > 0: yield screen_name.split()[0]
[ "def", "iter_lines", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rt'", ")", "as", "idfile", ":", "for", "line", "in", "idfile", ":", "screen_name", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "screen_name", ")", ">",...
Iterate over screen names in a file, one per line.
[ "Iterate", "over", "screen", "names", "in", "a", "file", "one", "per", "line", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L47-L53
train
Iterate over screen names in a file one per line.
tapilab/brandelion
brandelion/cli/collect.py
fetch_followers
def fetch_followers(account_file, outfile, limit, do_loop): """ Fetch up to limit followers for each Twitter account in account_file. Write results to outfile file in format: screen_name user_id follower_id_1 follower_id_2 ...""" print('Fetching followers for accounts in %s' % account_file) niters ...
python
def fetch_followers(account_file, outfile, limit, do_loop): """ Fetch up to limit followers for each Twitter account in account_file. Write results to outfile file in format: screen_name user_id follower_id_1 follower_id_2 ...""" print('Fetching followers for accounts in %s' % account_file) niters ...
[ "def", "fetch_followers", "(", "account_file", ",", "outfile", ",", "limit", ",", "do_loop", ")", ":", "print", "(", "'Fetching followers for accounts in %s'", "%", "account_file", ")", "niters", "=", "1", "while", "True", ":", "outf", "=", "gzip", ".", "open"...
Fetch up to limit followers for each Twitter account in account_file. Write results to outfile file in format: screen_name user_id follower_id_1 follower_id_2 ...
[ "Fetch", "up", "to", "limit", "followers", "for", "each", "Twitter", "account", "in", "account_file", ".", "Write", "results", "to", "outfile", "file", "in", "format", ":" ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L56-L82
train
Fetch up to limit followers for each Twitter account in account_file. Write out a gzipped file of the complete list of followers.
tapilab/brandelion
brandelion/cli/collect.py
fetch_tweets
def fetch_tweets(account_file, outfile, limit): """ Fetch up to limit tweets for each account in account_file and write to outfile. """ print('fetching tweets for accounts in', account_file) outf = io.open(outfile, 'wt') for screen_name in iter_lines(account_file): print('\nFetching tweets f...
python
def fetch_tweets(account_file, outfile, limit): """ Fetch up to limit tweets for each account in account_file and write to outfile. """ print('fetching tweets for accounts in', account_file) outf = io.open(outfile, 'wt') for screen_name in iter_lines(account_file): print('\nFetching tweets f...
[ "def", "fetch_tweets", "(", "account_file", ",", "outfile", ",", "limit", ")", ":", "print", "(", "'fetching tweets for accounts in'", ",", "account_file", ")", "outf", "=", "io", ".", "open", "(", "outfile", ",", "'wt'", ")", "for", "screen_name", "in", "it...
Fetch up to limit tweets for each account in account_file and write to outfile.
[ "Fetch", "up", "to", "limit", "tweets", "for", "each", "account", "in", "account_file", "and", "write", "to", "outfile", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L85-L95
train
Fetch up to limit tweets for each account in account_file and write tooutfile.
tapilab/brandelion
brandelion/cli/collect.py
fetch_lists
def fetch_lists(keyword,max_results=20): """ Fetch the urls of up to max_results Twitter lists that match the provided keyword. >>> len(fetch_lists('politics', max_results=4)) 4 """ #CONFIG FILE READ api_key=config.get('GOOGLE_CSE_KEYS','API_KEY') cse_id=config.get('GOOGLE_CSE_KEYS','CSE...
python
def fetch_lists(keyword,max_results=20): """ Fetch the urls of up to max_results Twitter lists that match the provided keyword. >>> len(fetch_lists('politics', max_results=4)) 4 """ #CONFIG FILE READ api_key=config.get('GOOGLE_CSE_KEYS','API_KEY') cse_id=config.get('GOOGLE_CSE_KEYS','CSE...
[ "def", "fetch_lists", "(", "keyword", ",", "max_results", "=", "20", ")", ":", "#CONFIG FILE READ", "api_key", "=", "config", ".", "get", "(", "'GOOGLE_CSE_KEYS'", ",", "'API_KEY'", ")", "cse_id", "=", "config", ".", "get", "(", "'GOOGLE_CSE_KEYS'", ",", "'C...
Fetch the urls of up to max_results Twitter lists that match the provided keyword. >>> len(fetch_lists('politics', max_results=4)) 4
[ "Fetch", "the", "urls", "of", "up", "to", "max_results", "Twitter", "lists", "that", "match", "the", "provided", "keyword", ".", ">>>", "len", "(", "fetch_lists", "(", "politics", "max_results", "=", "4", "))", "4" ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L138-L158
train
Fetch the urls of up to max_results Twitter lists that match the provided keyword.
tapilab/brandelion
brandelion/cli/collect.py
fetch_list_members
def fetch_list_members(list_url): """ Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education """ match = re.match(r'.+twitter\.com\/(.+)\/lists\/(.+)', list_url) if not match: print('cannot parse list url %s' % list_url) return ...
python
def fetch_list_members(list_url): """ Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education """ match = re.match(r'.+twitter\.com\/(.+)\/lists\/(.+)', list_url) if not match: print('cannot parse list url %s' % list_url) return ...
[ "def", "fetch_list_members", "(", "list_url", ")", ":", "match", "=", "re", ".", "match", "(", "r'.+twitter\\.com\\/(.+)\\/lists\\/(.+)'", ",", "list_url", ")", "if", "not", "match", ":", "print", "(", "'cannot parse list url %s'", "%", "list_url", ")", "return", ...
Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education
[ "Get", "all", "members", "of", "the", "list", "specified", "by", "the", "given", "url", ".", "E", ".", "g", ".", "https", ":", "//", "twitter", ".", "com", "/", "lore77", "/", "lists", "/", "libri", "-", "cultura", "-", "education" ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L160-L168
train
Get all members of the list specified by the given url.
tapilab/brandelion
brandelion/cli/collect.py
fetch_exemplars
def fetch_exemplars(keyword, outfile, n=50): """ Fetch top lists matching this keyword, then return Twitter screen names along with the number of different lists on which each appers.. """ list_urls = fetch_lists(keyword, n) print('found %d lists for %s' % (len(list_urls), keyword)) counts = Counter...
python
def fetch_exemplars(keyword, outfile, n=50): """ Fetch top lists matching this keyword, then return Twitter screen names along with the number of different lists on which each appers.. """ list_urls = fetch_lists(keyword, n) print('found %d lists for %s' % (len(list_urls), keyword)) counts = Counter...
[ "def", "fetch_exemplars", "(", "keyword", ",", "outfile", ",", "n", "=", "50", ")", ":", "list_urls", "=", "fetch_lists", "(", "keyword", ",", "n", ")", "print", "(", "'found %d lists for %s'", "%", "(", "len", "(", "list_urls", ")", ",", "keyword", ")",...
Fetch top lists matching this keyword, then return Twitter screen names along with the number of different lists on which each appers..
[ "Fetch", "top", "lists", "matching", "this", "keyword", "then", "return", "Twitter", "screen", "names", "along", "with", "the", "number", "of", "different", "lists", "on", "which", "each", "appers", ".." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L171-L184
train
Fetch all exemplars matching this keyword then return Twitter screen names along with the number of different lists on which each appers are.
tamasgal/km3pipe
km3pipe/io/ch.py
CHPump._init_controlhost
def _init_controlhost(self): """Set up the controlhost connection""" log.debug("Connecting to JLigier") self.client = Client(self.host, self.port) self.client._connect() log.debug("Subscribing to tags: {0}".format(self.tags)) for tag in self.tags.split(','): s...
python
def _init_controlhost(self): """Set up the controlhost connection""" log.debug("Connecting to JLigier") self.client = Client(self.host, self.port) self.client._connect() log.debug("Subscribing to tags: {0}".format(self.tags)) for tag in self.tags.split(','): s...
[ "def", "_init_controlhost", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Connecting to JLigier\"", ")", "self", ".", "client", "=", "Client", "(", "self", ".", "host", ",", "self", ".", "port", ")", "self", ".", "client", ".", "_connect", "(", "...
Set up the controlhost connection
[ "Set", "up", "the", "controlhost", "connection" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/ch.py#L88-L96
train
Initialize the controlhost connection
tamasgal/km3pipe
km3pipe/io/ch.py
CHPump.process
def process(self, blob): """Wait for the next packet and put it in the blob""" # self._add_process_dt() try: log.debug("Waiting for queue items.") prefix, data = self.queue.get(timeout=self.timeout) log.debug("Got {0} bytes from queue.".format(len(data))) ...
python
def process(self, blob): """Wait for the next packet and put it in the blob""" # self._add_process_dt() try: log.debug("Waiting for queue items.") prefix, data = self.queue.get(timeout=self.timeout) log.debug("Got {0} bytes from queue.".format(len(data))) ...
[ "def", "process", "(", "self", ",", "blob", ")", ":", "# self._add_process_dt()", "try", ":", "log", ".", "debug", "(", "\"Waiting for queue items.\"", ")", "prefix", ",", "data", "=", "self", ".", "queue", ".", "get", "(", "timeout", "=", "self", ".", "...
Wait for the next packet and put it in the blob
[ "Wait", "for", "the", "next", "packet", "and", "put", "it", "in", "the", "blob" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/ch.py#L140-L154
train
Wait for next packet and put it in the blob.
tamasgal/km3pipe
km3pipe/io/ch.py
CHPump.finish
def finish(self): """Clean up the JLigier controlhost connection""" log.debug("Disconnecting from JLigier.") self.client.socket.shutdown(socket.SHUT_RDWR) self.client._disconnect()
python
def finish(self): """Clean up the JLigier controlhost connection""" log.debug("Disconnecting from JLigier.") self.client.socket.shutdown(socket.SHUT_RDWR) self.client._disconnect()
[ "def", "finish", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Disconnecting from JLigier.\"", ")", "self", ".", "client", ".", "socket", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "self", ".", "client", ".", "_disconnect", "(", ")" ]
Clean up the JLigier controlhost connection
[ "Clean", "up", "the", "JLigier", "controlhost", "connection" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/ch.py#L176-L180
train
Clean up the JLigier controlhost connection
lexibank/pylexibank
src/pylexibank/dataset.py
Dataset.tokenizer
def tokenizer(self): """ Datasets can provide support for segmentation (aka tokenization) in two ways: - by providing an orthography profile at etc/orthography.tsv or - by overwriting this method to return a custom tokenizer callable. :return: A callable to do segmentation. ...
python
def tokenizer(self): """ Datasets can provide support for segmentation (aka tokenization) in two ways: - by providing an orthography profile at etc/orthography.tsv or - by overwriting this method to return a custom tokenizer callable. :return: A callable to do segmentation. ...
[ "def", "tokenizer", "(", "self", ")", ":", "profile", "=", "self", ".", "dir", "/", "'etc'", "/", "'orthography.tsv'", "if", "profile", ".", "exists", "(", ")", ":", "profile", "=", "Profile", ".", "from_file", "(", "str", "(", "profile", ")", ",", "...
Datasets can provide support for segmentation (aka tokenization) in two ways: - by providing an orthography profile at etc/orthography.tsv or - by overwriting this method to return a custom tokenizer callable. :return: A callable to do segmentation. The expected signature of the callab...
[ "Datasets", "can", "provide", "support", "for", "segmentation", "(", "aka", "tokenization", ")", "in", "two", "ways", ":", "-", "by", "providing", "an", "orthography", "profile", "at", "etc", "/", "orthography", ".", "tsv", "or", "-", "by", "overwriting", ...
c28e7f122f20de1232623dd7003cb5b01535e581
https://github.com/lexibank/pylexibank/blob/c28e7f122f20de1232623dd7003cb5b01535e581/src/pylexibank/dataset.py#L316-L348
train
A custom tokenizer for segmentation.
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads.list_variables
def list_variables(self): """ List available variables and applies any filters. """ station_codes = self._get_station_codes() station_codes = self._apply_features_filter(station_codes) variables = self._list_variables(station_codes) if hasattr(self, "_variables")...
python
def list_variables(self): """ List available variables and applies any filters. """ station_codes = self._get_station_codes() station_codes = self._apply_features_filter(station_codes) variables = self._list_variables(station_codes) if hasattr(self, "_variables")...
[ "def", "list_variables", "(", "self", ")", ":", "station_codes", "=", "self", ".", "_get_station_codes", "(", ")", "station_codes", "=", "self", ".", "_apply_features_filter", "(", "station_codes", ")", "variables", "=", "self", ".", "_list_variables", "(", "sta...
List available variables and applies any filters.
[ "List", "available", "variables", "and", "applies", "any", "filters", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L50-L61
train
List available variables and applies any filters.
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads._list_variables
def _list_variables(self, station_codes): """ Internal helper to list the variables for the given station codes. """ # sample output from obs retrieval: # # DD9452D0 # HP(SRBM5) # 2013-07-22 19:30 45.97 # HT(SRBM5) # ...
python
def _list_variables(self, station_codes): """ Internal helper to list the variables for the given station codes. """ # sample output from obs retrieval: # # DD9452D0 # HP(SRBM5) # 2013-07-22 19:30 45.97 # HT(SRBM5) # ...
[ "def", "_list_variables", "(", "self", ",", "station_codes", ")", ":", "# sample output from obs retrieval:", "#", "# DD9452D0", "# HP(SRBM5)", "# 2013-07-22 19:30 45.97", "# HT(SRBM5)", "# 2013-07-22 19:30 44.29", "# PC(SRBM5)", "# 2013-07-22 19:3...
Internal helper to list the variables for the given station codes.
[ "Internal", "helper", "to", "list", "the", "variables", "for", "the", "given", "station", "codes", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L63-L93
train
Internal helper to list the variables for the given station codes.
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads.raw
def raw(self, format=None, **kwargs): """ Returns a tuple of (metadata, raw data) """ station_codes = self._apply_features_filter(self._get_station_codes()) metadata = self._get_metadata(station_codes, **kwargs) raw_data = self._get_raw_data(station_codes, **kwargs) ...
python
def raw(self, format=None, **kwargs): """ Returns a tuple of (metadata, raw data) """ station_codes = self._apply_features_filter(self._get_station_codes()) metadata = self._get_metadata(station_codes, **kwargs) raw_data = self._get_raw_data(station_codes, **kwargs) ...
[ "def", "raw", "(", "self", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "station_codes", "=", "self", ".", "_apply_features_filter", "(", "self", ".", "_get_station_codes", "(", ")", ")", "metadata", "=", "self", ".", "_get_metadata", "...
Returns a tuple of (metadata, raw data)
[ "Returns", "a", "tuple", "of", "(", "metadata", "raw", "data", ")" ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L114-L122
train
Returns a tuple of metadata and raw data for the current locale.
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads._apply_features_filter
def _apply_features_filter(self, station_codes): """ If the features filter is set, this will return the intersection of those filter items and the given station codes. """ # apply features filter if hasattr(self, "features") and self.features is not None: sta...
python
def _apply_features_filter(self, station_codes): """ If the features filter is set, this will return the intersection of those filter items and the given station codes. """ # apply features filter if hasattr(self, "features") and self.features is not None: sta...
[ "def", "_apply_features_filter", "(", "self", ",", "station_codes", ")", ":", "# apply features filter", "if", "hasattr", "(", "self", ",", "\"features\"", ")", "and", "self", ".", "features", "is", "not", "None", ":", "station_codes", "=", "set", "(", "statio...
If the features filter is set, this will return the intersection of those filter items and the given station codes.
[ "If", "the", "features", "filter", "is", "set", "this", "will", "return", "the", "intersection", "of", "those", "filter", "items", "and", "the", "given", "station", "codes", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L124-L136
train
This will return the intersection of the station codes and the given station codes.
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads._get_station_codes
def _get_station_codes(self, force=False): """ Gets and caches a list of station codes optionally within a bbox. Will return the cached version if it exists unless force is True. """ if not force and self.station_codes is not None: return self.station_codes ...
python
def _get_station_codes(self, force=False): """ Gets and caches a list of station codes optionally within a bbox. Will return the cached version if it exists unless force is True. """ if not force and self.station_codes is not None: return self.station_codes ...
[ "def", "_get_station_codes", "(", "self", ",", "force", "=", "False", ")", ":", "if", "not", "force", "and", "self", ".", "station_codes", "is", "not", "None", ":", "return", "self", ".", "station_codes", "state_urls", "=", "self", ".", "_get_state_urls", ...
Gets and caches a list of station codes optionally within a bbox. Will return the cached version if it exists unless force is True.
[ "Gets", "and", "caches", "a", "list", "of", "station", "codes", "optionally", "within", "a", "bbox", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L158-L216
train
Gets and caches a list of station codes optionally within a bounding box.
SentimensRG/txCelery
txcelery/defer.py
DeferredTask._monitor_task
def _monitor_task(self): """Wrapper that handles the actual asynchronous monitoring of the task state. """ if self.task.state in states.UNREADY_STATES: reactor.callLater(self.POLL_PERIOD, self._monitor_task) return if self.task.state == 'SUCCESS': ...
python
def _monitor_task(self): """Wrapper that handles the actual asynchronous monitoring of the task state. """ if self.task.state in states.UNREADY_STATES: reactor.callLater(self.POLL_PERIOD, self._monitor_task) return if self.task.state == 'SUCCESS': ...
[ "def", "_monitor_task", "(", "self", ")", ":", "if", "self", ".", "task", ".", "state", "in", "states", ".", "UNREADY_STATES", ":", "reactor", ".", "callLater", "(", "self", ".", "POLL_PERIOD", ",", "self", ".", "_monitor_task", ")", "return", "if", "sel...
Wrapper that handles the actual asynchronous monitoring of the task state.
[ "Wrapper", "that", "handles", "the", "actual", "asynchronous", "monitoring", "of", "the", "task", "state", "." ]
15b9705198009f5ce6db1bfd0a8af9b8949d6277
https://github.com/SentimensRG/txCelery/blob/15b9705198009f5ce6db1bfd0a8af9b8949d6277/txcelery/defer.py#L52-L71
train
Wrapper that handles the actual asynchronous monitoring of the task.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
_clean_query_string
def _clean_query_string(q): """Clean up a query string for searching. Removes unmatched parentheses and joining operators. Arguments: q (str): Query string to be cleaned Returns: str: The clean query string. """ q = q.replace("()", "").strip() if q.endswith("("): q...
python
def _clean_query_string(q): """Clean up a query string for searching. Removes unmatched parentheses and joining operators. Arguments: q (str): Query string to be cleaned Returns: str: The clean query string. """ q = q.replace("()", "").strip() if q.endswith("("): q...
[ "def", "_clean_query_string", "(", "q", ")", ":", "q", "=", "q", ".", "replace", "(", "\"()\"", ",", "\"\"", ")", ".", "strip", "(", ")", "if", "q", ".", "endswith", "(", "\"(\"", ")", ":", "q", "=", "q", "[", ":", "-", "1", "]", ".", "strip"...
Clean up a query string for searching. Removes unmatched parentheses and joining operators. Arguments: q (str): Query string to be cleaned Returns: str: The clean query string.
[ "Clean", "up", "a", "query", "string", "for", "searching", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L40-L66
train
Clean up a query string for searching.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
_validate_query
def _validate_query(query): """Validate and clean up a query to be sent to Search. Cleans the query string, removes unneeded parameters, and validates for correctness. Does not modify the original argument. Raises an Exception on invalid input. Arguments: query (dict): The query to validate...
python
def _validate_query(query): """Validate and clean up a query to be sent to Search. Cleans the query string, removes unneeded parameters, and validates for correctness. Does not modify the original argument. Raises an Exception on invalid input. Arguments: query (dict): The query to validate...
[ "def", "_validate_query", "(", "query", ")", ":", "query", "=", "deepcopy", "(", "query", ")", "# q is always required", "if", "query", "[", "\"q\"", "]", "==", "BLANK_QUERY", "[", "\"q\"", "]", ":", "raise", "ValueError", "(", "\"No query specified.\"", ")", ...
Validate and clean up a query to be sent to Search. Cleans the query string, removes unneeded parameters, and validates for correctness. Does not modify the original argument. Raises an Exception on invalid input. Arguments: query (dict): The query to validate. Returns: dict: The v...
[ "Validate", "and", "clean", "up", "a", "query", "to", "be", "sent", "to", "Search", ".", "Cleans", "the", "query", "string", "removes", "unneeded", "parameters", "and", "validates", "for", "correctness", ".", "Does", "not", "modify", "the", "original", "argu...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L69-L107
train
Validate and clean up a query string.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._term
def _term(self, term): """Add a term to the query. Arguments: term (str): The term to add. Returns: SearchHelper: Self """ # All terms must be strings for Elasticsearch term = str(term) if term: self.__query["q"] += term ...
python
def _term(self, term): """Add a term to the query. Arguments: term (str): The term to add. Returns: SearchHelper: Self """ # All terms must be strings for Elasticsearch term = str(term) if term: self.__query["q"] += term ...
[ "def", "_term", "(", "self", ",", "term", ")", ":", "# All terms must be strings for Elasticsearch", "term", "=", "str", "(", "term", ")", "if", "term", ":", "self", ".", "__query", "[", "\"q\"", "]", "+=", "term", "return", "self" ]
Add a term to the query. Arguments: term (str): The term to add. Returns: SearchHelper: Self
[ "Add", "a", "term", "to", "the", "query", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L197-L210
train
Add a term to the query.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._field
def _field(self, field, value): """Add a ``field:value`` term to the query. Matches will have the ``value`` in the ``field``. Note: This method triggers advanced mode. Arguments: field (str): The field to check for the value, in Elasticsearch dot syntax. ...
python
def _field(self, field, value): """Add a ``field:value`` term to the query. Matches will have the ``value`` in the ``field``. Note: This method triggers advanced mode. Arguments: field (str): The field to check for the value, in Elasticsearch dot syntax. ...
[ "def", "_field", "(", "self", ",", "field", ",", "value", ")", ":", "# Fields and values must be strings for Elasticsearch", "field", "=", "str", "(", "field", ")", "value", "=", "str", "(", "value", ")", "# Check if quotes required and allowed, and quotes not present",...
Add a ``field:value`` term to the query. Matches will have the ``value`` in the ``field``. Note: This method triggers advanced mode. Arguments: field (str): The field to check for the value, in Elasticsearch dot syntax. value (str): The value to match. ...
[ "Add", "a", "field", ":", "value", "term", "to", "the", "query", ".", "Matches", "will", "have", "the", "value", "in", "the", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L212-L242
train
Add a field value term to the query.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._operator
def _operator(self, op, close_group=False): """Add an operator between terms. There must be a term added before using this method. All operators have helpers, so this method is usually not necessary to directly invoke. Arguments: op (str): The operator to add. Must be in the...
python
def _operator(self, op, close_group=False): """Add an operator between terms. There must be a term added before using this method. All operators have helpers, so this method is usually not necessary to directly invoke. Arguments: op (str): The operator to add. Must be in the...
[ "def", "_operator", "(", "self", ",", "op", ",", "close_group", "=", "False", ")", ":", "op", "=", "op", ".", "upper", "(", ")", ".", "strip", "(", ")", "if", "op", "not", "in", "OP_LIST", ":", "raise", "ValueError", "(", "\"Error: '{}' is not a valid ...
Add an operator between terms. There must be a term added before using this method. All operators have helpers, so this method is usually not necessary to directly invoke. Arguments: op (str): The operator to add. Must be in the OP_LIST. close_group (bool): If ``True``, ...
[ "Add", "an", "operator", "between", "terms", ".", "There", "must", "be", "a", "term", "added", "before", "using", "this", "method", ".", "All", "operators", "have", "helpers", "so", "this", "method", "is", "usually", "not", "necessary", "to", "directly", "...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L244-L271
train
Add an operator between terms.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._and_join
def _and_join(self, close_group=False): """Combine terms with AND. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. ...
python
def _and_join(self, close_group=False): """Combine terms with AND. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. ...
[ "def", "_and_join", "(", "self", ",", "close_group", "=", "False", ")", ":", "if", "not", "self", ".", "initialized", ":", "raise", "ValueError", "(", "\"You must add a search term before adding an operator.\"", ")", "else", ":", "self", ".", "_operator", "(", "...
Combine terms with AND. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. Example:: If ...
[ "Combine", "terms", "with", "AND", ".", "There", "must", "be", "a", "term", "added", "before", "using", "this", "method", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L273-L294
train
Combine terms with AND.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._or_join
def _or_join(self, close_group=False): """Combine terms with OR. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. ...
python
def _or_join(self, close_group=False): """Combine terms with OR. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. ...
[ "def", "_or_join", "(", "self", ",", "close_group", "=", "False", ")", ":", "if", "not", "self", ".", "initialized", ":", "raise", "ValueError", "(", "\"You must add a search term before adding an operator.\"", ")", "else", ":", "self", ".", "_operator", "(", "\...
Combine terms with OR. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. Example: If th...
[ "Combine", "terms", "with", "OR", ".", "There", "must", "be", "a", "term", "added", "before", "using", "this", "method", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L296-L317
train
Combine terms with OR.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._add_sort
def _add_sort(self, field, ascending=True): """Sort the search results by a certain field. If this method is called multiple times, the later sort fields are given lower priority, and will only be considered when the eariler fields have the same value. Arguments: field (str...
python
def _add_sort(self, field, ascending=True): """Sort the search results by a certain field. If this method is called multiple times, the later sort fields are given lower priority, and will only be considered when the eariler fields have the same value. Arguments: field (str...
[ "def", "_add_sort", "(", "self", ",", "field", ",", "ascending", "=", "True", ")", ":", "# Fields must be strings for Elasticsearch", "field", "=", "str", "(", "field", ")", "# No-op on blank sort field", "if", "field", ":", "self", ".", "__query", "[", "\"sort\...
Sort the search results by a certain field. If this method is called multiple times, the later sort fields are given lower priority, and will only be considered when the eariler fields have the same value. Arguments: field (str): The field to sort by, in Elasticsearch dot syntax. ...
[ "Sort", "the", "search", "results", "by", "a", "certain", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L328-L349
train
Add a sort to the search results.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._ex_search
def _ex_search(self, limit=None, info=False, retries=3): """Execute a search and return the results, up to the ``SEARCH_LIMIT``. Uses the query currently in this SearchHelper. Arguments: limit (int): Maximum number of entries to return. **Default**: ``10`` for basic ...
python
def _ex_search(self, limit=None, info=False, retries=3): """Execute a search and return the results, up to the ``SEARCH_LIMIT``. Uses the query currently in this SearchHelper. Arguments: limit (int): Maximum number of entries to return. **Default**: ``10`` for basic ...
[ "def", "_ex_search", "(", "self", ",", "limit", "=", "None", ",", "info", "=", "False", ",", "retries", "=", "3", ")", ":", "# Make sure there is query information present", "if", "not", "self", ".", "initialized", ":", "raise", "ValueError", "(", "'No query h...
Execute a search and return the results, up to the ``SEARCH_LIMIT``. Uses the query currently in this SearchHelper. Arguments: limit (int): Maximum number of entries to return. **Default**: ``10`` for basic queries, and ``10000`` for advanced. info (bool): If ``...
[ "Execute", "a", "search", "and", "return", "the", "results", "up", "to", "the", "SEARCH_LIMIT", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L351-L416
train
Execute a search and return the results.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._mapping
def _mapping(self): """Fetch the entire mapping for the specified index. Returns: dict: The full mapping for the index. """ return (self.__search_client.get( "/unstable/index/{}/mapping".format(mdf_toolbox.translate_index(self.index))) ["m...
python
def _mapping(self): """Fetch the entire mapping for the specified index. Returns: dict: The full mapping for the index. """ return (self.__search_client.get( "/unstable/index/{}/mapping".format(mdf_toolbox.translate_index(self.index))) ["m...
[ "def", "_mapping", "(", "self", ")", ":", "return", "(", "self", ".", "__search_client", ".", "get", "(", "\"/unstable/index/{}/mapping\"", ".", "format", "(", "mdf_toolbox", ".", "translate_index", "(", "self", ".", "index", ")", ")", ")", "[", "\"mappings\...
Fetch the entire mapping for the specified index. Returns: dict: The full mapping for the index.
[ "Fetch", "the", "entire", "mapping", "for", "the", "specified", "index", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L418-L426
train
Fetch the entire mapping for the specified index.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.match_term
def match_term(self, value, required=True, new_group=False): """Add a fulltext search term to the query. Warning: Do not use this method with any other query-building helpers. This method is only for building fulltext queries (in non-advanced mode). Using other helpe...
python
def match_term(self, value, required=True, new_group=False): """Add a fulltext search term to the query. Warning: Do not use this method with any other query-building helpers. This method is only for building fulltext queries (in non-advanced mode). Using other helpe...
[ "def", "match_term", "(", "self", ",", "value", ",", "required", "=", "True", ",", "new_group", "=", "False", ")", ":", "# If not the start of the query string, add an AND or OR", "if", "self", ".", "initialized", ":", "if", "required", ":", "self", ".", "_and_j...
Add a fulltext search term to the query. Warning: Do not use this method with any other query-building helpers. This method is only for building fulltext queries (in non-advanced mode). Using other helpers, such as ``match_field()``, will cause the query to run in advanced m...
[ "Add", "a", "fulltext", "search", "term", "to", "the", "query", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L435-L463
train
Add a fulltext search term to the query.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.match_field
def match_field(self, field, value, required=True, new_group=False): """Add a ``field:value`` term to the query. Matches will have the ``value`` in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to ...
python
def match_field(self, field, value, required=True, new_group=False): """Add a ``field:value`` term to the query. Matches will have the ``value`` in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to ...
[ "def", "match_field", "(", "self", ",", "field", ",", "value", ",", "required", "=", "True", ",", "new_group", "=", "False", ")", ":", "# If not the start of the query string, add an AND or OR", "if", "self", ".", "initialized", ":", "if", "required", ":", "self...
Add a ``field:value`` term to the query. Matches will have the ``value`` in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to Elasticsearch rules using the dot syntax. ...
[ "Add", "a", "field", ":", "value", "term", "to", "the", "query", ".", "Matches", "will", "have", "the", "value", "in", "the", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L465-L492
train
Add a field : value term to the query.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.exclude_field
def exclude_field(self, field, value, new_group=False): """Exclude a ``field:value`` term from the query. Matches will NOT have the ``value`` in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to Ela...
python
def exclude_field(self, field, value, new_group=False): """Exclude a ``field:value`` term from the query. Matches will NOT have the ``value`` in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to Ela...
[ "def", "exclude_field", "(", "self", ",", "field", ",", "value", ",", "new_group", "=", "False", ")", ":", "# No-op on missing arguments", "if", "not", "field", "and", "not", "value", ":", "return", "self", "# If not the start of the query string, add an AND", "# OR...
Exclude a ``field:value`` term from the query. Matches will NOT have the ``value`` in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to Elasticsearch rules using the dot syntax. ...
[ "Exclude", "a", "field", ":", "value", "term", "from", "the", "query", ".", "Matches", "will", "NOT", "have", "the", "value", "in", "the", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L494-L520
train
Exclude a field value term from the query.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.match_exists
def match_exists(self, field, required=True, new_group=False): """Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
python
def match_exists(self, field, required=True, new_group=False): """Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
[ "def", "match_exists", "(", "self", ",", "field", ",", "required", "=", "True", ",", "new_group", "=", "False", ")", ":", "return", "self", ".", "match_field", "(", "field", ",", "\"*\"", ",", "required", "=", "required", ",", "new_group", "=", "new_grou...
Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules using the dot syntax. For example, ``"mdf...
[ "Require", "a", "field", "to", "exist", "in", "the", "results", ".", "Matches", "will", "have", "some", "value", "in", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L522-L541
train
Returns True if a field exists in the results.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.match_not_exists
def match_not_exists(self, field, new_group=False): """Require a field to not exist in the results. Matches will not have ``field`` present. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
python
def match_not_exists(self, field, new_group=False): """Require a field to not exist in the results. Matches will not have ``field`` present. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
[ "def", "match_not_exists", "(", "self", ",", "field", ",", "new_group", "=", "False", ")", ":", "return", "self", ".", "exclude_field", "(", "field", ",", "\"*\"", ",", "new_group", "=", "new_group", ")" ]
Require a field to not exist in the results. Matches will not have ``field`` present. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules using the dot syntax. For example, ``"m...
[ "Require", "a", "field", "to", "not", "exist", "in", "the", "results", ".", "Matches", "will", "not", "have", "field", "present", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L543-L560
train
Require a field to not exist in the results. Matches will not have field present.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.match_range
def match_range(self, field, start=None, stop=None, inclusive=True, required=True, new_group=False): """Add a ``field:[some range]`` term to the query. Matches will have a ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the...
python
def match_range(self, field, start=None, stop=None, inclusive=True, required=True, new_group=False): """Add a ``field:[some range]`` term to the query. Matches will have a ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the...
[ "def", "match_range", "(", "self", ",", "field", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "inclusive", "=", "True", ",", "required", "=", "True", ",", "new_group", "=", "False", ")", ":", "# Accept None as *", "if", "start", "is", "Non...
Add a ``field:[some range]`` term to the query. Matches will have a ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to Elasticsearch rules using the dot syntax. ...
[ "Add", "a", "field", ":", "[", "some", "range", "]", "term", "to", "the", "query", ".", "Matches", "will", "have", "a", "value", "in", "the", "range", "in", "the", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L562-L604
train
This method will add a term to the query that matches a value in a range of values.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.exclude_range
def exclude_range(self, field, start="*", stop="*", inclusive=True, new_group=False): """Exclude a ``field:[some range]`` term from the query. Matches will not have any ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the value. ...
python
def exclude_range(self, field, start="*", stop="*", inclusive=True, new_group=False): """Exclude a ``field:[some range]`` term from the query. Matches will not have any ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the value. ...
[ "def", "exclude_range", "(", "self", ",", "field", ",", "start", "=", "\"*\"", ",", "stop", "=", "\"*\"", ",", "inclusive", "=", "True", ",", "new_group", "=", "False", ")", ":", "# Accept None as *", "if", "start", "is", "None", ":", "start", "=", "\"...
Exclude a ``field:[some range]`` term from the query. Matches will not have any ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to Elasticsearch rules using the ...
[ "Exclude", "a", "field", ":", "[", "some", "range", "]", "term", "from", "the", "query", ".", "Matches", "will", "not", "have", "any", "value", "in", "the", "range", "in", "the", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L606-L645
train
Exclude a field from the search.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.exclusive_match
def exclusive_match(self, field, value): """Match exactly the given value(s), with no other data in the field. Arguments: field (str): The field to check for the value. The field must be namespaced according to Elasticsearch rules using the dot syntax...
python
def exclusive_match(self, field, value): """Match exactly the given value(s), with no other data in the field. Arguments: field (str): The field to check for the value. The field must be namespaced according to Elasticsearch rules using the dot syntax...
[ "def", "exclusive_match", "(", "self", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "[", "value", "]", "# Hacky way to get ES to do exclusive search", "# Essentially have a big range search that matches NO...
Match exactly the given value(s), with no other data in the field. Arguments: field (str): The field to check for the value. The field must be namespaced according to Elasticsearch rules using the dot syntax. For example, ``"mdf.source_nam...
[ "Match", "exactly", "the", "given", "value", "(", "s", ")", "with", "no", "other", "data", "in", "the", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L647-L684
train
Match exactly the given value with no other data in the field.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.add_sort
def add_sort(self, field, ascending=True): """Sort the search results by a certain field. If this method is called multiple times, the later sort fields are given lower priority, and will only be considered when the eariler fields have the same value. Arguments: field (str)...
python
def add_sort(self, field, ascending=True): """Sort the search results by a certain field. If this method is called multiple times, the later sort fields are given lower priority, and will only be considered when the eariler fields have the same value. Arguments: field (str)...
[ "def", "add_sort", "(", "self", ",", "field", ",", "ascending", "=", "True", ")", ":", "# No-op on blank field", "if", "not", "field", ":", "return", "self", "self", ".", "_add_sort", "(", "field", ",", "ascending", "=", "ascending", ")", "return", "self" ...
Sort the search results by a certain field. If this method is called multiple times, the later sort fields are given lower priority, and will only be considered when the eariler fields have the same value. Arguments: field (str): The field to sort by. The field ...
[ "Sort", "the", "search", "results", "by", "a", "certain", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L686-L708
train
Sort the search results by a certain field.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.search
def search(self, q=None, advanced=False, limit=None, info=False, reset_query=True): """Execute a search and return the results, up to the ``SEARCH_LIMIT``. Arguments: q (str): The query to execute. **Default:** The current helper-formed query, if any. There must be some ...
python
def search(self, q=None, advanced=False, limit=None, info=False, reset_query=True): """Execute a search and return the results, up to the ``SEARCH_LIMIT``. Arguments: q (str): The query to execute. **Default:** The current helper-formed query, if any. There must be some ...
[ "def", "search", "(", "self", ",", "q", "=", "None", ",", "advanced", "=", "False", ",", "limit", "=", "None", ",", "info", "=", "False", ",", "reset_query", "=", "True", ")", ":", "# If q not specified, use internal, helper-built query", "if", "q", "is", ...
Execute a search and return the results, up to the ``SEARCH_LIMIT``. Arguments: q (str): The query to execute. **Default:** The current helper-formed query, if any. There must be some query to execute. advanced (bool): Whether to treat ``q`` as a basic or advanced qu...
[ "Execute", "a", "search", "and", "return", "the", "results", "up", "to", "the", "SEARCH_LIMIT", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L714-L758
train
Execute a search and return the results.
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.show_fields
def show_fields(self, block=None): """Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the ...
python
def show_fields(self, block=None): """Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the ...
[ "def", "show_fields", "(", "self", ",", "block", "=", "None", ")", ":", "mapping", "=", "self", ".", "_mapping", "(", ")", "if", "block", "is", "None", ":", "return", "mapping", "elif", "block", "==", "\"top\"", ":", "blocks", "=", "set", "(", ")", ...
Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the top-level fields. ...
[ "Retrieve", "and", "return", "the", "mapping", "for", "the", "given", "metadata", "block", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L764-L792
train
Retrieve and return the mapping for the given metadata block.
tamasgal/km3pipe
km3pipe/dataclasses.py
inflate_dtype
def inflate_dtype(arr, names): """Create structured dtype from a 2d ndarray with unstructured dtype.""" arr = np.asanyarray(arr) if has_structured_dt(arr): return arr.dtype s_dt = arr.dtype dt = [(n, s_dt) for n in names] dt = np.dtype(dt) return dt
python
def inflate_dtype(arr, names): """Create structured dtype from a 2d ndarray with unstructured dtype.""" arr = np.asanyarray(arr) if has_structured_dt(arr): return arr.dtype s_dt = arr.dtype dt = [(n, s_dt) for n in names] dt = np.dtype(dt) return dt
[ "def", "inflate_dtype", "(", "arr", ",", "names", ")", ":", "arr", "=", "np", ".", "asanyarray", "(", "arr", ")", "if", "has_structured_dt", "(", "arr", ")", ":", "return", "arr", ".", "dtype", "s_dt", "=", "arr", ".", "dtype", "dt", "=", "[", "(",...
Create structured dtype from a 2d ndarray with unstructured dtype.
[ "Create", "structured", "dtype", "from", "a", "2d", "ndarray", "with", "unstructured", "dtype", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L48-L56
train
Create structured dtype from a 2d ndarray with unstructured dtype.
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.from_dict
def from_dict(cls, arr_dict, dtype=None, fillna=False, **kwargs): """Generate a table from a dictionary of arrays. """ # i hope order of keys == order or values if dtype is None: names = sorted(list(arr_dict.keys())) else: dtype = np.dtype(dtype) ...
python
def from_dict(cls, arr_dict, dtype=None, fillna=False, **kwargs): """Generate a table from a dictionary of arrays. """ # i hope order of keys == order or values if dtype is None: names = sorted(list(arr_dict.keys())) else: dtype = np.dtype(dtype) ...
[ "def", "from_dict", "(", "cls", ",", "arr_dict", ",", "dtype", "=", "None", ",", "fillna", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# i hope order of keys == order or values", "if", "dtype", "is", "None", ":", "names", "=", "sorted", "(", "list", ...
Generate a table from a dictionary of arrays.
[ "Generate", "a", "table", "from", "a", "dictionary", "of", "arrays", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L246-L270
train
Generate a table from a dictionary of arrays.
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.from_template
def from_template(cls, data, template): """Create a table from a predefined datatype. See the ``templates_avail`` property for available names. Parameters ---------- data Data in a format that the ``__init__`` understands. template: str or dict N...
python
def from_template(cls, data, template): """Create a table from a predefined datatype. See the ``templates_avail`` property for available names. Parameters ---------- data Data in a format that the ``__init__`` understands. template: str or dict N...
[ "def", "from_template", "(", "cls", ",", "data", ",", "template", ")", ":", "name", "=", "DEFAULT_NAME", "if", "isinstance", "(", "template", ",", "str", ")", ":", "name", "=", "template", "table_info", "=", "TEMPLATES", "[", "name", "]", "else", ":", ...
Create a table from a predefined datatype. See the ``templates_avail`` property for available names. Parameters ---------- data Data in a format that the ``__init__`` understands. template: str or dict Name of the dtype template to use from ``kp.dataclas...
[ "Create", "a", "table", "from", "a", "predefined", "datatype", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L314-L348
train
Create a new instance of the class from a predefined datatype.
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.append_columns
def append_columns(self, colnames, values, **kwargs): """Append new columns to the table. When appending a single column, ``values`` can be a scalar or an array of either length 1 or the same length as this array (the one it's appended to). In case of multiple columns, values must have ...
python
def append_columns(self, colnames, values, **kwargs): """Append new columns to the table. When appending a single column, ``values`` can be a scalar or an array of either length 1 or the same length as this array (the one it's appended to). In case of multiple columns, values must have ...
[ "def", "append_columns", "(", "self", ",", "colnames", ",", "values", ",", "*", "*", "kwargs", ")", ":", "n", "=", "len", "(", "self", ")", "if", "np", ".", "isscalar", "(", "values", ")", ":", "values", "=", "np", ".", "full", "(", "n", ",", "...
Append new columns to the table. When appending a single column, ``values`` can be a scalar or an array of either length 1 or the same length as this array (the one it's appended to). In case of multiple columns, values must have the shape ``list(arrays)``, and the dimension of each arr...
[ "Append", "new", "columns", "to", "the", "table", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L362-L402
train
Append new columns to the table.
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.drop_columns
def drop_columns(self, colnames, **kwargs): """Drop columns from the table. See the docs for ``numpy.lib.recfunctions.drop_fields`` for an explanation of the remaining options. """ new_arr = rfn.drop_fields( self, colnames, usemask=False, asrecarray=True, **kwargs ...
python
def drop_columns(self, colnames, **kwargs): """Drop columns from the table. See the docs for ``numpy.lib.recfunctions.drop_fields`` for an explanation of the remaining options. """ new_arr = rfn.drop_fields( self, colnames, usemask=False, asrecarray=True, **kwargs ...
[ "def", "drop_columns", "(", "self", ",", "colnames", ",", "*", "*", "kwargs", ")", ":", "new_arr", "=", "rfn", ".", "drop_fields", "(", "self", ",", "colnames", ",", "usemask", "=", "False", ",", "asrecarray", "=", "True", ",", "*", "*", "kwargs", ")...
Drop columns from the table. See the docs for ``numpy.lib.recfunctions.drop_fields`` for an explanation of the remaining options.
[ "Drop", "columns", "from", "the", "table", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L404-L419
train
Drop columns from the table.
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.sorted
def sorted(self, by, **kwargs): """Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time'). """ sort_idc = np.argsort(self[by], **kwargs) return self.__class__( self[sort_idc], h5loc=se...
python
def sorted(self, by, **kwargs): """Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time'). """ sort_idc = np.argsort(self[by], **kwargs) return self.__class__( self[sort_idc], h5loc=se...
[ "def", "sorted", "(", "self", ",", "by", ",", "*", "*", "kwargs", ")", ":", "sort_idc", "=", "np", ".", "argsort", "(", "self", "[", "by", "]", ",", "*", "*", "kwargs", ")", "return", "self", ".", "__class__", "(", "self", "[", "sort_idc", "]", ...
Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time').
[ "Sort", "array", "by", "a", "column", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L421-L435
train
Sort the array by a column.
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.merge
def merge(cls, tables, fillna=False): """Merge a list of tables""" cols = set(itertools.chain(*[table.dtype.descr for table in tables])) tables_to_merge = [] for table in tables: missing_cols = cols - set(table.dtype.descr) if missing_cols: if fi...
python
def merge(cls, tables, fillna=False): """Merge a list of tables""" cols = set(itertools.chain(*[table.dtype.descr for table in tables])) tables_to_merge = [] for table in tables: missing_cols = cols - set(table.dtype.descr) if missing_cols: if fi...
[ "def", "merge", "(", "cls", ",", "tables", ",", "fillna", "=", "False", ")", ":", "cols", "=", "set", "(", "itertools", ".", "chain", "(", "*", "[", "table", ".", "dtype", ".", "descr", "for", "table", "in", "tables", "]", ")", ")", "tables_to_merg...
Merge a list of tables
[ "Merge", "a", "list", "of", "tables" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L447-L487
train
Merge a list of tables into a single table.
tamasgal/km3pipe
km3pipe/io/hdf5.py
create_index_tuple
def create_index_tuple(group_ids): """An helper function to create index tuples for fast lookup in HDF5Pump""" max_group_id = np.max(group_ids) start_idx_arr = np.full(max_group_id + 1, 0) n_items_arr = np.full(max_group_id + 1, 0) current_group_id = group_ids[0] current_idx = 0 item_count...
python
def create_index_tuple(group_ids): """An helper function to create index tuples for fast lookup in HDF5Pump""" max_group_id = np.max(group_ids) start_idx_arr = np.full(max_group_id + 1, 0) n_items_arr = np.full(max_group_id + 1, 0) current_group_id = group_ids[0] current_idx = 0 item_count...
[ "def", "create_index_tuple", "(", "group_ids", ")", ":", "max_group_id", "=", "np", ".", "max", "(", "group_ids", ")", "start_idx_arr", "=", "np", ".", "full", "(", "max_group_id", "+", "1", ",", "0", ")", "n_items_arr", "=", "np", ".", "full", "(", "m...
An helper function to create index tuples for fast lookup in HDF5Pump
[ "An", "helper", "function", "to", "create", "index", "tuples", "for", "fast", "lookup", "in", "HDF5Pump" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L892-L915
train
Create index tuples for fast lookup in HDF5Pump
tamasgal/km3pipe
km3pipe/io/hdf5.py
HDF5Header._set_attributes
def _set_attributes(self): """Traverse the internal dictionary and set the getters""" for parameter, data in self._data.items(): if isinstance(data, dict) or isinstance(data, OrderedDict): field_names, field_values = zip(*data.items()) sorted_indices = np.args...
python
def _set_attributes(self): """Traverse the internal dictionary and set the getters""" for parameter, data in self._data.items(): if isinstance(data, dict) or isinstance(data, OrderedDict): field_names, field_values = zip(*data.items()) sorted_indices = np.args...
[ "def", "_set_attributes", "(", "self", ")", ":", "for", "parameter", ",", "data", "in", "self", ".", "_data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", "or", "isinstance", "(", "data", ",", "OrderedDict", ")", ":...
Traverse the internal dictionary and set the getters
[ "Traverse", "the", "internal", "dictionary", "and", "set", "the", "getters" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L74-L88
train
Traverse the internal dictionary and set the getters
tamasgal/km3pipe
km3pipe/io/hdf5.py
HDF5Sink._write_ndarrays_cache_to_disk
def _write_ndarrays_cache_to_disk(self): """Writes all the cached NDArrays to disk and empties the cache""" for h5loc, arrs in self._ndarrays_cache.items(): title = arrs[0].title chunkshape = (self.chunksize,) + arrs[0].shape[1:] if self.chunksize is not\ ...
python
def _write_ndarrays_cache_to_disk(self): """Writes all the cached NDArrays to disk and empties the cache""" for h5loc, arrs in self._ndarrays_cache.items(): title = arrs[0].title chunkshape = (self.chunksize,) + arrs[0].shape[1:] if self.chunksize is not\ ...
[ "def", "_write_ndarrays_cache_to_disk", "(", "self", ")", ":", "for", "h5loc", ",", "arrs", "in", "self", ".", "_ndarrays_cache", ".", "items", "(", ")", ":", "title", "=", "arrs", "[", "0", "]", ".", "title", "chunkshape", "=", "(", "self", ".", "chun...
Writes all the cached NDArrays to disk and empties the cache
[ "Writes", "all", "the", "cached", "NDArrays", "to", "disk", "and", "empties", "the", "cache" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L254-L289
train
Writes all the cached NDArrays to disk and empties the cache
tamasgal/km3pipe
km3pipe/io/hdf5.py
HDF5Sink.flush
def flush(self): """Flush tables and arrays to disk""" self.log.info('Flushing tables and arrays to disk...') for tab in self._tables.values(): tab.flush() self._write_ndarrays_cache_to_disk()
python
def flush(self): """Flush tables and arrays to disk""" self.log.info('Flushing tables and arrays to disk...') for tab in self._tables.values(): tab.flush() self._write_ndarrays_cache_to_disk()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'Flushing tables and arrays to disk...'", ")", "for", "tab", "in", "self", ".", "_tables", ".", "values", "(", ")", ":", "tab", ".", "flush", "(", ")", "self", ".", "_write_n...
Flush tables and arrays to disk
[ "Flush", "tables", "and", "arrays", "to", "disk" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L450-L455
train
Flush tables and arrays to disk
PrefPy/prefpy
prefpy/gmm_mixpl_moments.py
top2_reduced
def top2_reduced(votes): """ Description: Top 2 alternatives 12 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ res = np.zeros(12) for vote in votes: # the top ranked alternative is in vote[0][0], second in v...
python
def top2_reduced(votes): """ Description: Top 2 alternatives 12 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ res = np.zeros(12) for vote in votes: # the top ranked alternative is in vote[0][0], second in v...
[ "def", "top2_reduced", "(", "votes", ")", ":", "res", "=", "np", ".", "zeros", "(", "12", ")", "for", "vote", "in", "votes", ":", "# the top ranked alternative is in vote[0][0], second in vote[1][0]", "if", "vote", "[", "0", "]", "[", "0", "]", "==", "0", ...
Description: Top 2 alternatives 12 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers)
[ "Description", ":", "Top", "2", "alternatives", "12", "moment", "conditions", "values", "calculation", "Parameters", ":", "votes", ":", "ordinal", "preference", "data", "(", "numpy", "ndarray", "of", "integers", ")" ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmm_mixpl_moments.py#L11-L46
train
This function calculates the 12 top 2 alternatives for the given set of votes.
PrefPy/prefpy
prefpy/gmm_mixpl_moments.py
top2_full
def top2_full(votes): """ Description: Top 2 alternatives 16 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ res = np.zeros(16) for vote in votes: # the top ranked alternative is in vote[0][0], second in vote...
python
def top2_full(votes): """ Description: Top 2 alternatives 16 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ res = np.zeros(16) for vote in votes: # the top ranked alternative is in vote[0][0], second in vote...
[ "def", "top2_full", "(", "votes", ")", ":", "res", "=", "np", ".", "zeros", "(", "16", ")", "for", "vote", "in", "votes", ":", "# the top ranked alternative is in vote[0][0], second in vote[1][0]", "if", "vote", "[", "0", "]", "[", "0", "]", "==", "0", ":"...
Description: Top 2 alternatives 16 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers)
[ "Description", ":", "Top", "2", "alternatives", "16", "moment", "conditions", "values", "calculation", "Parameters", ":", "votes", ":", "ordinal", "preference", "data", "(", "numpy", "ndarray", "of", "integers", ")" ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmm_mixpl_moments.py#L49-L92
train
This function calculates the top 2 alternatives of the main language.
PrefPy/prefpy
prefpy/gmm_mixpl_moments.py
top3_reduced
def top3_reduced(votes): """ Description: Top 3 alternatives 16 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ res = np.zeros(16) for vote in votes: # the top ranked alternative is in vote[0][0], second in v...
python
def top3_reduced(votes): """ Description: Top 3 alternatives 16 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ res = np.zeros(16) for vote in votes: # the top ranked alternative is in vote[0][0], second in v...
[ "def", "top3_reduced", "(", "votes", ")", ":", "res", "=", "np", ".", "zeros", "(", "16", ")", "for", "vote", "in", "votes", ":", "# the top ranked alternative is in vote[0][0], second in vote[1][0]", "if", "vote", "[", "0", "]", "[", "0", "]", "==", "0", ...
Description: Top 3 alternatives 16 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers)
[ "Description", ":", "Top", "3", "alternatives", "16", "moment", "conditions", "values", "calculation", "Parameters", ":", "votes", ":", "ordinal", "preference", "data", "(", "numpy", "ndarray", "of", "integers", ")" ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmm_mixpl_moments.py#L95-L138
train
This function calculates the top 3 alternatives 16 moment conditions values calculation
PrefPy/prefpy
prefpy/gmm_mixpl_moments.py
top3_full
def top3_full(votes): """ Description: Top m - 1 alternatives q = m(m - 1) + 2m moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ #create array of zeros, length = q res = np.zeros(2 * len(votes[0]) + (len(votes[0]) * (...
python
def top3_full(votes): """ Description: Top m - 1 alternatives q = m(m - 1) + 2m moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ #create array of zeros, length = q res = np.zeros(2 * len(votes[0]) + (len(votes[0]) * (...
[ "def", "top3_full", "(", "votes", ")", ":", "#create array of zeros, length = q", "res", "=", "np", ".", "zeros", "(", "2", "*", "len", "(", "votes", "[", "0", "]", ")", "+", "(", "len", "(", "votes", "[", "0", "]", ")", "*", "(", "len", "(", "vo...
Description: Top m - 1 alternatives q = m(m - 1) + 2m moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers)
[ "Description", ":", "Top", "m", "-", "1", "alternatives", "q", "=", "m", "(", "m", "-", "1", ")", "+", "2m", "moment", "conditions", "values", "calculation", "Parameters", ":", "votes", ":", "ordinal", "preference", "data", "(", "numpy", "ndarray", "of",...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmm_mixpl_moments.py#L141-L174
train
This function calculates the top 3 alternatives of the given set of entries.
cprogrammer1994/GLWindow
GLWindow/__main__.py
main
def main(): ''' Sample program to test GLWindow. ''' print('GLWindow:', GLWindow.__version__) print('Python:', sys.version) print('Platform:', sys.platform) wnd = GLWindow.create_window((480, 480), title='GLWindow Sample') wnd.vsync = False ctx = ModernGL.create_context() ...
python
def main(): ''' Sample program to test GLWindow. ''' print('GLWindow:', GLWindow.__version__) print('Python:', sys.version) print('Platform:', sys.platform) wnd = GLWindow.create_window((480, 480), title='GLWindow Sample') wnd.vsync = False ctx = ModernGL.create_context() ...
[ "def", "main", "(", ")", ":", "print", "(", "'GLWindow:'", ",", "GLWindow", ".", "__version__", ")", "print", "(", "'Python:'", ",", "sys", ".", "version", ")", "print", "(", "'Platform:'", ",", "sys", ".", "platform", ")", "wnd", "=", "GLWindow", ".",...
Sample program to test GLWindow.
[ "Sample", "program", "to", "test", "GLWindow", "." ]
521e18fcbc15e88d3c1f3547aa313c3a07386ee5
https://github.com/cprogrammer1994/GLWindow/blob/521e18fcbc15e88d3c1f3547aa313c3a07386ee5/GLWindow/__main__.py#L12-L71
train
This program will test GLWindow. Formula.
tamasgal/km3pipe
examples/offline_analysis/k40summary.py
write_header
def write_header(fobj): """Add the header to the CSV file""" fobj.write("# K40 calibration results\n") fobj.write("det_id\trun_id\tdom_id") for param in ['t0', 'qe']: for i in range(31): fobj.write("\t{}_ch{}".format(param, i))
python
def write_header(fobj): """Add the header to the CSV file""" fobj.write("# K40 calibration results\n") fobj.write("det_id\trun_id\tdom_id") for param in ['t0', 'qe']: for i in range(31): fobj.write("\t{}_ch{}".format(param, i))
[ "def", "write_header", "(", "fobj", ")", ":", "fobj", ".", "write", "(", "\"# K40 calibration results\\n\"", ")", "fobj", ".", "write", "(", "\"det_id\\trun_id\\tdom_id\"", ")", "for", "param", "in", "[", "'t0'", ",", "'qe'", "]", ":", "for", "i", "in", "r...
Add the header to the CSV file
[ "Add", "the", "header", "to", "the", "CSV", "file" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/examples/offline_analysis/k40summary.py#L30-L36
train
Add the header to the CSV file
tamasgal/km3pipe
km3pipe/math.py
neutrino_to_source_direction
def neutrino_to_source_direction(phi, theta, radian=True): """Flip the direction. Parameters ========== phi, theta: neutrino direction radian: bool [default=True] receive + return angles in radian? (if false, use degree) """ phi = np.atleast_1d(phi).copy() theta = np.atleast_1d(...
python
def neutrino_to_source_direction(phi, theta, radian=True): """Flip the direction. Parameters ========== phi, theta: neutrino direction radian: bool [default=True] receive + return angles in radian? (if false, use degree) """ phi = np.atleast_1d(phi).copy() theta = np.atleast_1d(...
[ "def", "neutrino_to_source_direction", "(", "phi", ",", "theta", ",", "radian", "=", "True", ")", ":", "phi", "=", "np", ".", "atleast_1d", "(", "phi", ")", ".", "copy", "(", ")", "theta", "=", "np", ".", "atleast_1d", "(", "theta", ")", ".", "copy",...
Flip the direction. Parameters ========== phi, theta: neutrino direction radian: bool [default=True] receive + return angles in radian? (if false, use degree)
[ "Flip", "the", "direction", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L25-L46
train
Flip the direction of a neutrino in the source direction.
tamasgal/km3pipe
km3pipe/math.py
source_to_neutrino_direction
def source_to_neutrino_direction(azimuth, zenith, radian=True): """Flip the direction. Parameters ========== zenith, azimuth: neutrino origin radian: bool [default=True] receive + return angles in radian? (if false, use degree) """ azimuth = np.atleast_1d(azimuth).copy() zenith ...
python
def source_to_neutrino_direction(azimuth, zenith, radian=True): """Flip the direction. Parameters ========== zenith, azimuth: neutrino origin radian: bool [default=True] receive + return angles in radian? (if false, use degree) """ azimuth = np.atleast_1d(azimuth).copy() zenith ...
[ "def", "source_to_neutrino_direction", "(", "azimuth", ",", "zenith", ",", "radian", "=", "True", ")", ":", "azimuth", "=", "np", ".", "atleast_1d", "(", "azimuth", ")", ".", "copy", "(", ")", "zenith", "=", "np", ".", "atleast_1d", "(", "zenith", ")", ...
Flip the direction. Parameters ========== zenith, azimuth: neutrino origin radian: bool [default=True] receive + return angles in radian? (if false, use degree)
[ "Flip", "the", "direction", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L49-L68
train
Flip the direction from source to neutrino.
tamasgal/km3pipe
km3pipe/math.py
theta
def theta(v): """Neutrino direction in polar coordinates. Downgoing event: theta = 180deg Horizont: 90deg Upgoing: theta = 0 Angles in radians. """ v = np.atleast_2d(v) dir_z = v[:, 2] return theta_separg(dir_z)
python
def theta(v): """Neutrino direction in polar coordinates. Downgoing event: theta = 180deg Horizont: 90deg Upgoing: theta = 0 Angles in radians. """ v = np.atleast_2d(v) dir_z = v[:, 2] return theta_separg(dir_z)
[ "def", "theta", "(", "v", ")", ":", "v", "=", "np", ".", "atleast_2d", "(", "v", ")", "dir_z", "=", "v", "[", ":", ",", "2", "]", "return", "theta_separg", "(", "dir_z", ")" ]
Neutrino direction in polar coordinates. Downgoing event: theta = 180deg Horizont: 90deg Upgoing: theta = 0 Angles in radians.
[ "Neutrino", "direction", "in", "polar", "coordinates", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L71-L82
train
Returns the angle in polar coordinates.
tamasgal/km3pipe
km3pipe/math.py
phi
def phi(v): """Neutrino direction in polar coordinates. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. Angles in radians. """ v = np.atleast_2d(v) dir_x = v[:, 0] dir_y = v[:, 1] return phi_separg(dir_x, dir_y)
python
def phi(v): """Neutrino direction in polar coordinates. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. Angles in radians. """ v = np.atleast_2d(v) dir_x = v[:, 0] dir_y = v[:, 1] return phi_separg(dir_x, dir_y)
[ "def", "phi", "(", "v", ")", ":", "v", "=", "np", ".", "atleast_2d", "(", "v", ")", "dir_x", "=", "v", "[", ":", ",", "0", "]", "dir_y", "=", "v", "[", ":", ",", "1", "]", "return", "phi_separg", "(", "dir_x", ",", "dir_y", ")" ]
Neutrino direction in polar coordinates. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. Angles in radians.
[ "Neutrino", "direction", "in", "polar", "coordinates", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L89-L99
train
Neutrino direction in polar coordinates.
tamasgal/km3pipe
km3pipe/math.py
azimuth
def azimuth(v): """Return the azimuth angle in radians. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. This is the 'normal' azimuth definition -- beware of how you define your coordinates. KM3NeT defines azimuth differently than e.g. SLALIB, astropy, the AAS.org """ v = np....
python
def azimuth(v): """Return the azimuth angle in radians. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. This is the 'normal' azimuth definition -- beware of how you define your coordinates. KM3NeT defines azimuth differently than e.g. SLALIB, astropy, the AAS.org """ v = np....
[ "def", "azimuth", "(", "v", ")", ":", "v", "=", "np", ".", "atleast_2d", "(", "v", ")", "azi", "=", "phi", "(", "v", ")", "-", "np", ".", "pi", "azi", "[", "azi", "<", "0", "]", "+=", "2", "*", "np", ".", "pi", "if", "len", "(", "azi", ...
Return the azimuth angle in radians. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. This is the 'normal' azimuth definition -- beware of how you define your coordinates. KM3NeT defines azimuth differently than e.g. SLALIB, astropy, the AAS.org
[ "Return", "the", "azimuth", "angle", "in", "radians", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L119-L133
train
Return the azimuth angle in radians.
tamasgal/km3pipe
km3pipe/math.py
angle_between
def angle_between(v1, v2): """Returns the angle in radians between vectors 'v1' and 'v2'. >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 """ v1_u = unit_vector(v1) ...
python
def angle_between(v1, v2): """Returns the angle in radians between vectors 'v1' and 'v2'. >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 """ v1_u = unit_vector(v1) ...
[ "def", "angle_between", "(", "v1", ",", "v2", ")", ":", "v1_u", "=", "unit_vector", "(", "v1", ")", "v2_u", "=", "unit_vector", "(", "v2", ")", "# Don't use `np.dot`, does not work with all shapes", "angle", "=", "np", ".", "arccos", "(", "np", ".", "inner",...
Returns the angle in radians between vectors 'v1' and 'v2'. >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793
[ "Returns", "the", "angle", "in", "radians", "between", "vectors", "v1", "and", "v2", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L143-L158
train
Returns the angle in radians between vectors v1 and v2.
tamasgal/km3pipe
km3pipe/math.py
unit_vector
def unit_vector(vector, **kwargs): """Returns the unit vector of the vector.""" # This also works for a dataframe with columns ['x', 'y', 'z'] # However, the division operation is picky about the shapes # So, remember input vector shape, cast all up to 2d, # do the (ugly) conversion, then return uni...
python
def unit_vector(vector, **kwargs): """Returns the unit vector of the vector.""" # This also works for a dataframe with columns ['x', 'y', 'z'] # However, the division operation is picky about the shapes # So, remember input vector shape, cast all up to 2d, # do the (ugly) conversion, then return uni...
[ "def", "unit_vector", "(", "vector", ",", "*", "*", "kwargs", ")", ":", "# This also works for a dataframe with columns ['x', 'y', 'z']", "# However, the division operation is picky about the shapes", "# So, remember input vector shape, cast all up to 2d,", "# do the (ugly) conversion, the...
Returns the unit vector of the vector.
[ "Returns", "the", "unit", "vector", "of", "the", "vector", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L175-L186
train
Returns the unit vector of the vector.
tamasgal/km3pipe
km3pipe/math.py
pld3
def pld3(pos, line_vertex, line_dir): """Calculate the point-line-distance for given point and line.""" pos = np.atleast_2d(pos) line_vertex = np.atleast_1d(line_vertex) line_dir = np.atleast_1d(line_dir) c = np.cross(line_dir, line_vertex - pos) n1 = np.linalg.norm(c, axis=1) n2 = np.linalg...
python
def pld3(pos, line_vertex, line_dir): """Calculate the point-line-distance for given point and line.""" pos = np.atleast_2d(pos) line_vertex = np.atleast_1d(line_vertex) line_dir = np.atleast_1d(line_dir) c = np.cross(line_dir, line_vertex - pos) n1 = np.linalg.norm(c, axis=1) n2 = np.linalg...
[ "def", "pld3", "(", "pos", ",", "line_vertex", ",", "line_dir", ")", ":", "pos", "=", "np", ".", "atleast_2d", "(", "pos", ")", "line_vertex", "=", "np", ".", "atleast_1d", "(", "line_vertex", ")", "line_dir", "=", "np", ".", "atleast_1d", "(", "line_d...
Calculate the point-line-distance for given point and line.
[ "Calculate", "the", "point", "-", "line", "-", "distance", "for", "given", "point", "and", "line", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L189-L200
train
Calculate the point - line - distance for given point and line.
tamasgal/km3pipe
km3pipe/math.py
dist
def dist(x1, x2, axis=0): """Return the distance between two points. Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances. """ return np.linalg.norm(x2 - x1, axis=axis)
python
def dist(x1, x2, axis=0): """Return the distance between two points. Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances. """ return np.linalg.norm(x2 - x1, axis=axis)
[ "def", "dist", "(", "x1", ",", "x2", ",", "axis", "=", "0", ")", ":", "return", "np", ".", "linalg", ".", "norm", "(", "x2", "-", "x1", ",", "axis", "=", "axis", ")" ]
Return the distance between two points. Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances.
[ "Return", "the", "distance", "between", "two", "points", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L207-L212
train
Return the distance between two points.
tamasgal/km3pipe
km3pipe/math.py
com
def com(points, masses=None): """Calculate center of mass for given points. If masses is not set, assume equal masses.""" if masses is None: return np.average(points, axis=0) else: return np.average(points, axis=0, weights=masses)
python
def com(points, masses=None): """Calculate center of mass for given points. If masses is not set, assume equal masses.""" if masses is None: return np.average(points, axis=0) else: return np.average(points, axis=0, weights=masses)
[ "def", "com", "(", "points", ",", "masses", "=", "None", ")", ":", "if", "masses", "is", "None", ":", "return", "np", ".", "average", "(", "points", ",", "axis", "=", "0", ")", "else", ":", "return", "np", ".", "average", "(", "points", ",", "axi...
Calculate center of mass for given points. If masses is not set, assume equal masses.
[ "Calculate", "center", "of", "mass", "for", "given", "points", ".", "If", "masses", "is", "not", "set", "assume", "equal", "masses", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L215-L221
train
Calculate center of mass for given points.
tamasgal/km3pipe
km3pipe/math.py
circ_permutation
def circ_permutation(items): """Calculate the circular permutation for a given list of items.""" permutations = [] for i in range(len(items)): permutations.append(items[i:] + items[:i]) return permutations
python
def circ_permutation(items): """Calculate the circular permutation for a given list of items.""" permutations = [] for i in range(len(items)): permutations.append(items[i:] + items[:i]) return permutations
[ "def", "circ_permutation", "(", "items", ")", ":", "permutations", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "items", ")", ")", ":", "permutations", ".", "append", "(", "items", "[", "i", ":", "]", "+", "items", "[", ":", "i", "]...
Calculate the circular permutation for a given list of items.
[ "Calculate", "the", "circular", "permutation", "for", "a", "given", "list", "of", "items", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L224-L229
train
Calculate the circular permutation for a given list of items.
tamasgal/km3pipe
km3pipe/math.py
space_angle
def space_angle(phi1, theta1, phi2, theta2): """Also called Great-circle-distance -- use long-ass formula from wikipedia (last in section): https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas Space angle only makes sense in lon-lat, so convert zenith -> latitude. """ from...
python
def space_angle(phi1, theta1, phi2, theta2): """Also called Great-circle-distance -- use long-ass formula from wikipedia (last in section): https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas Space angle only makes sense in lon-lat, so convert zenith -> latitude. """ from...
[ "def", "space_angle", "(", "phi1", ",", "theta1", ",", "phi2", ",", "theta2", ")", ":", "from", "numpy", "import", "pi", ",", "sin", ",", "cos", ",", "arctan2", ",", "sqrt", ",", "square", "lamb1", "=", "pi", "/", "2", "-", "theta1", "lamb2", "=", ...
Also called Great-circle-distance -- use long-ass formula from wikipedia (last in section): https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas Space angle only makes sense in lon-lat, so convert zenith -> latitude.
[ "Also", "called", "Great", "-", "circle", "-", "distance", "--", "use", "long", "-", "ass", "formula", "from", "wikipedia", "(", "last", "in", "section", ")", ":", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Great", "-"...
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L237-L254
train
Returns the angle between two points in a single space.
tamasgal/km3pipe
km3pipe/math.py
rotation_matrix
def rotation_matrix(axis, theta): """The Euler–Rodrigues formula. Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. Parameters ---------- axis: vector to rotate around theta: rotation angle, in rad """ axis = np.asarray(axis...
python
def rotation_matrix(axis, theta): """The Euler–Rodrigues formula. Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. Parameters ---------- axis: vector to rotate around theta: rotation angle, in rad """ axis = np.asarray(axis...
[ "def", "rotation_matrix", "(", "axis", ",", "theta", ")", ":", "axis", "=", "np", ".", "asarray", "(", "axis", ")", "axis", "=", "axis", "/", "np", ".", "linalg", ".", "norm", "(", "axis", ")", "a", "=", "np", ".", "cos", "(", "theta", "/", "2"...
The Euler–Rodrigues formula. Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. Parameters ---------- axis: vector to rotate around theta: rotation angle, in rad
[ "The", "Euler–Rodrigues", "formula", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L257-L278
train
The Euler–Rodrigues formula.
tamasgal/km3pipe
km3pipe/math.py
inertia
def inertia(x, y, z, weight=None): """Inertia tensor, stolen of thomas""" if weight is None: weight = 1 tensor_of_inertia = np.zeros((3, 3), dtype=float) tensor_of_inertia[0][0] = (y * y + z * z) * weight tensor_of_inertia[0][1] = (-1) * x * y * weight tensor_of_inertia[0][2] = (-1) * x ...
python
def inertia(x, y, z, weight=None): """Inertia tensor, stolen of thomas""" if weight is None: weight = 1 tensor_of_inertia = np.zeros((3, 3), dtype=float) tensor_of_inertia[0][0] = (y * y + z * z) * weight tensor_of_inertia[0][1] = (-1) * x * y * weight tensor_of_inertia[0][2] = (-1) * x ...
[ "def", "inertia", "(", "x", ",", "y", ",", "z", ",", "weight", "=", "None", ")", ":", "if", "weight", "is", "None", ":", "weight", "=", "1", "tensor_of_inertia", "=", "np", ".", "zeros", "(", "(", "3", ",", "3", ")", ",", "dtype", "=", "float",...
Inertia tensor, stolen of thomas
[ "Inertia", "tensor", "stolen", "of", "thomas" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L381-L400
train
Inertia tensor stolen of thomas
tamasgal/km3pipe
km3pipe/math.py
g_parameter
def g_parameter(time_residual): """stolen from thomas""" mean = np.mean(time_residual) time_residual_prime = (time_residual - np.ones(time_residual.shape) * mean) time_residual_prime *= time_residual_prime / (-2 * 1.5 * 1.5) time_residual_prime = np.exp(time_residual_prime) g = np.sum(time_resid...
python
def g_parameter(time_residual): """stolen from thomas""" mean = np.mean(time_residual) time_residual_prime = (time_residual - np.ones(time_residual.shape) * mean) time_residual_prime *= time_residual_prime / (-2 * 1.5 * 1.5) time_residual_prime = np.exp(time_residual_prime) g = np.sum(time_resid...
[ "def", "g_parameter", "(", "time_residual", ")", ":", "mean", "=", "np", ".", "mean", "(", "time_residual", ")", "time_residual_prime", "=", "(", "time_residual", "-", "np", ".", "ones", "(", "time_residual", ".", "shape", ")", "*", "mean", ")", "time_resi...
stolen from thomas
[ "stolen", "from", "thomas" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L403-L410
train
stolen from thomas
tamasgal/km3pipe
km3pipe/math.py
gold_parameter
def gold_parameter(time_residual): """stolen from thomas""" gold = np.exp(-1 * time_residual * time_residual / (2 * 1.5 * 1.5)) / len(time_residual) gold = np.sum(gold)
python
def gold_parameter(time_residual): """stolen from thomas""" gold = np.exp(-1 * time_residual * time_residual / (2 * 1.5 * 1.5)) / len(time_residual) gold = np.sum(gold)
[ "def", "gold_parameter", "(", "time_residual", ")", ":", "gold", "=", "np", ".", "exp", "(", "-", "1", "*", "time_residual", "*", "time_residual", "/", "(", "2", "*", "1.5", "*", "1.5", ")", ")", "/", "len", "(", "time_residual", ")", "gold", "=", ...
stolen from thomas
[ "stolen", "from", "thomas" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L413-L417
train
stolen from thomas
tamasgal/km3pipe
km3pipe/math.py
qrot
def qrot(vector, quaternion): """Rotate a 3D vector using quaternion algebra. Implemented by Vladimir Kulikovskiy. Parameters ---------- vector: np.array quaternion: np.array Returns ------- np.array """ t = 2 * np.cross(quaternion[1:], vector) v_rot = vector + quater...
python
def qrot(vector, quaternion): """Rotate a 3D vector using quaternion algebra. Implemented by Vladimir Kulikovskiy. Parameters ---------- vector: np.array quaternion: np.array Returns ------- np.array """ t = 2 * np.cross(quaternion[1:], vector) v_rot = vector + quater...
[ "def", "qrot", "(", "vector", ",", "quaternion", ")", ":", "t", "=", "2", "*", "np", ".", "cross", "(", "quaternion", "[", "1", ":", "]", ",", "vector", ")", "v_rot", "=", "vector", "+", "quaternion", "[", "0", "]", "*", "t", "+", "np", ".", ...
Rotate a 3D vector using quaternion algebra. Implemented by Vladimir Kulikovskiy. Parameters ---------- vector: np.array quaternion: np.array Returns ------- np.array
[ "Rotate", "a", "3D", "vector", "using", "quaternion", "algebra", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L425-L442
train
Rotate a 3D vector using quaternion algebra.
tamasgal/km3pipe
km3pipe/math.py
qeuler
def qeuler(yaw, pitch, roll): """Convert Euler angle to quaternion. Parameters ---------- yaw: number pitch: number roll: number Returns ------- np.array """ yaw = np.radians(yaw) pitch = np.radians(pitch) roll = np.radians(roll) cy = np.cos(yaw * 0.5) sy ...
python
def qeuler(yaw, pitch, roll): """Convert Euler angle to quaternion. Parameters ---------- yaw: number pitch: number roll: number Returns ------- np.array """ yaw = np.radians(yaw) pitch = np.radians(pitch) roll = np.radians(roll) cy = np.cos(yaw * 0.5) sy ...
[ "def", "qeuler", "(", "yaw", ",", "pitch", ",", "roll", ")", ":", "yaw", "=", "np", ".", "radians", "(", "yaw", ")", "pitch", "=", "np", ".", "radians", "(", "pitch", ")", "roll", "=", "np", ".", "radians", "(", "roll", ")", "cy", "=", "np", ...
Convert Euler angle to quaternion. Parameters ---------- yaw: number pitch: number roll: number Returns ------- np.array
[ "Convert", "Euler", "angle", "to", "quaternion", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L445-L474
train
Convert Euler angle to quaternion.
tamasgal/km3pipe
km3pipe/math.py
intersect_3d
def intersect_3d(p1, p2): """Find the closes point for a given set of lines in 3D. Parameters ---------- p1 : (M, N) array_like Starting points p2 : (M, N) array_like End points. Returns ------- x : (N,) ndarray Least-squares solution - the closest point of the ...
python
def intersect_3d(p1, p2): """Find the closes point for a given set of lines in 3D. Parameters ---------- p1 : (M, N) array_like Starting points p2 : (M, N) array_like End points. Returns ------- x : (N,) ndarray Least-squares solution - the closest point of the ...
[ "def", "intersect_3d", "(", "p1", ",", "p2", ")", ":", "v", "=", "p2", "-", "p1", "normed_v", "=", "unit_vector", "(", "v", ")", "nx", "=", "normed_v", "[", ":", ",", "0", "]", "ny", "=", "normed_v", "[", ":", ",", "1", "]", "nz", "=", "norme...
Find the closes point for a given set of lines in 3D. Parameters ---------- p1 : (M, N) array_like Starting points p2 : (M, N) array_like End points. Returns ------- x : (N,) ndarray Least-squares solution - the closest point of the intersections. Raises --...
[ "Find", "the", "closes", "point", "for", "a", "given", "set", "of", "lines", "in", "3D", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L494-L536
train
Find the closest point of the intersections between two sets of lines in 3D.
htm-community/menorah
menorah/swarmrunner.py
swarm
def swarm(workingDir): """ Runs a swarm in the giving working directory, assuming it was created by Menorah. :param workingDir: absolute or relative path to working directory created by Menorah """ name = os.path.splitext(os.path.basename(workingDir))[0] swarmDescriptionFile = os.pat...
python
def swarm(workingDir): """ Runs a swarm in the giving working directory, assuming it was created by Menorah. :param workingDir: absolute or relative path to working directory created by Menorah """ name = os.path.splitext(os.path.basename(workingDir))[0] swarmDescriptionFile = os.pat...
[ "def", "swarm", "(", "workingDir", ")", ":", "name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "workingDir", ")", ")", "[", "0", "]", "swarmDescriptionFile", "=", "os", ".", "path", ".", "join", "(", "wo...
Runs a swarm in the giving working directory, assuming it was created by Menorah. :param workingDir: absolute or relative path to working directory created by Menorah
[ "Runs", "a", "swarm", "in", "the", "giving", "working", "directory", "assuming", "it", "was", "created", "by", "Menorah", ".", ":", "param", "workingDir", ":", "absolute", "or", "relative", "path", "to", "working", "directory", "created", "by", "Menorah" ]
1991b01eda3f6361b22ed165b4a688ae3fb2deaf
https://github.com/htm-community/menorah/blob/1991b01eda3f6361b22ed165b4a688ae3fb2deaf/menorah/swarmrunner.py#L66-L82
train
Runs a swarm in the given working directory.
astooke/gtimer
gtimer/util.py
compat_py2_py3
def compat_py2_py3(): """ For Python 2, 3 compatibility. """ if (sys.version_info > (3, 0)): def iteritems(dictionary): return dictionary.items() def itervalues(dictionary): return dictionary.values() else: def iteritems(dictionary): return dicti...
python
def compat_py2_py3(): """ For Python 2, 3 compatibility. """ if (sys.version_info > (3, 0)): def iteritems(dictionary): return dictionary.items() def itervalues(dictionary): return dictionary.values() else: def iteritems(dictionary): return dicti...
[ "def", "compat_py2_py3", "(", ")", ":", "if", "(", "sys", ".", "version_info", ">", "(", "3", ",", "0", ")", ")", ":", "def", "iteritems", "(", "dictionary", ")", ":", "return", "dictionary", ".", "items", "(", ")", "def", "itervalues", "(", "diction...
For Python 2, 3 compatibility.
[ "For", "Python", "2", "3", "compatibility", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/util.py#L20-L36
train
For Python 2 and 3 compatibility.
tamasgal/km3pipe
km3pipe/io/jpp.py
TimeslicePump.timeslice_generator
def timeslice_generator(self): """Uses slice ID as iterator""" slice_id = 0 while slice_id < self.n_timeslices: blob = self.get_blob(slice_id) yield blob slice_id += 1
python
def timeslice_generator(self): """Uses slice ID as iterator""" slice_id = 0 while slice_id < self.n_timeslices: blob = self.get_blob(slice_id) yield blob slice_id += 1
[ "def", "timeslice_generator", "(", "self", ")", ":", "slice_id", "=", "0", "while", "slice_id", "<", "self", ".", "n_timeslices", ":", "blob", "=", "self", ".", "get_blob", "(", "slice_id", ")", "yield", "blob", "slice_id", "+=", "1" ]
Uses slice ID as iterator
[ "Uses", "slice", "ID", "as", "iterator" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/jpp.py#L185-L191
train
Uses slice ID as iterator
tamasgal/km3pipe
km3pipe/io/jpp.py
TimeslicePump.get_blob
def get_blob(self, index): """Index is slice ID""" blob = self._current_blob self.r.retrieve_timeslice(index) timeslice_info = Table.from_template({ 'frame_index': self.r.frame_index, 'slice_id': index, 'timestamp': self.r.utc_seconds, 'nan...
python
def get_blob(self, index): """Index is slice ID""" blob = self._current_blob self.r.retrieve_timeslice(index) timeslice_info = Table.from_template({ 'frame_index': self.r.frame_index, 'slice_id': index, 'timestamp': self.r.utc_seconds, 'nan...
[ "def", "get_blob", "(", "self", ",", "index", ")", ":", "blob", "=", "self", ".", "_current_blob", "self", ".", "r", ".", "retrieve_timeslice", "(", "index", ")", "timeslice_info", "=", "Table", ".", "from_template", "(", "{", "'frame_index'", ":", "self",...
Index is slice ID
[ "Index", "is", "slice", "ID" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/jpp.py#L193-L208
train
Get the blob for the given index.
tamasgal/km3pipe
km3pipe/io/jpp.py
TimeslicePump._slice_generator
def _slice_generator(self, index): """A simple slice generator for iterations""" start, stop, step = index.indices(len(self)) for i in range(start, stop, step): yield self.get_blob(i)
python
def _slice_generator(self, index): """A simple slice generator for iterations""" start, stop, step = index.indices(len(self)) for i in range(start, stop, step): yield self.get_blob(i)
[ "def", "_slice_generator", "(", "self", ",", "index", ")", ":", "start", ",", "stop", ",", "step", "=", "index", ".", "indices", "(", "len", "(", "self", ")", ")", "for", "i", "in", "range", "(", "start", ",", "stop", ",", "step", ")", ":", "yiel...
A simple slice generator for iterations
[ "A", "simple", "slice", "generator", "for", "iterations" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/jpp.py#L270-L274
train
A simple slice generator for iterations
tapilab/brandelion
brandelion/cli/diagnose.py
correlation_by_exemplar
def correlation_by_exemplar(brands, exemplars, validation_scores, analyze_fn_str, outf): """ Report the overall correlation with the validation scores using each exemplar in isolation. """ analyze_fn = getattr(analyze, analyze_fn_str) keys = sorted(k for k in validation_scores.keys() if k in set(x[0] for x ...
python
def correlation_by_exemplar(brands, exemplars, validation_scores, analyze_fn_str, outf): """ Report the overall correlation with the validation scores using each exemplar in isolation. """ analyze_fn = getattr(analyze, analyze_fn_str) keys = sorted(k for k in validation_scores.keys() if k in set(x[0] for x ...
[ "def", "correlation_by_exemplar", "(", "brands", ",", "exemplars", ",", "validation_scores", ",", "analyze_fn_str", ",", "outf", ")", ":", "analyze_fn", "=", "getattr", "(", "analyze", ",", "analyze_fn_str", ")", "keys", "=", "sorted", "(", "k", "for", "k", ...
Report the overall correlation with the validation scores using each exemplar in isolation.
[ "Report", "the", "overall", "correlation", "with", "the", "validation", "scores", "using", "each", "exemplar", "in", "isolation", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/diagnose.py#L50-L66
train
Report the overall correlation with the validation scores using each exemplar in isolation.
IRC-SPHERE/HyperStream
hyperstream/node/node.py
Node.intersection
def intersection(self, meta): """ Get the intersection between the meta data given and the meta data contained within the plates. Since all of the streams have the same meta data keys (but differing values) we only need to consider the first stream. :param meta: The meta data to ...
python
def intersection(self, meta): """ Get the intersection between the meta data given and the meta data contained within the plates. Since all of the streams have the same meta data keys (but differing values) we only need to consider the first stream. :param meta: The meta data to ...
[ "def", "intersection", "(", "self", ",", "meta", ")", ":", "keys", "=", "self", ".", "_streams", "[", "0", "]", ".", "stream_id", ".", "meta_data", ".", "keys", "(", ")", "return", "StreamId", "(", "self", ".", "node_id", ",", "dict", "(", "*", "zi...
Get the intersection between the meta data given and the meta data contained within the plates. Since all of the streams have the same meta data keys (but differing values) we only need to consider the first stream. :param meta: The meta data to compare :return: A stream id with the inte...
[ "Get", "the", "intersection", "between", "the", "meta", "data", "given", "and", "the", "meta", "data", "contained", "within", "the", "plates", ".", "Since", "all", "of", "the", "streams", "have", "the", "same", "meta", "data", "keys", "(", "but", "differin...
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/node/node.py#L100-L111
train
Get the intersection between this node s meta data and the given meta data.
IRC-SPHERE/HyperStream
hyperstream/node/node.py
Node.difference
def difference(self, other): """ Summarise the differences between this node and the other node. :param other: The other node :return: A tuple containing the diff, the counts of the diff, and whether this plate is a sub-plate of the other :type other: Node """ di...
python
def difference(self, other): """ Summarise the differences between this node and the other node. :param other: The other node :return: A tuple containing the diff, the counts of the diff, and whether this plate is a sub-plate of the other :type other: Node """ di...
[ "def", "difference", "(", "self", ",", "other", ")", ":", "diff", "=", "(", "tuple", "(", "set", "(", "self", ".", "plates", ")", "-", "set", "(", "other", ".", "plates", ")", ")", ",", "tuple", "(", "set", "(", "other", ".", "plates", ")", "-"...
Summarise the differences between this node and the other node. :param other: The other node :return: A tuple containing the diff, the counts of the diff, and whether this plate is a sub-plate of the other :type other: Node
[ "Summarise", "the", "differences", "between", "this", "node", "and", "the", "other", "node", "." ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/node/node.py#L113-L127
train
Summarise the differences between this node and the other node.
IRC-SPHERE/HyperStream
hyperstream/node/node.py
Node.print_head
def print_head(self, parent_plate_value, plate_values, interval, n=10, print_func=logging.info): """ Print the first n values from the streams in the given time interval. The parent plate value is the value of the parent plate, and then the plate values are the values for the plate that ...
python
def print_head(self, parent_plate_value, plate_values, interval, n=10, print_func=logging.info): """ Print the first n values from the streams in the given time interval. The parent plate value is the value of the parent plate, and then the plate values are the values for the plate that ...
[ "def", "print_head", "(", "self", ",", "parent_plate_value", ",", "plate_values", ",", "interval", ",", "n", "=", "10", ",", "print_func", "=", "logging", ".", "info", ")", ":", "if", "isinstance", "(", "plate_values", ",", "Plate", ")", ":", "self", "."...
Print the first n values from the streams in the given time interval. The parent plate value is the value of the parent plate, and then the plate values are the values for the plate that are to be printed. e.g. print_head(None, ("house", "1")) :param parent_plate_value: The (fixed) pare...
[ "Print", "the", "first", "n", "values", "from", "the", "streams", "in", "the", "given", "time", "interval", ".", "The", "parent", "plate", "value", "is", "the", "value", "of", "the", "parent", "plate", "and", "then", "the", "plate", "values", "are", "the...
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/node/node.py#L129-L169
train
Print the first n values from the streams in the given time interval.
astooke/gtimer
gtimer/public/report.py
report
def report(times=None, include_itrs=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted report of the current timing data. Notes: When reporting a collection of parallel subdivisions, only the one with the gre...
python
def report(times=None, include_itrs=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted report of the current timing data. Notes: When reporting a collection of parallel subdivisions, only the one with the gre...
[ "def", "report", "(", "times", "=", "None", ",", "include_itrs", "=", "True", ",", "include_stats", "=", "True", ",", "delim_mode", "=", "False", ",", "format_options", "=", "None", ")", ":", "if", "times", "is", "None", ":", "if", "f", ".", "root", ...
Produce a formatted report of the current timing data. Notes: When reporting a collection of parallel subdivisions, only the one with the greatest total time is reported on, and the rest are ignored (no branching). To compare parallel subdivisions use compare(). Args: times (T...
[ "Produce", "a", "formatted", "report", "of", "the", "current", "timing", "data", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/report.py#L22-L86
train
Produce a formatted report of the current timing data.
astooke/gtimer
gtimer/public/report.py
compare
def compare(times_list=None, name=None, include_list=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted comparison of timing datas. Notes: If no times_list is provided, produces comparison reports on ...
python
def compare(times_list=None, name=None, include_list=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted comparison of timing datas. Notes: If no times_list is provided, produces comparison reports on ...
[ "def", "compare", "(", "times_list", "=", "None", ",", "name", "=", "None", ",", "include_list", "=", "True", ",", "include_stats", "=", "True", ",", "delim_mode", "=", "False", ",", "format_options", "=", "None", ")", ":", "if", "times_list", "is", "Non...
Produce a formatted comparison of timing datas. Notes: If no times_list is provided, produces comparison reports on all parallel subdivisions present at the root level of the current timer. To compare parallel subdivisions at a lower level, get the times data, navigate within it to...
[ "Produce", "a", "formatted", "comparison", "of", "timing", "datas", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/report.py#L89-L155
train
Generates a formatted comparison of the times data of the current timer and the times data of the current root timer.
astooke/gtimer
gtimer/public/report.py
write_structure
def write_structure(times=None): """ Produce a formatted record of a times data structure. Args: times (Times, optional): If not provided, uses the current root timer. Returns: str: Timer tree hierarchy in a formatted string. Raises: TypeError: If provided argument is not ...
python
def write_structure(times=None): """ Produce a formatted record of a times data structure. Args: times (Times, optional): If not provided, uses the current root timer. Returns: str: Timer tree hierarchy in a formatted string. Raises: TypeError: If provided argument is not ...
[ "def", "write_structure", "(", "times", "=", "None", ")", ":", "if", "times", "is", "None", ":", "return", "report_loc", ".", "write_structure", "(", "f", ".", "root", ".", "times", ")", "else", ":", "if", "not", "isinstance", "(", "times", ",", "Times...
Produce a formatted record of a times data structure. Args: times (Times, optional): If not provided, uses the current root timer. Returns: str: Timer tree hierarchy in a formatted string. Raises: TypeError: If provided argument is not a Times object.
[ "Produce", "a", "formatted", "record", "of", "a", "times", "data", "structure", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/report.py#L158-L176
train
Produce a formatted record of a times data structure.
tamasgal/km3pipe
examples/plot_dom_hits.py
filter_muons
def filter_muons(blob): """Write all muons from McTracks to Muons.""" tracks = blob['McTracks'] muons = tracks[tracks.type == -13] # PDG particle code blob["Muons"] = Table(muons) return blob
python
def filter_muons(blob): """Write all muons from McTracks to Muons.""" tracks = blob['McTracks'] muons = tracks[tracks.type == -13] # PDG particle code blob["Muons"] = Table(muons) return blob
[ "def", "filter_muons", "(", "blob", ")", ":", "tracks", "=", "blob", "[", "'McTracks'", "]", "muons", "=", "tracks", "[", "tracks", ".", "type", "==", "-", "13", "]", "# PDG particle code", "blob", "[", "\"Muons\"", "]", "=", "Table", "(", "muons", ")"...
Write all muons from McTracks to Muons.
[ "Write", "all", "muons", "from", "McTracks", "to", "Muons", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/examples/plot_dom_hits.py#L33-L38
train
Write all muons from McTracks to Muons.
aouyar/healthgraph-api
samples/bottle/runkeeper_demo.py
parse_cmdline
def parse_cmdline(argv=None): """Parse command line options. @param argv: List of command line arguments. If None, get list from system. @return: Tuple of Option List and Argument List. """ parser = optparse.OptionParser() parser.add_option('-c', '--conf', help='Configuration file ...
python
def parse_cmdline(argv=None): """Parse command line options. @param argv: List of command line arguments. If None, get list from system. @return: Tuple of Option List and Argument List. """ parser = optparse.OptionParser() parser.add_option('-c', '--conf', help='Configuration file ...
[ "def", "parse_cmdline", "(", "argv", "=", "None", ")", ":", "parser", "=", "optparse", ".", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-c'", ",", "'--conf'", ",", "help", "=", "'Configuration file path.'", ",", "dest", "=", "'confpath'", ...
Parse command line options. @param argv: List of command line arguments. If None, get list from system. @return: Tuple of Option List and Argument List.
[ "Parse", "command", "line", "options", "." ]
fc5135ab353ca1f05e8a70ec784ff921e686c072
https://github.com/aouyar/healthgraph-api/blob/fc5135ab353ca1f05e8a70ec784ff921e686c072/samples/bottle/runkeeper_demo.py#L121-L145
train
Parse command line options.
aouyar/healthgraph-api
samples/bottle/runkeeper_demo.py
parse_conf_files
def parse_conf_files(conf_paths): """Parse the configuration file and return dictionary of configuration options. @param conf_paths: List of configuration file paths to parse. @return: Dictionary of configuration options. """ conf_file = ConfigParser.RawConfigParser() co...
python
def parse_conf_files(conf_paths): """Parse the configuration file and return dictionary of configuration options. @param conf_paths: List of configuration file paths to parse. @return: Dictionary of configuration options. """ conf_file = ConfigParser.RawConfigParser() co...
[ "def", "parse_conf_files", "(", "conf_paths", ")", ":", "conf_file", "=", "ConfigParser", ".", "RawConfigParser", "(", ")", "conf_read", "=", "conf_file", ".", "read", "(", "conf_paths", ")", "conf", "=", "{", "}", "try", ":", "if", "conf_read", ":", "conf...
Parse the configuration file and return dictionary of configuration options. @param conf_paths: List of configuration file paths to parse. @return: Dictionary of configuration options.
[ "Parse", "the", "configuration", "file", "and", "return", "dictionary", "of", "configuration", "options", "." ]
fc5135ab353ca1f05e8a70ec784ff921e686c072
https://github.com/aouyar/healthgraph-api/blob/fc5135ab353ca1f05e8a70ec784ff921e686c072/samples/bottle/runkeeper_demo.py#L148-L175
train
Parse the configuration file and return dictionary of configuration options.
aouyar/healthgraph-api
samples/bottle/runkeeper_demo.py
main
def main(argv=None): """Main Block - Configure and run the Bottle Web Server.""" cmd_opts = parse_cmdline(argv)[0] if cmd_opts.confpath is not None: if os.path.exists(cmd_opts.confpath): conf_paths = [cmd_opts.confpath,] else: return "Configuration file not found: %s"...
python
def main(argv=None): """Main Block - Configure and run the Bottle Web Server.""" cmd_opts = parse_cmdline(argv)[0] if cmd_opts.confpath is not None: if os.path.exists(cmd_opts.confpath): conf_paths = [cmd_opts.confpath,] else: return "Configuration file not found: %s"...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "cmd_opts", "=", "parse_cmdline", "(", "argv", ")", "[", "0", "]", "if", "cmd_opts", ".", "confpath", "is", "not", "None", ":", "if", "os", ".", "path", ".", "exists", "(", "cmd_opts", ".", "confpa...
Main Block - Configure and run the Bottle Web Server.
[ "Main", "Block", "-", "Configure", "and", "run", "the", "Bottle", "Web", "Server", "." ]
fc5135ab353ca1f05e8a70ec784ff921e686c072
https://github.com/aouyar/healthgraph-api/blob/fc5135ab353ca1f05e8a70ec784ff921e686c072/samples/bottle/runkeeper_demo.py#L178-L204
train
Main function - Configure and run the Bottle Web Server.
NaPs/Kolekto
kolekto/helpers.py
get_hash
def get_hash(input_string): """ Return the hash of the movie depending on the input string. If the input string looks like a symbolic link to a movie in a Kolekto tree, return its movies hash, else, return the input directly in lowercase. """ # Check if the input looks like a link to a movie: ...
python
def get_hash(input_string): """ Return the hash of the movie depending on the input string. If the input string looks like a symbolic link to a movie in a Kolekto tree, return its movies hash, else, return the input directly in lowercase. """ # Check if the input looks like a link to a movie: ...
[ "def", "get_hash", "(", "input_string", ")", ":", "# Check if the input looks like a link to a movie:", "if", "os", ".", "path", ".", "islink", "(", "input_string", ")", ":", "directory", ",", "movie_hash", "=", "os", ".", "path", ".", "split", "(", "os", ".",...
Return the hash of the movie depending on the input string. If the input string looks like a symbolic link to a movie in a Kolekto tree, return its movies hash, else, return the input directly in lowercase.
[ "Return", "the", "hash", "of", "the", "movie", "depending", "on", "the", "input", "string", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/helpers.py#L8-L20
train
Return the hash of the movie depending on the input string.
NaPs/Kolekto
kolekto/helpers.py
JsonDbm.get
def get(self, key): """ Get data associated with provided key. """ return self._object_class(json.loads(self._db[key]))
python
def get(self, key): """ Get data associated with provided key. """ return self._object_class(json.loads(self._db[key]))
[ "def", "get", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_object_class", "(", "json", ".", "loads", "(", "self", ".", "_db", "[", "key", "]", ")", ")" ]
Get data associated with provided key.
[ "Get", "data", "associated", "with", "provided", "key", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/helpers.py#L35-L38
train
Get data associated with provided key.
NaPs/Kolekto
kolekto/helpers.py
JsonDbm.save
def save(self, key, data): """ Save data associated with key. """ self._db[key] = json.dumps(data) self._db.sync()
python
def save(self, key, data): """ Save data associated with key. """ self._db[key] = json.dumps(data) self._db.sync()
[ "def", "save", "(", "self", ",", "key", ",", "data", ")", ":", "self", ".", "_db", "[", "key", "]", "=", "json", ".", "dumps", "(", "data", ")", "self", ".", "_db", ".", "sync", "(", ")" ]
Save data associated with key.
[ "Save", "data", "associated", "with", "key", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/helpers.py#L45-L49
train
Save data associated with key.
IRC-SPHERE/HyperStream
hyperstream/meta_data/meta_data_manager.py
MetaDataManager.global_meta_data
def global_meta_data(self): """ Get the global meta data, which will be stored in a tree structure :return: The global meta data """ with switch_db(MetaDataModel, 'hyperstream'): return sorted(map(lambda x: x.to_dict(), MetaDataModel.objects), ...
python
def global_meta_data(self): """ Get the global meta data, which will be stored in a tree structure :return: The global meta data """ with switch_db(MetaDataModel, 'hyperstream'): return sorted(map(lambda x: x.to_dict(), MetaDataModel.objects), ...
[ "def", "global_meta_data", "(", "self", ")", ":", "with", "switch_db", "(", "MetaDataModel", ",", "'hyperstream'", ")", ":", "return", "sorted", "(", "map", "(", "lambda", "x", ":", "x", ".", "to_dict", "(", ")", ",", "MetaDataModel", ".", "objects", ")"...
Get the global meta data, which will be stored in a tree structure :return: The global meta data
[ "Get", "the", "global", "meta", "data", "which", "will", "be", "stored", "in", "a", "tree", "structure" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/meta_data/meta_data_manager.py#L56-L65
train
Get the global meta data for a given resource ID
IRC-SPHERE/HyperStream
hyperstream/meta_data/meta_data_manager.py
MetaDataManager.insert
def insert(self, tag, identifier, parent, data): """ Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier ...
python
def insert(self, tag, identifier, parent, data): """ Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier ...
[ "def", "insert", "(", "self", ",", "tag", ",", "identifier", ",", "parent", ",", "data", ")", ":", "# First try to add it into the tree", "if", "self", ".", "global_plate_definitions", ".", "contains", "(", "identifier", ")", ":", "raise", "KeyError", "(", "\"...
Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier :param data: The data (plate value) :return: None
[ "Insert", "the", "given", "meta", "data", "into", "the", "database" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/meta_data/meta_data_manager.py#L76-L97
train
Insert the given meta data into the database and the global plate definitions.
IRC-SPHERE/HyperStream
hyperstream/meta_data/meta_data_manager.py
MetaDataManager.delete
def delete(self, identifier): """ Delete the meta data with the given identifier from the database :param identifier: The identifier :return: None """ try: node = self.global_plate_definitions[identifier] except NodeIDAbsentError: logging...
python
def delete(self, identifier): """ Delete the meta data with the given identifier from the database :param identifier: The identifier :return: None """ try: node = self.global_plate_definitions[identifier] except NodeIDAbsentError: logging...
[ "def", "delete", "(", "self", ",", "identifier", ")", ":", "try", ":", "node", "=", "self", ".", "global_plate_definitions", "[", "identifier", "]", "except", "NodeIDAbsentError", ":", "logging", ".", "info", "(", "\"Meta data {} not present during deletion\"", "....
Delete the meta data with the given identifier from the database :param identifier: The identifier :return: None
[ "Delete", "the", "meta", "data", "with", "the", "given", "identifier", "from", "the", "database" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/meta_data/meta_data_manager.py#L99-L125
train
Delete the meta data with the given identifier from the database.
PrefPy/prefpy
prefpy/evbwie.py
EMMMixPLAggregator.delta
def delta(x_i, j, s, N): """ delta_i_j_s """ flag = j == EMMMixPLAggregator.c(x_i, s) if flag and s < len(x_i): return 1 elif s == N: found_equal = False for l in range(len(x_i)): if j == EMMMixPLAggregator.c(x_i, l): ...
python
def delta(x_i, j, s, N): """ delta_i_j_s """ flag = j == EMMMixPLAggregator.c(x_i, s) if flag and s < len(x_i): return 1 elif s == N: found_equal = False for l in range(len(x_i)): if j == EMMMixPLAggregator.c(x_i, l): ...
[ "def", "delta", "(", "x_i", ",", "j", ",", "s", ",", "N", ")", ":", "flag", "=", "j", "==", "EMMMixPLAggregator", ".", "c", "(", "x_i", ",", "s", ")", "if", "flag", "and", "s", "<", "len", "(", "x_i", ")", ":", "return", "1", "elif", "s", "...
delta_i_j_s
[ "delta_i_j_s" ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/evbwie.py#L75-L88
train
delta_i_j_s returns 1 if the i j is less than or equal to the s
PrefPy/prefpy
prefpy/evbwie.py
EMMMixPLAggregator.omega
def omega(k, j, z, x): """ omega_k_j """ sum_out = 0 for i in range(len(x)): sum_in = 0 for t in range(len(x[i])): sum_in += z[i][k] * EMMMixPLAggregator.indic(j, x[i], t) sum_out += sum_in return sum_out
python
def omega(k, j, z, x): """ omega_k_j """ sum_out = 0 for i in range(len(x)): sum_in = 0 for t in range(len(x[i])): sum_in += z[i][k] * EMMMixPLAggregator.indic(j, x[i], t) sum_out += sum_in return sum_out
[ "def", "omega", "(", "k", ",", "j", ",", "z", ",", "x", ")", ":", "sum_out", "=", "0", "for", "i", "in", "range", "(", "len", "(", "x", ")", ")", ":", "sum_in", "=", "0", "for", "t", "in", "range", "(", "len", "(", "x", "[", "i", "]", "...
omega_k_j
[ "omega_k_j" ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/evbwie.py#L90-L98
train
omega_k_j
PrefPy/prefpy
prefpy/evbwie.py
EMMMixPLAggregator.aggregate
def aggregate(self, rankings, K, epsilon, epsilon_mm, iters): """ Description: Takes in a set of rankings and computes the model parameters for a mixture of Plackett-Luce models. Parameters: rankings: set of rankings to aggregate K: numb...
python
def aggregate(self, rankings, K, epsilon, epsilon_mm, iters): """ Description: Takes in a set of rankings and computes the model parameters for a mixture of Plackett-Luce models. Parameters: rankings: set of rankings to aggregate K: numb...
[ "def", "aggregate", "(", "self", ",", "rankings", ",", "K", ",", "epsilon", ",", "epsilon_mm", ",", "iters", ")", ":", "x", "=", "rankings", "# shorter pseudonym for voting data", "self", ".", "n", "=", "len", "(", "rankings", ")", "# number of votes", "# \"...
Description: Takes in a set of rankings and computes the model parameters for a mixture of Plackett-Luce models. Parameters: rankings: set of rankings to aggregate K: number of mixture components to compute epsilon: convergence condition ...
[ "Description", ":", "Takes", "in", "a", "set", "of", "rankings", "and", "computes", "the", "model", "parameters", "for", "a", "mixture", "of", "Plackett", "-", "Luce", "models", ".", "Parameters", ":", "rankings", ":", "set", "of", "rankings", "to", "aggre...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/evbwie.py#L100-L202
train
This method computes the model parameters for a mixture of Plackett - Luce models.
PrefPy/prefpy
prefpy/evbwie.py
EMMMixPLAggregator._EStep
def _EStep(self, K, x, z_h1, pi_h, p_h): """ Description: Internal function for computing the E-Step of the EMM algorithm. """ # E-Step: for i in range(self.n): for k in range(K): denom_sum = 0 for k2 in range(K): ...
python
def _EStep(self, K, x, z_h1, pi_h, p_h): """ Description: Internal function for computing the E-Step of the EMM algorithm. """ # E-Step: for i in range(self.n): for k in range(K): denom_sum = 0 for k2 in range(K): ...
[ "def", "_EStep", "(", "self", ",", "K", ",", "x", ",", "z_h1", ",", "pi_h", ",", "p_h", ")", ":", "# E-Step:", "for", "i", "in", "range", "(", "self", ".", "n", ")", ":", "for", "k", "in", "range", "(", "K", ")", ":", "denom_sum", "=", "0", ...
Description: Internal function for computing the E-Step of the EMM algorithm.
[ "Description", ":", "Internal", "function", "for", "computing", "the", "E", "-", "Step", "of", "the", "EMM", "algorithm", "." ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/evbwie.py#L205-L216
train
Internal function for computing the E - Step of the EMM algorithm.