project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
Alexander-Parker/youtube_nlp | options.py | Options.add_experimental_option | add_experimental_option | Adds an experimental option which is passed to chrome. | [
"Adds",
"an",
"experimental",
"option",
"which",
"is",
"passed",
"to",
"chrome."
] | def add_experimental_option(self, name, value):
self._experimental_options[name] = value | ['def', 'add_experimental_option(self,', 'name,', 'value):', 'self._experimental_options[name]', '=', 'value'] | 970,776 |
Alexander-Parker/youtube_nlp | webdriver.py | WebDriver.launch_app | launch_app | Launches Chrome app specified by id. | [
"Launches",
"Chrome",
"app",
"specified",
"by",
"id."
] | def launch_app(self, id):
return self.execute('launchApp', {'id': id}) | ['def', 'launch_app(self,', 'id):', 'return', "self.execute('launchApp',", "{'id':", 'id})'] | 970,781 |
Alexander-Parker/youtube_nlp | alert.py | Alert.text | text | Gets the text of the Alert. | [
"Gets",
"the",
"text",
"of",
"the",
"Alert."
] | def text(self):
if self.driver.w3c:
return self.driver.execute(Command.W3C_GET_ALERT_TEXT)['value']
else:
return self.driver.execute(Command.GET_ALERT_TEXT)['value'] | ['def', 'text(self):', 'if', 'self.driver.w3c:', 'return', "self.driver.execute(Command.W3C_GET_ALERT_TEXT)['value']", 'else:', 'return', "self.driver.execute(Command.GET_ALERT_TEXT)['value']"] | 970,803 |
Alexander-Parker/youtube_nlp | alert.py | Alert.dismiss | dismiss | Dismisses the alert available. | [
"Dismisses",
"the",
"alert",
"available."
] | def dismiss(self):
if self.driver.w3c:
self.driver.execute(Command.W3C_DISMISS_ALERT)
else:
self.driver.execute(Command.DISMISS_ALERT) | ['def', 'dismiss(self):', 'if', 'self.driver.w3c:', 'self.driver.execute(Command.W3C_DISMISS_ALERT)', 'else:', 'self.driver.execute(Command.DISMISS_ALERT)'] | 970,804 |
Alexander-Parker/youtube_nlp | proxy.py | Proxy.proxy_type | proxy_type | Returns proxy type as `ProxyType`. | [
"Returns",
"proxy",
"type",
"as",
"`ProxyType`."
] | def proxy_type(self):
return self.proxyType | ['def', 'proxy_type(self):', 'return', 'self.proxyType'] | 970,807 |
Alexander-Parker/youtube_nlp | proxy.py | Proxy.http_proxy | http_proxy | Returns http proxy setting. | [
"Returns",
"http",
"proxy",
"setting."
] | def http_proxy(self):
return self.httpProxy | ['def', 'http_proxy(self):', 'return', 'self.httpProxy'] | 970,812 |
Alexander-Parker/youtube_nlp | proxy.py | Proxy.socks_proxy | socks_proxy | Returns socks proxy setting. | [
"Returns",
"socks",
"proxy",
"setting."
] | def socks_proxy(self):
return self.socksProxy | ['def', 'socks_proxy(self):', 'return', 'self.socksProxy'] | 970,819 |
Alexander-Parker/youtube_nlp | touch_actions.py | TouchActions.perform | perform | Performs all stored actions. | [
"Performs",
"all",
"stored",
"actions."
] | def perform(self):
for action in self._actions:
action() | ['def', 'perform(self):', 'for', 'action', 'in', 'self._actions:', 'action()'] | 970,828 |
Alexander-Parker/youtube_nlp | utils.py | free_port | free_port | Determines a free port using sockets. | [
"Determines",
"a",
"free",
"port",
"using",
"sockets."
] | def free_port():
free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
free_socket.bind(('0.0.0.0', 0))
free_socket.listen(5)
port = free_socket.getsockname()[1]
free_socket.close()
return port | ['def', 'free_port():', 'free_socket', '=', 'socket.socket(socket.AF_INET,', 'socket.SOCK_STREAM)', "free_socket.bind(('0.0.0.0',", '0))', 'free_socket.listen(5)', 'port', '=', 'free_socket.getsockname()[1]', 'free_socket.close()', 'return', 'port'] | 970,839 |
Alexander-Parker/youtube_nlp | application_cache.py | ApplicationCache.status | status | Returns a current status of application cache. | [
"Returns",
"a",
"current",
"status",
"of",
"application",
"cache."
] | def status(self):
return self.driver.execute(Command.GET_APP_CACHE_STATUS)['value'] | ['def', 'status(self):', 'return', "self.driver.execute(Command.GET_APP_CACHE_STATUS)['value']"] | 970,845 |
Alexander-Parker/youtube_nlp | extension_connection.py | ExtensionConnection.connect | connect | Connects to the extension and retrieves the session id. | [
"Connects",
"to",
"the",
"extension",
"and",
"retrieves",
"the",
"session",
"id."
] | def connect(self):
return self.execute(Command.NEW_SESSION, {'desiredCapabilities': DesiredCapabilities.FIREFOX}) | ['def', 'connect(self):', 'return', 'self.execute(Command.NEW_SESSION,', "{'desiredCapabilities':", 'DesiredCapabilities.FIREFOX})'] | 970,847 |
Alexander-Parker/youtube_nlp | options.py | Options.binary | binary | Sets location of the browser binary, either by string or ``FirefoxBinary`` instance. | [
"Sets",
"location",
"of",
"the",
"browser",
"binary,",
"either",
"by",
"string",
"or",
"``FirefoxBinary``",
"instance."
] | def binary(self, new_binary):
if not isinstance(new_binary, FirefoxBinary):
new_binary = FirefoxBinary(new_binary)
self._binary = new_binary | ['def', 'binary(self,', 'new_binary):', 'if', 'not', 'isinstance(new_binary,', 'FirefoxBinary):', 'new_binary', '=', 'FirefoxBinary(new_binary)', 'self._binary', '=', 'new_binary'] | 970,859 |
Alexander-Parker/youtube_nlp | options.py | Options.binary_location | binary_location | Returns the location of the binary. | [
"Returns",
"the",
"location",
"of",
"the",
"binary."
] | def binary_location(self):
return self.binary._start_cmd | ['def', 'binary_location(self):', 'return', 'self.binary._start_cmd'] | 970,860 |
Alexander-Parker/youtube_nlp | options.py | Options.preferences | preferences | Returns a dict of preferences. | [
"Returns",
"a",
"dict",
"of",
"preferences."
] | def preferences(self):
return self._preferences | ['def', 'preferences(self):', 'return', 'self._preferences'] | 970,862 |
Alexander-Parker/youtube_nlp | options.py | Options.profile | profile | Returns the Firefox profile to use. | [
"Returns",
"the",
"Firefox",
"profile",
"to",
"use."
] | def profile(self):
return self._profile | ['def', 'profile(self):', 'return', 'self._profile'] | 970,864 |
Alexander-Parker/youtube_nlp | options.py | Options.profile | profile | Sets location of the browser profile to use, either by string or ``FirefoxProfile``. | [
"Sets",
"location",
"of",
"the",
"browser",
"profile",
"to",
"use,",
"either",
"by",
"string",
"or",
"``FirefoxProfile``."
] | def profile(self, new_profile):
if not isinstance(new_profile, FirefoxProfile):
new_profile = FirefoxProfile(new_profile)
self._profile = new_profile | ['def', 'profile(self,', 'new_profile):', 'if', 'not', 'isinstance(new_profile,', 'FirefoxProfile):', 'new_profile', '=', 'FirefoxProfile(new_profile)', 'self._profile', '=', 'new_profile'] | 970,865 |
Alexander-Parker/youtube_nlp | webdriver.py | WebDriver.create_web_element | create_web_element | Creates a web element with the specified `element_id`. | [
"Creates",
"a",
"web",
"element",
"with",
"the",
"specified",
"`element_id`."
] | def create_web_element(self, element_id):
return self._web_element_cls(self, element_id, w3c=self.w3c) | ['def', 'create_web_element(self,', 'element_id):', 'return', 'self._web_element_cls(self,', 'element_id,', 'w3c=self.w3c)'] | 970,940 |
Alexander-Parker/youtube_nlp | webelement.py | WebElement.text | text | The text of the element. | [
"The",
"text",
"of",
"the",
"element."
] | def text(self):
return self._execute(Command.GET_ELEMENT_TEXT)['value'] | ['def', 'text(self):', 'return', "self._execute(Command.GET_ELEMENT_TEXT)['value']"] | 971,003 |
Alexander-Parker/youtube_nlp | webelement.py | WebElement.is_enabled | is_enabled | Returns whether the element is enabled. | [
"Returns",
"whether",
"the",
"element",
"is",
"enabled."
] | def is_enabled(self):
return self._execute(Command.IS_ELEMENT_ENABLED)['value'] | ['def', 'is_enabled(self):', 'return', "self._execute(Command.IS_ELEMENT_ENABLED)['value']"] | 971,008 |
Alexander-Parker/youtube_nlp | webelement.py | WebElement.is_displayed | is_displayed | Whether the element is visible to a user. | [
"Whether",
"the",
"element",
"is",
"visible",
"to",
"a",
"user."
] | def is_displayed(self):
if self._w3c:
return self.parent.execute_script('return (%s).apply(null, arguments);' % isDisplayed_js, self)
else:
return self._execute(Command.IS_ELEMENT_DISPLAYED)['value'] | ['def', 'is_displayed(self):', 'if', 'self._w3c:', 'return', "self.parent.execute_script('return", '(%s).apply(null,', "arguments);'", '%', 'isDisplayed_js,', 'self)', 'else:', 'return', "self._execute(Command.IS_ELEMENT_DISPLAYED)['value']"] | 971,026 |
Alexander-Parker/youtube_nlp | webelement.py | WebElement.value_of_css_property | value_of_css_property | The value of a CSS property. | [
"The",
"value",
"of",
"a",
"CSS",
"property."
] | def value_of_css_property(self, property_name):
return self._execute(Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY, {'propertyName': property_name})['value'] | ['def', 'value_of_css_property(self,', 'property_name):', 'return', 'self._execute(Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY,', "{'propertyName':", "property_name})['value']"] | 971,029 |
Alexander-Parker/youtube_nlp | webelement.py | WebElement.parent | parent | Internal reference to the WebDriver instance this element was found from. | [
"Internal",
"reference",
"to",
"the",
"WebDriver",
"instance",
"this",
"element",
"was",
"found",
"from."
] | def parent(self):
return self._parent | ['def', 'parent(self):', 'return', 'self._parent'] | 971,035 |
Alexander-Parker/youtube_nlp | wait.py | WebDriverWait.until | until | Calls the method provided with the driver as an argument until the return value is not False. | [
"Calls",
"the",
"method",
"provided",
"with",
"the",
"driver",
"as",
"an",
"argument",
"until",
"the",
"return",
"value",
"is",
"not",
"False."
] | def until(self, method, message=''):
screen = None
stacktrace = None
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(ex... | ['def', 'until(self,', 'method,', "message=''):", 'screen', '=', 'None', 'stacktrace', '=', 'None', 'end_time', '=', 'time.time()', '+', 'self._timeout', 'while', 'True:', 'try:', 'value', '=', 'method(self._driver)', 'if', 'value:', 'return', 'value', 'except', 'self._ignored_exceptions', 'as', 'exc:', 'screen', '=', ... | 971,053 |
CUNY-CL/yoyodyne | evaluators.py | Evaluator.evaluate | evaluate | Computes the exact word match accuracy. | [
"Computes",
"the",
"exact",
"word",
"match",
"accuracy."
] | def evaluate(self, predictions: torch.Tensor, golds: torch.Tensor, end_idx: int, pad_idx: int) -> EvalItem:
if predictions.size(0) != golds.size(0):
raise Error(f'Preds batch size ({predictions.size(0)}) and golds batch size ({golds.size(0)} do not match')
(_, predictions) = torch.max(predictions, dim=2... | ['def', 'evaluate(self,', 'predictions:', 'torch.Tensor,', 'golds:', 'torch.Tensor,', 'end_idx:', 'int,', 'pad_idx:', 'int)', '->', 'EvalItem:', 'if', 'predictions.size(0)', '!=', 'golds.size(0):', 'raise', "Error(f'Preds", 'batch', 'size', '({predictions.size(0)})', 'and', 'golds', 'batch', 'size', '({golds.size(0)}',... | 971,165 |
gooofy/zbrain | kb_extract_enwiki.py | unwiki | unwiki | Remove wiki markup from the text. | [
"Remove",
"wiki",
"markup",
"from",
"the",
"text."
] | def unwiki(wiki):
wiki = re.sub('(?i) ', ' ', wiki)
wiki = re.sub('(?i)<br[ \\\\]*?>', '\n', wiki)
wiki = re.sub('(?m)<!--.*?--\\s*>', '', wiki)
wiki = re.sub('(?i)<ref[^>]*>[^>]*<\\/ ?ref>', '', wiki)
wiki = re.sub('(?m)<.*?>', '', wiki)
wiki = re.sub('(?i)&', '&', wiki)
wiki = re.... | ['def', 'unwiki(wiki):', 'wiki', '=', "re.sub('(?i) ',", "'", "',", 'wiki)', 'wiki', '=', "re.sub('(?i)<br[", "\\\\\\\\]*?>',", "'\\n',", 'wiki)', 'wiki', '=', "re.sub('(?m)<!--.*?--\\\\s*>',", "'',", 'wiki)', 'wiki', '=', "re.sub('(?i)<ref[^>]*>[^>]*<\\\\/", "?ref>',", "'',", 'wiki)', 'wiki', '=', "re.sub('(?m)<.... | 971,179 |
adamasstokhorst/ZechdB | mathhelper.py | get_factorization | get_factorization | Return list of prime factors of n as well as their multiplicities. | [
"Return",
"list",
"of",
"prime",
"factors",
"of",
"n",
"as",
"well",
"as",
"their",
"multiplicities."
] | def get_factorization(n):
p_list = get_prime_factor(n)
factors = []
for p in p_list:
i = 0
while n % p == 0:
n /= p
i += 1
factors.append((p, i))
return factors | ['def', 'get_factorization(n):', 'p_list', '=', 'get_prime_factor(n)', 'factors', '=', '[]', 'for', 'p', 'in', 'p_list:', 'i', '=', '0', 'while', 'n', '%', 'p', '==', '0:', 'n', '/=', 'p', 'i', '+=', '1', 'factors.append((p,', 'i))', 'return', 'factors'] | 971,183 |
adamasstokhorst/ZechdB | mathhelper.py | factor_str | factor_str | Return factorization of n as a human-readable string. | [
"Return",
"factorization",
"of",
"n",
"as",
"a",
"human-readable",
"string."
] | def factor_str(n):
s = []
for (p, i) in get_factorization(n):
if i == 1:
s.append(str(p))
else:
s.append('{}**{}'.format(p, i))
return ' . '.join(s) | ['def', 'factor_str(n):', 's', '=', '[]', 'for', '(p,', 'i)', 'in', 'get_factorization(n):', 'if', 'i', '==', '1:', 's.append(str(p))', 'else:', "s.append('{}**{}'.format(p,", 'i))', 'return', "'", '.', "'.join(s)"] | 971,184 |
adamasstokhorst/ZechdB | mathhelper.py | gcd | gcd | Greatest common divisor function. | [
"Greatest",
"common",
"divisor",
"function."
] | def gcd(*s):
if len(s) > 1:
return reduce(_gcd, s)
elif len(s) == 0:
return 0
elif type(s[0]) is int or type(s[0]) is long:
return s[0]
elif not s[0]:
return 0
else:
return reduce(_gcd, s[0]) | ['def', 'gcd(*s):', 'if', 'len(s)', '>', '1:', 'return', 'reduce(_gcd,', 's)', 'elif', 'len(s)', '==', '0:', 'return', '0', 'elif', 'type(s[0])', 'is', 'int', 'or', 'type(s[0])', 'is', 'long:', 'return', 's[0]', 'elif', 'not', 's[0]:', 'return', '0', 'else:', 'return', 'reduce(_gcd,', 's[0])'] | 971,185 |
adamasstokhorst/ZechdB | mathhelper.py | lcm | lcm | Least common multiple function. | [
"Least",
"common",
"multiple",
"function."
] | def lcm(*s):
if len(s) > 1:
return reduce(lambda x, y: x * y, s) / gcd(s)
elif len(s) == 0:
return 1
elif type(s[0]) is int or type(s[0]) is long:
return s[0]
elif not s[0]:
return 1
elif len(s[0]) == 1:
return s[0][0]
else:
return reduce(lambda x,... | ['def', 'lcm(*s):', 'if', 'len(s)', '>', '1:', 'return', 'reduce(lambda', 'x,', 'y:', 'x', '*', 'y,', 's)', '/', 'gcd(s)', 'elif', 'len(s)', '==', '0:', 'return', '1', 'elif', 'type(s[0])', 'is', 'int', 'or', 'type(s[0])', 'is', 'long:', 'return', 's[0]', 'elif', 'not', 's[0]:', 'return', '1', 'elif', 'len(s[0])', '=='... | 971,186 |
adamasstokhorst/ZechdB | mathhelper.py | zeros | zeros | Return zero matrix of given size. | [
"Return",
"zero",
"matrix",
"of",
"given",
"size."
] | def zeros(*args):
if len(args) == 1:
return Matrix(args[0], args[0], [0] * args[0] ** 2)
elif len(args) == 2:
return Matrix(args[0], args[1], [0] * (args[0] * args[1]))
else:
return TypeError('Expected 1 or 2 arguments (' + len(args) + ' given') | ['def', 'zeros(*args):', 'if', 'len(args)', '==', '1:', 'return', 'Matrix(args[0],', 'args[0],', '[0]', '*', 'args[0]', '**', '2)', 'elif', 'len(args)', '==', '2:', 'return', 'Matrix(args[0],', 'args[1],', '[0]', '*', '(args[0]', '*', 'args[1]))', 'else:', 'return', "TypeError('Expected", '1', 'or', '2', 'arguments', "... | 971,187 |
veronica320/Zeroshot-Event-Extraction | graph.py | Graph.copy | copy | Make a copy of the graph :return (Graph): a copy of the current graph. | [
"Make",
"a",
"copy",
"of",
"the",
"graph",
":return",
"(Graph):",
"a",
"copy",
"of",
"the",
"current",
"graph."
] | def copy(self):
graph = Graph(triggers=self.triggers.copy(), roles=self.roles.copy(), vocabs=self.vocabs)
graph.graph_local_score = self.graph_local_score
graph.trigger_scores = self.trigger_scores
graph.role_scores = self.role_scores
return graph | ['def', 'copy(self):', 'graph', '=', 'Graph(triggers=self.triggers.copy(),', 'roles=self.roles.copy(),', 'vocabs=self.vocabs)', 'graph.graph_local_score', '=', 'self.graph_local_score', 'graph.trigger_scores', '=', 'self.trigger_scores', 'graph.role_scores', '=', 'self.role_scores', 'return', 'graph'] | 971,237 |
veronica320/Zeroshot-Event-Extraction | model.py | EventDetector.classify_a_trigger | classify_a_trigger | Classify a single trigger. | [
"Classify",
"a",
"single",
"trigger."
] | def classify_a_trigger(self, premise, trigger_text):
result_dict = {}
for event_type in self.trg_subtypes:
label = self.trg_probe_lexicon[event_type]
if self.trg_probe_type == 'topical':
hypothesis = f'This text is about {label}.'
elif self.trg_probe_type in ['natural', 'exis... | ['def', 'classify_a_trigger(self,', 'premise,', 'trigger_text):', 'result_dict', '=', '{}', 'for', 'event_type', 'in', 'self.trg_subtypes:', 'label', '=', 'self.trg_probe_lexicon[event_type]', 'if', 'self.trg_probe_type', '==', "'topical':", 'hypothesis', '=', "f'This", 'text', 'is', 'about', "{label}.'", 'elif', 'self... | 971,242 |
veronica320/Zeroshot-Event-Extraction | model.py | EventDetector.answer_ex | answer_ex | Answers an extractive question. | [
"Answers",
"an",
"extractive",
"question."
] | def answer_ex(self, question, context_tokens):
if context_tokens and len(context_tokens) > 1:
context_tokens[0] = context_tokens[0][0].upper() + context_tokens[0][1:]
question = question[0].upper() + question[1:]
if question[-1] != '?':
question = question + '?'
question_tensor = self.QA... | ['def', 'answer_ex(self,', 'question,', 'context_tokens):', 'if', 'context_tokens', 'and', 'len(context_tokens)', '>', '1:', 'context_tokens[0]', '=', 'context_tokens[0][0].upper()', '+', 'context_tokens[0][1:]', 'question', '=', 'question[0].upper()', '+', 'question[1:]', 'if', 'question[-1]', '!=', "'?':", 'question'... | 971,244 |
veronica320/Zeroshot-Event-Extraction | custom_head_identifier.py | identify_head_custom | identify_head_custom | A coarse-grained head identifier. | [
"A",
"coarse-grained",
"head",
"identifier."
] | def identify_head_custom(dependency_parser, span, tokens, pos_tags):
instance = dependency_parser._dataset_reader.text_to_instance(tokens, pos_tags)
output = dependency_parser.predict_instance(instance)
start_ix = span[0]
root_idx = output['predicted_heads'].index(0)
pos_list = output['pos']
wor... | ['def', 'identify_head_custom(dependency_parser,', 'span,', 'tokens,', 'pos_tags):', 'instance', '=', 'dependency_parser._dataset_reader.text_to_instance(tokens,', 'pos_tags)', 'output', '=', 'dependency_parser.predict_instance(instance)', 'start_ix', '=', 'span[0]', 'root_idx', '=', "output['predicted_heads'].index(0)... | 971,247 |
veronica320/Zeroshot-Event-Extraction | process_ace.py | mask_escape | mask_escape | Replaces escaped characters with rare sequences. | [
"Replaces",
"escaped",
"characters",
"with",
"rare",
"sequences."
] | def mask_escape(text: str) -> str:
return text.replace('&', 'Ã\x92ªÃ\x92ªÃ\x92ªÃ\x92ªÃ\x92ª').replace('<', 'Ã\x92Â\x9aÃ\x92Â\x9aÃ\x92Â\x9aÃ\x92Â\x9a').replace('>', 'Ã\x92ºÃ\x92ºÃ\x92ºÃ\x92º') | ['def', 'mask_escape(text:', 'str)', '->', 'str:', 'return', "text.replace('&',", "'Ã\\x92ªÃ\\x92ªÃ\\x92ªÃ\\x92ªÃ\\x92ª').replace('<',", "'Ã\\x92Â\\x9aÃ\\x92Â\\x9aÃ\\x92Â\\x9aÃ\\x92Â\\x9a').replace('>',", "'Ã\\x92ºÃ\\x92ºÃ\\x92ºÃ\\x92º')"] | 971,248 |
veronica320/Zeroshot-Event-Extraction | process_ere.py | sentence_tokenize | sentence_tokenize | Split a sentence and adds offsets. | [
"Split",
"a",
"sentence",
"and",
"adds",
"offsets."
] | def sentence_tokenize(sentence: Tuple[int, int, str], language: str='english') -> List[Tuple[int, int, str]]:
(start, end, text) = sentence
sents = sent_tokenize(text, language='english')
last = 0
sents_ = []
for sent in sents:
index = text[last:].find(sent)
if index == -1:
... | ['def', 'sentence_tokenize(sentence:', 'Tuple[int,', 'int,', 'str],', 'language:', "str='english')", '->', 'List[Tuple[int,', 'int,', 'str]]:', '(start,', 'end,', 'text)', '=', 'sentence', 'sents', '=', 'sent_tokenize(text,', "language='english')", 'last', '=', '0', 'sents_', '=', '[]', 'for', 'sent', 'in', 'sents:', '... | 971,279 |
veronica320/Zeroshot-Event-Extraction | process_ere.py | process_wrapped_text | process_wrapped_text | Handles wrapped text in some documents by replacing linebreaks between a a pair of <p> and </p> tags with spaces. | [
"Handles",
"wrapped",
"text",
"in",
"some",
"documents",
"by",
"replacing",
"linebreaks",
"between",
"a",
"a",
"pair",
"of",
"<p>",
"and",
"</p>",
"tags",
"with",
"spaces."
] | def process_wrapped_text(text: str) -> str:
segments = text.split('\n')
segments_new = []
in_p = False
for segment in segments:
if in_p:
if segment == '</P>':
segments_new.append(segment)
in_p = False
else:
if segments_new[-... | ['def', 'process_wrapped_text(text:', 'str)', '->', 'str:', 'segments', '=', "text.split('\\n')", 'segments_new', '=', '[]', 'in_p', '=', 'False', 'for', 'segment', 'in', 'segments:', 'if', 'in_p:', 'if', 'segment', '==', "'</P>':", 'segments_new.append(segment)', 'in_p', '=', 'False', 'else:', 'if', 'segments_new[-1]:... | 971,280 |
veronica320/Zeroshot-Event-Extraction | process_ere.py | clean_relations | clean_relations | Cleans relations and assigns them to the corresponding sentence. | [
"Cleans",
"relations",
"and",
"assigns",
"them",
"to",
"the",
"corresponding",
"sentence."
] | def clean_relations(relations: List[Relation], sentence_entities: List[List[Entity]], sentences: List[Tuple[int, int, str]]) -> List[List[Relation]]:
sentence_relations = [[] for _ in range(len(sentences))]
for relation in relations:
keep = False
(entity_id_1, mention_id_1) = (relation.arg1.enti... | ['def', 'clean_relations(relations:', 'List[Relation],', 'sentence_entities:', 'List[List[Entity]],', 'sentences:', 'List[Tuple[int,', 'int,', 'str]])', '->', 'List[List[Relation]]:', 'sentence_relations', '=', '[[]', 'for', '_', 'in', 'range(len(sentences))]', 'for', 'relation', 'in', 'relations:', 'keep', '=', 'False... | 971,285 |
veronica320/Zeroshot-Event-Extraction | process_ere.py | tokenize | tokenize | Tokenizes a sentence and makes sure entity and event spans are compatible with the tokenization result. | [
"Tokenizes",
"a",
"sentence",
"and",
"makes",
"sure",
"entity",
"and",
"event",
"spans",
"are",
"compatible",
"with",
"the",
"tokenization",
"result."
] | def tokenize(sentence: Tuple[int, int, str], entities: List[Entity], events: List[Event], language: str='english') -> List[Tuple[int, int, str]]:
(start, end, text) = sentence
text = mask_escape(text)
splits = {0, len(text)}
for entity in entities:
splits.add(entity.start - start)
splits... | ['def', 'tokenize(sentence:', 'Tuple[int,', 'int,', 'str],', 'entities:', 'List[Entity],', 'events:', 'List[Event],', 'language:', "str='english')", '->', 'List[Tuple[int,', 'int,', 'str]]:', '(start,', 'end,', 'text)', '=', 'sentence', 'text', '=', 'mask_escape(text)', 'splits', '=', '{0,', 'len(text)}', 'for', 'entit... | 971,286 |
veronica320/Zeroshot-Event-Extraction | process_ere.py | extract | extract | Generates a Document object from a text file and an annotation file. | [
"Generates",
"a",
"Document",
"object",
"from",
"a",
"text",
"file",
"and",
"an",
"annotation",
"file."
] | def extract(source_path: str, ere_path: str, doc_id: str, language: str='english', discard_sentences_with_multievent_triggers: bool=True) -> Document:
wrapped = doc_id in WRAPPED_DOCS or (language == 'spanish' and 'newswire' in source_path)
sentences = read_source_file(source_path, language=language, wrapped=wr... | ['def', 'extract(source_path:', 'str,', 'ere_path:', 'str,', 'doc_id:', 'str,', 'language:', "str='english',", 'discard_sentences_with_multievent_triggers:', 'bool=True)', '->', 'Document:', 'wrapped', '=', 'doc_id', 'in', 'WRAPPED_DOCS', 'or', '(language', '==', "'spanish'", 'and', "'newswire'", 'in', 'source_path)', ... | 971,287 |
veronica320/Zeroshot-Event-Extraction | process_ere.py | ere_to_oneie | ere_to_oneie | Converts to OneIE format. | [
"Converts",
"to",
"OneIE",
"format."
] | def ere_to_oneie(input_file: str, output_file: str, tokenizer: PreTrainedTokenizer):
skip_num = 0
with open(input_file, 'r', encoding='utf-8') as r, open(output_file, 'w', encoding='utf-8') as w:
for line in r:
inst = json.loads(line)
tokens = inst['tokens']
pieces = ... | ['def', 'ere_to_oneie(input_file:', 'str,', 'output_file:', 'str,', 'tokenizer:', 'PreTrainedTokenizer):', 'skip_num', '=', '0', 'with', 'open(input_file,', "'r',", "encoding='utf-8')", 'as', 'r,', 'open(output_file,', "'w',", "encoding='utf-8')", 'as', 'w:', 'for', 'line', 'in', 'r:', 'inst', '=', 'json.loads(line)', ... | 971,289 |
veronica320/Zeroshot-Event-Extraction | process_ere.py | ere_to_event_only | ere_to_event_only | Converts to event-only format. | [
"Converts",
"to",
"event-only",
"format."
] | def ere_to_event_only(input_file: str, output_file: str, tokenizer: PreTrainedTokenizer):
print('Converting the dataset to event-only format...')
skip_num = 0
with open(input_file, 'r', encoding='utf-8') as r, open(output_file, 'w', encoding='utf-8') as w:
for line in r:
inst = json.load... | ['def', 'ere_to_event_only(input_file:', 'str,', 'output_file:', 'str,', 'tokenizer:', 'PreTrainedTokenizer):', "print('Converting", 'the', 'dataset', 'to', 'event-only', "format...')", 'skip_num', '=', '0', 'with', 'open(input_file,', "'r',", "encoding='utf-8')", 'as', 'r,', 'open(output_file,', "'w',", "encoding='utf... | 971,290 |
veronica320/Zeroshot-Event-Extraction | process_ere.py | Entity.to_dict | to_dict | Converts instance variables to a dict. | [
"Converts",
"instance",
"variables",
"to",
"a",
"dict."
] | def to_dict(self, sent_id: str=None) -> Dict[str, Any]:
if sent_id:
entity_id = '{}-{}-{}'.format(sent_id, self.entity_id.split('-')[-1], self.mention_id.split('-')[-1])
else:
entity_id = '{}-{}'.format(self.entity_id.split('-')[-1], self.mention_id.split('-')[-1])
return {'entity_id': entit... | ['def', 'to_dict(self,', 'sent_id:', 'str=None)', '->', 'Dict[str,', 'Any]:', 'if', 'sent_id:', 'entity_id', '=', "'{}-{}-{}'.format(sent_id,", "self.entity_id.split('-')[-1],", "self.mention_id.split('-')[-1])", 'else:', 'entity_id', '=', "'{}-{}'.format(self.entity_id.split('-')[-1],", "self.mention_id.split('-')[-1]... | 971,296 |
veronica320/Zeroshot-Event-Extraction | lexicon.py | load_trg_probe_lexicon | load_trg_probe_lexicon | Loads the trigger probe lexicon. | [
"Loads",
"the",
"trigger",
"probe",
"lexicon."
] | def load_trg_probe_lexicon(fr):
lexicon = {}
for line in fr:
line = line.strip()
if line:
if line.isupper():
event_type = line
else:
lexicon[event_type] = line
return lexicon | ['def', 'load_trg_probe_lexicon(fr):', 'lexicon', '=', '{}', 'for', 'line', 'in', 'fr:', 'line', '=', 'line.strip()', 'if', 'line:', 'if', 'line.isupper():', 'event_type', '=', 'line', 'else:', 'lexicon[event_type]', '=', 'line', 'return', 'lexicon'] | 971,303 |
veronica320/Zeroshot-Event-Extraction | span_utils.py | find_lowest_constituent | find_lowest_constituent | Find the lowest constituent above the current trigger. | [
"Find",
"the",
"lowest",
"constituent",
"above",
"the",
"current",
"trigger."
] | def find_lowest_constituent(predictor, trigger_text, sent):
pred = predictor.predict(sentence=sent)
root = pred['hierplane_tree']['root']
cur_node = root
parent_level = 0
level_stack = [[root]]
if_still_child = True
while if_still_child:
if_still_child = False
for node in lev... | ['def', 'find_lowest_constituent(predictor,', 'trigger_text,', 'sent):', 'pred', '=', 'predictor.predict(sentence=sent)', 'root', '=', "pred['hierplane_tree']['root']", 'cur_node', '=', 'root', 'parent_level', '=', '0', 'level_stack', '=', '[[root]]', 'if_still_child', '=', 'True', 'while', 'if_still_child:', 'if_still... | 971,307 |
veronica320/Zeroshot-Event-Extraction | span_utils.py | match_bert_span_to_text | match_bert_span_to_text | Match the predicted bert span to the text in gold context. | [
"Match",
"the",
"predicted",
"bert",
"span",
"to",
"the",
"text",
"in",
"gold",
"context."
] | def match_bert_span_to_text(pred, bertid_2_goldid, question_len, context_tokens):
(answer_start, answer_end) = pred['span']
if (answer_start, answer_end) == (0, 0):
return {'span': None, 'answer': None, 'answer_tokens': None, 'confidence': pred['confidence'], 'start_logit': pred['start_logit'], 'end_log... | ['def', 'match_bert_span_to_text(pred,', 'bertid_2_goldid,', 'question_len,', 'context_tokens):', '(answer_start,', 'answer_end)', '=', "pred['span']", 'if', '(answer_start,', 'answer_end)', '==', '(0,', '0):', 'return', "{'span':", 'None,', "'answer':", 'None,', "'answer_tokens':", 'None,', "'confidence':", "pred['con... | 971,310 |
veronica320/Zeroshot-Event-Extraction | srl.py | load_srl | load_srl | Loads cached SRL predictions for an input file. | [
"Loads",
"cached",
"SRL",
"predictions",
"for",
"an",
"input",
"file."
] | def load_srl(input_file):
(verb_srl_dict, nom_srl_dict) = ({}, {})
if 'ACE' in input_file:
dataset = 'ACE'
elif 'ERE' in input_file:
dataset = 'ERE'
else:
raise ValueError('Unknown dataset')
split = input_file.split('/')[-1].split('.')[0]
for type in ['verb', 'nom']:
... | ['def', 'load_srl(input_file):', '(verb_srl_dict,', 'nom_srl_dict)', '=', '({},', '{})', 'if', "'ACE'", 'in', 'input_file:', 'dataset', '=', "'ACE'", 'elif', "'ERE'", 'in', 'input_file:', 'dataset', '=', "'ERE'", 'else:', 'raise', "ValueError('Unknown", "dataset')", 'split', '=', "input_file.split('/')[-1].split('.')[0... | 971,311 |
veronica320/Zeroshot-Event-Extraction | srl.py | get_srl_result_for_instance | get_srl_result_for_instance | Get SRL output for an instance. | [
"Get",
"SRL",
"output",
"for",
"an",
"instance."
] | def get_srl_result_for_instance(srl_dict, instance):
sent_id = instance.sent_id
tokens_gold = instance.tokens
srl_output = srl_dict[sent_id]
srl_output['words'] = [word for word in srl_output['words'] if word != '\\']
tokens_srl = srl_output['words']
if tokens_srl != tokens_gold:
srl2gol... | ['def', 'get_srl_result_for_instance(srl_dict,', 'instance):', 'sent_id', '=', 'instance.sent_id', 'tokens_gold', '=', 'instance.tokens', 'srl_output', '=', 'srl_dict[sent_id]', "srl_output['words']", '=', '[word', 'for', 'word', 'in', "srl_output['words']", 'if', 'word', '!=', "'\\\\']", 'tokens_srl', '=', "srl_output... | 971,314 |
veronica320/Zeroshot-Event-Extraction | srl.py | get_srl_results | get_srl_results | Get the SRL result, text pieces, token maps for one instance. | [
"Get",
"the",
"SRL",
"result,",
"text",
"pieces,",
"token",
"maps",
"for",
"one",
"instance."
] | def get_srl_results(instance, srl_dicts, stopwords, srl_consts_for_trg):
srl_id_results = {}
text_pieces = {}
trg_cands = {}
srl2gold_maps = []
srl_id = 0
(verb_srl_dict, nom_srl_dict) = srl_dicts
(verb_srl_output, verb_srl2gold) = get_srl_result_for_instance(verb_srl_dict, instance)
(ve... | ['def', 'get_srl_results(instance,', 'srl_dicts,', 'stopwords,', 'srl_consts_for_trg):', 'srl_id_results', '=', '{}', 'text_pieces', '=', '{}', 'trg_cands', '=', '{}', 'srl2gold_maps', '=', '[]', 'srl_id', '=', '0', '(verb_srl_dict,', 'nom_srl_dict)', '=', 'srl_dicts', '(verb_srl_output,', 'verb_srl2gold)', '=', 'get_s... | 971,315 |
andi611/ZeroSpeech-TTS-without-T | eval_tacotron.py | tts | tts | Convert text to speech waveform given a Tacotron model. | [
"Convert",
"text",
"to",
"speech",
"waveform",
"given",
"a",
"Tacotron",
"model."
] | def tts(model, text):
if USE_CUDA:
model = model.cuda()
model.encoder.eval()
model.postnet.eval()
sequence = np.array(text_to_sequence(text))
sequence = Variable(torch.from_numpy(sequence)).unsqueeze(0)
if USE_CUDA:
sequence = sequence.cuda()
(mel_outputs, linear_outputs, gat... | ['def', 'tts(model,', 'text):', 'if', 'USE_CUDA:', 'model', '=', 'model.cuda()', 'model.encoder.eval()', 'model.postnet.eval()', 'sequence', '=', 'np.array(text_to_sequence(text))', 'sequence', '=', 'Variable(torch.from_numpy(sequence)).unsqueeze(0)', 'if', 'USE_CUDA:', 'sequence', '=', 'sequence.cuda()', '(mel_outputs... | 971,324 |
dbash/zerowaste | point_utils.py | get_point_coords_from_point_annotation | get_point_coords_from_point_annotation | Load point coords and their corresponding labels from point annotation. | [
"Load",
"point",
"coords",
"and",
"their",
"corresponding",
"labels",
"from",
"point",
"annotation."
] | def get_point_coords_from_point_annotation(instances):
point_coords_list = []
point_labels_list = []
for instances_per_image in instances:
if len(instances_per_image) == 0:
continue
point_coords = instances_per_image.gt_point_coords.to(torch.float32)
point_labels = instan... | ['def', 'get_point_coords_from_point_annotation(instances):', 'point_coords_list', '=', '[]', 'point_labels_list', '=', '[]', 'for', 'instances_per_image', 'in', 'instances:', 'if', 'len(instances_per_image)', '==', '0:', 'continue', 'point_coords', '=', 'instances_per_image.gt_point_coords.to(torch.float32)', 'point_l... | 971,732 |
dbash/zerowaste | evaluation.py | CausalMetric.single_run | single_run | Run metric on one image-saliency pair. | [
"Run",
"metric",
"on",
"one",
"image-saliency",
"pair."
] | def single_run(self, img_tensor, explanation, verbose=0, save_to=None):
pred = self.model(img_tensor.cuda())
(top, c) = torch.max(pred, 1)
c = c.cpu().numpy()[0]
n_steps = (HW + self.step - 1) // self.step
if self.mode == 'del':
title = 'Deletion game'
ylabel = 'Pixels deleted'
... | ['def', 'single_run(self,', 'img_tensor,', 'explanation,', 'verbose=0,', 'save_to=None):', 'pred', '=', 'self.model(img_tensor.cuda())', '(top,', 'c)', '=', 'torch.max(pred,', '1)', 'c', '=', 'c.cpu().numpy()[0]', 'n_steps', '=', '(HW', '+', 'self.step', '-', '1)', '//', 'self.step', 'if', 'self.mode', '==', "'del':", ... | 971,804 |
nkthiebaut/zeugma | test_embeddings.py | test_model_loading | test_model_loading | Test model loading exceptions raising. | [
"Test",
"model",
"loading",
"exceptions",
"raising."
] | def test_model_loading(sample_corpus_embedding, toy_model_keyed_vectors):
with pytest.raises(TypeError):
EmbeddingTransformer(model=3)
with pytest.raises(KeyError):
EmbeddingTransformer(model='fake_model') | ['def', 'test_model_loading(sample_corpus_embedding,', 'toy_model_keyed_vectors):', 'with', 'pytest.raises(TypeError):', 'EmbeddingTransformer(model=3)', 'with', 'pytest.raises(KeyError):', "EmbeddingTransformer(model='fake_model')"] | 971,813 |
nkthiebaut/zeugma | test_embeddings.py | test_api_model_loading | test_api_model_loading | Test embeddings loaded through the Gensim download API. | [
"Test",
"embeddings",
"loaded",
"through",
"the",
"Gensim",
"download",
"API."
] | def test_api_model_loading(sample_corpus_embedding):
embedder = EmbeddingTransformer(model=list(DEFAULT_PRETRAINED_EMBEDDINGS.keys())[0])
embeddings = embedder.transform(sample_corpus_embedding)
assert embeddings.shape[0] == len(sample_corpus_embedding)
assert np.all(embeddings[1] == embeddings[2])
... | ['def', 'test_api_model_loading(sample_corpus_embedding):', 'embedder', '=', 'EmbeddingTransformer(model=list(DEFAULT_PRETRAINED_EMBEDDINGS.keys())[0])', 'embeddings', '=', 'embedder.transform(sample_corpus_embedding)', 'assert', 'embeddings.shape[0]', '==', 'len(sample_corpus_embedding)', 'assert', 'np.all(embeddings[... | 971,814 |
nkthiebaut/zeugma | test_texttransformers.py | test_text_stats | test_text_stats | Test basic text statistics extraction transformer. | [
"Test",
"basic",
"text",
"statistics",
"extraction",
"transformer."
] | def test_text_stats(sample_corpus):
text_stats = TextStats()
out = text_stats.fit_transform(sample_corpus)
assert out[0]['length'] == len(sample_corpus[0])
assert out[0]['num_sentences'] == 0 | ['def', 'test_text_stats(sample_corpus):', 'text_stats', '=', 'TextStats()', 'out', '=', 'text_stats.fit_transform(sample_corpus)', 'assert', "out[0]['length']", '==', 'len(sample_corpus[0])', 'assert', "out[0]['num_sentences']", '==', '0'] | 971,819 |
nkthiebaut/zeugma | test_texttransformers.py | test_namer | test_namer | Test turning features into mappables. | [
"Test",
"turning",
"features",
"into",
"mappables."
] | def test_namer():
namer = Namer('feature')
out = namer.fit_transform([1, 2, 3])
assert out == {'feature': [1, 2, 3]} | ['def', 'test_namer():', 'namer', '=', "Namer('feature')", 'out', '=', 'namer.fit_transform([1,', '2,', '3])', 'assert', 'out', '==', "{'feature':", '[1,', '2,', '3]}'] | 971,820 |
nkthiebaut/zeugma | embeddings.py | EmbeddingTransformer.transform_sentence | transform_sentence | Compute an aggregate embedding vector for an input str or iterable of str. | [
"Compute",
"an",
"aggregate",
"embedding",
"vector",
"for",
"an",
"input",
"str",
"or",
"iterable",
"of",
"str."
] | def transform_sentence(self, text: Union[Iterable, str]) -> np.array:
def preprocess_text(raw_text: Union[Iterable, str]) -> List[str]:
if not isinstance(raw_text, list):
if not isinstance(raw_text, str):
raise TypeError(f'Input should be a str or a list of str, got {type(raw_te... | ['def', 'transform_sentence(self,', 'text:', 'Union[Iterable,', 'str])', '->', 'np.array:', 'def', 'preprocess_text(raw_text:', 'Union[Iterable,', 'str])', '->', 'List[str]:', 'if', 'not', 'isinstance(raw_text,', 'list):', 'if', 'not', 'isinstance(raw_text,', 'str):', 'raise', "TypeError(f'Input", 'should', 'be', 'a', ... | 971,821 |
zenika-open-source/zevision | server.py | get_status | get_status | Return model status, could be used to track training failures and model update progress. | [
"Return",
"model",
"status,",
"could",
"be",
"used",
"to",
"track",
"training",
"failures",
"and",
"model",
"update",
"progress."
] | def get_status():
app.logger.debug('Getting model status.')
logs = {'failed': os.path.join(LOG_PATH, 'model.failed.json'), 'pending': os.path.join(LOG_PATH, 'model.pending.json'), 'current': os.path.join(LOG_PATH, 'model.json')}
status = {}
for (level, path) in logs.items():
if os.path.exists(pa... | ['def', 'get_status():', "app.logger.debug('Getting", 'model', "status.')", 'logs', '=', "{'failed':", 'os.path.join(LOG_PATH,', "'model.failed.json'),", "'pending':", 'os.path.join(LOG_PATH,', "'model.pending.json'),", "'current':", 'os.path.join(LOG_PATH,', "'model.json')}", 'status', '=', '{}', 'for', '(level,', 'pa... | 971,828 |
zenika-open-source/zevision | server.py | retrain | retrain | Retrain model without any data change. | [
"Retrain",
"model",
"without",
"any",
"data",
"change."
] | def retrain():
app.logger.debug('Retrain the model.')
try:
train_model()
except Exception as e:
return abort('Unable to run model training: %s.' % str(e), 500)
return ('', 204) | ['def', 'retrain():', "app.logger.debug('Retrain", 'the', "model.')", 'try:', 'train_model()', 'except', 'Exception', 'as', 'e:', 'return', "abort('Unable", 'to', 'run', 'model', 'training:', "%s.'", '%', 'str(e),', '500)', 'return', "('',", '204)'] | 971,830 |
zenika-open-source/zevision | server.py | add_category | add_category | Add new categories data to the model. | [
"Add",
"new",
"categories",
"data",
"to",
"the",
"model."
] | def add_category():
file_2_category = {}
existing_categories = _get_categories()
add_categories = []
app.logger.debug('Add category.')
app.logger.debug('Validate categories.json and build file-to-category maps.')
for upload in request.files.getlist('categories'):
try:
meta = ... | ['def', 'add_category():', 'file_2_category', '=', '{}', 'existing_categories', '=', '_get_categories()', 'add_categories', '=', '[]', "app.logger.debug('Add", "category.')", "app.logger.debug('Validate", 'categories.json', 'and', 'build', 'file-to-category', "maps.')", 'for', 'upload', 'in', "request.files.getlist('ca... | 971,831 |
zenika-open-source/zevision | server.py | update_category | update_category | Add new data to an existing category. | [
"Add",
"new",
"data",
"to",
"an",
"existing",
"category."
] | def update_category(category):
app.logger.debug('Update category.')
app.logger.debug('Validate categories.json.')
if not category in _get_categories():
return abort('Unable to locate specified category: %s.' % category, 404)
app.logger.debug('Create backup files.')
category_folder = _get_cat... | ['def', 'update_category(category):', "app.logger.debug('Update", "category.')", "app.logger.debug('Validate", "categories.json.')", 'if', 'not', 'category', 'in', '_get_categories():', 'return', "abort('Unable", 'to', 'locate', 'specified', 'category:', "%s.'", '%', 'category,', '404)', "app.logger.debug('Create", 'ba... | 971,832 |
lartpang/ZoomNet | misc.py | mapping_to_str | mapping_to_str | Print the structural information of the dict. | [
"Print",
"the",
"structural",
"information",
"of",
"the",
"dict."
] | def mapping_to_str(mapping: abc.Mapping, *, prefix: str=' ', lvl: int=0, max_lvl: int=1) -> str:
sub_lvl = lvl + 1
cur_prefix = prefix * lvl
sub_prefix = prefix * sub_lvl
if lvl == max_lvl:
sub_items = str(mapping)
else:
sub_items = ['{']
for (k, v) in mapping.items():
... | ['def', 'mapping_to_str(mapping:', 'abc.Mapping,', '*,', 'prefix:', "str='", "',", 'lvl:', 'int=0,', 'max_lvl:', 'int=1)', '->', 'str:', 'sub_lvl', '=', 'lvl', '+', '1', 'cur_prefix', '=', 'prefix', '*', 'lvl', 'sub_prefix', '=', 'prefix', '*', 'sub_lvl', 'if', 'lvl', '==', 'max_lvl:', 'sub_items', '=', 'str(mapping)',... | 971,846 |
lartpang/ZoomNet | tensor_ops.py | upsample_add | upsample_add | resize xs[:-1] to the size of xs[-1] and add them together. | [
"resize",
"xs[:-1]",
"to",
"the",
"size",
"of",
"xs[-1]",
"and",
"add",
"them",
"together."
] | def upsample_add(*xs: torch.Tensor, interpolation='bilinear', align_corners=False) -> torch.Tensor:
y = xs[-1]
for x in xs[:-1]:
y = y + cus_sample(x, mode='size', factors=y.size()[2:], interpolation=interpolation, align_corners=align_corners)
return y | ['def', 'upsample_add(*xs:', 'torch.Tensor,', "interpolation='bilinear',", 'align_corners=False)', '->', 'torch.Tensor:', 'y', '=', 'xs[-1]', 'for', 'x', 'in', 'xs[:-1]:', 'y', '=', 'y', '+', 'cus_sample(x,', "mode='size',", 'factors=y.size()[2:],', 'interpolation=interpolation,', 'align_corners=align_corners)', 'retur... | 971,853 |
lartpang/ZoomNet | visualize_results.py | plot_results | plot_results | Plot the results conresponding to the batched images based on the `make_grid` method from `torchvision`. | [
"Plot",
"the",
"results",
"conresponding",
"to",
"the",
"batched",
"images",
"based",
"on",
"the",
"`make_grid`",
"method",
"from",
"`torchvision`."
] | def plot_results(data_container, save_path=None):
axes = plt.subplots(nrows=len(data_container), ncols=1)[1].ravel()
plt.subplots_adjust(hspace=0.03, left=0.05, bottom=0.01, right=0.99, top=0.99)
for (subplot_id, (name, data)) in enumerate(data_container.items()):
grid = make_grid(data, nrow=data.sh... | ['def', 'plot_results(data_container,', 'save_path=None):', 'axes', '=', 'plt.subplots(nrows=len(data_container),', 'ncols=1)[1].ravel()', 'plt.subplots_adjust(hspace=0.03,', 'left=0.05,', 'bottom=0.01,', 'right=0.99,', 'top=0.99)', 'for', '(subplot_id,', '(name,', 'data))', 'in', 'enumerate(data_container.items()):', ... | 971,865 |
ZumoLabs/zpy | setup.py | get_requirements_from_file | get_requirements_from_file | Purpose: Get python requirements from a specified requirements file. | [
"Purpose:",
"Get",
"python",
"requirements",
"from",
"a",
"specified",
"requirements",
"file."
] | def get_requirements_from_file(python_requirements_file='./requirements.txt'):
requirements = []
with open(python_requirements_file) as requirements_file:
requirement = requirements_file.readline()
while requirement:
if requirement.strip().startswith('#'):
pass
... | ['def', "get_requirements_from_file(python_requirements_file='./requirements.txt'):", 'requirements', '=', '[]', 'with', 'open(python_requirements_file)', 'as', 'requirements_file:', 'requirement', '=', 'requirements_file.readline()', 'while', 'requirement:', 'if', "requirement.strip().startswith('#'):", 'pass', 'elif'... | 971,866 |
ZumoLabs/zpy | accounts.py | fetch_accounts | fetch_accounts | fetch accounts Fetch accounts from ZumoLabs backend. | [
"fetch",
"accounts",
"Fetch",
"accounts",
"from",
"ZumoLabs",
"backend."
] | def fetch_accounts(filters, url, auth_headers):
endpoint = f'{url}/api/v1/accounts/'
r = requests.get(endpoint, headers=auth_headers, params=filters)
if r.status_code != 200:
r.raise_for_status()
return json.loads(r.text)['results'] | ['def', 'fetch_accounts(filters,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/accounts/'", 'r', '=', 'requests.get(endpoint,', 'headers=auth_headers,', 'params=filters)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'return', "json.loads(r.text)['results']"] | 971,891 |
ZumoLabs/zpy | cli.py | cli | cli | zpy cli Zumo Labs cli which is used to create, get, list, upload objects from the Zumo Labs backend (ragnarok). | [
"zpy",
"cli",
"Zumo",
"Labs",
"cli",
"which",
"is",
"used",
"to",
"create,",
"get,",
"list,",
"upload",
"objects",
"from",
"the",
"Zumo",
"Labs",
"backend",
"(ragnarok)."
] | def cli():
initialize_config() | ['def', 'cli():', 'initialize_config()'] | 971,892 |
ZumoLabs/zpy | cli.py | cli_config | cli_config | display config Display current configuration file to developer. | [
"display",
"config",
"Display",
"current",
"configuration",
"file",
"to",
"developer."
] | def cli_config():
pretty_config = json.dumps(read_config(), indent=2)
click.echo(f'Zpy cli configuration:\n{pretty_config}') | ['def', 'cli_config():', 'pretty_config', '=', 'json.dumps(read_config(),', 'indent=2)', "click.echo(f'Zpy", 'cli', "configuration:\\n{pretty_config}')"] | 971,895 |
ZumoLabs/zpy | cli.py | version | version | version Display the zpy cli version. | [
"version",
"Display",
"the",
"zpy",
"cli",
"version."
] | def version():
import zpy
click.echo(f'Version: {zpy.__version__}') | ['def', 'version():', 'import', 'zpy', "click.echo(f'Version:", "{zpy.__version__}')"] | 971,896 |
ZumoLabs/zpy | cli.py | set_env | set_env | switch target environment This command allows zumo labs developers to swap the endpoint that the cli communicates with. | [
"switch",
"target",
"environment",
"This",
"command",
"allows",
"zumo",
"labs",
"developers",
"to",
"swap",
"the",
"endpoint",
"that",
"the",
"cli",
"communicates",
"with."
] | def set_env(env):
config = read_config()
(old_env, old_endpoint) = (config['ENVIRONMENT'], config['ENDPOINT'])
swap_env(env)
config = read_config()
click.echo('Swapped environment:')
click.echo(f" {old_env} -> {config['ENVIRONMENT']}")
click.echo(f" {old_endpoint} -> {config['ENDPOINT']}")... | ['def', 'set_env(env):', 'config', '=', 'read_config()', '(old_env,', 'old_endpoint)', '=', "(config['ENVIRONMENT'],", "config['ENDPOINT'])", 'swap_env(env)', 'config', '=', 'read_config()', "click.echo('Swapped", "environment:')", 'click.echo(f"', '{old_env}', '->', '{config[\'ENVIRONMENT\']}")', 'click.echo(f"', '{ol... | 971,898 |
ZumoLabs/zpy | cli.py | clear_project | clear_project | Clear project Clear global PROJECT uuid. | [
"Clear",
"project",
"Clear",
"global",
"PROJECT",
"uuid."
] | def clear_project():
config = read_config()
config.pop('PROJECT')
write_config(config)
click.echo('Cleared global project namespace.') | ['def', 'clear_project():', 'config', '=', 'read_config()', "config.pop('PROJECT')", 'write_config(config)', "click.echo('Cleared", 'global', 'project', "namespace.')"] | 971,909 |
ZumoLabs/zpy | cli.py | list_accounts | list_accounts | list accounts List accounts from backend with optional FILTERS. | [
"list",
"accounts",
"List",
"accounts",
"from",
"backend",
"with",
"optional",
"FILTERS."
] | def list_accounts(filters):
from cli.accounts import fetch_accounts
try:
filters = parse_args(filters)
except Exception:
click.secho(f'Failed to parse filters: {filters}', fg='yellow', err=True)
return
try:
with Loader('Fetching accounts...'):
accounts = fetch... | ['def', 'list_accounts(filters):', 'from', 'cli.accounts', 'import', 'fetch_accounts', 'try:', 'filters', '=', 'parse_args(filters)', 'except', 'Exception:', "click.secho(f'Failed", 'to', 'parse', 'filters:', "{filters}',", "fg='yellow',", 'err=True)', 'return', 'try:', 'with', "Loader('Fetching", "accounts...'):", 'ac... | 971,915 |
ZumoLabs/zpy | config.py | write_config | write_config | write config Write zpy cli configuration file. | [
"write",
"config",
"Write",
"zpy",
"cli",
"configuration",
"file."
] | def write_config(config, file=CONFIG_FILE):
path = to_pathlib_path(os.path.expanduser(file))
with path.open('w') as f:
yaml.dump(config, f) | ['def', 'write_config(config,', 'file=CONFIG_FILE):', 'path', '=', 'to_pathlib_path(os.path.expanduser(file))', 'with', "path.open('w')", 'as', 'f:', 'yaml.dump(config,', 'f)'] | 971,924 |
ZumoLabs/zpy | config.py | swap_env | swap_env | swap environment Swap the current environment configuration. | [
"swap",
"environment",
"Swap",
"the",
"current",
"environment",
"configuration."
] | def swap_env(name):
old_config = read_config()
new_config = read_config(file=f'~/.zpy/{name}.yaml')
write_config(new_config)
write_config(old_config, file=f"~/.zpy/{old_config['ENVIRONMENT']}.yaml") | ['def', 'swap_env(name):', 'old_config', '=', 'read_config()', 'new_config', '=', "read_config(file=f'~/.zpy/{name}.yaml')", 'write_config(new_config)', 'write_config(old_config,', 'file=f"~/.zpy/{old_config[\'ENVIRONMENT\']}.yaml")'] | 971,926 |
ZumoLabs/zpy | datasets.py | download_dataset | download_dataset | download dataset Download dataset object from S3 through ZumoLabs backend. | [
"download",
"dataset",
"Download",
"dataset",
"object",
"from",
"S3",
"through",
"ZumoLabs",
"backend."
] | def download_dataset(name, path, url, auth_headers):
dataset = fetch_dataset(name)
endpoint = f"{url}/api/v1/datasets/{dataset['id']}/download/"
r = requests.get(endpoint, headers=auth_headers)
if r.status_code != 200:
r.raise_for_status()
dataset = json.loads(r.text)
name_slug = f"{name... | ['def', 'download_dataset(name,', 'path,', 'url,', 'auth_headers):', 'dataset', '=', 'fetch_dataset(name)', 'endpoint', '=', 'f"{url}/api/v1/datasets/{dataset[\'id\']}/download/"', 'r', '=', 'requests.get(endpoint,', 'headers=auth_headers)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'dataset', '=', '... | 971,929 |
ZumoLabs/zpy | datasets.py | fetch_dataset | fetch_dataset | fetch dataset Fetch info on a dataset by name from backend. | [
"fetch",
"dataset",
"Fetch",
"info",
"on",
"a",
"dataset",
"by",
"name",
"from",
"backend."
] | def fetch_dataset(name, url, auth_headers):
endpoint = f'{url}/api/v1/datasets/'
r = requests.get(endpoint, params={'name': name}, headers=auth_headers)
if r.status_code != 200:
r.raise_for_status()
response = json.loads(r.text)
if response['count'] != 1:
raise NameError(f"found {res... | ['def', 'fetch_dataset(name,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/datasets/'", 'r', '=', 'requests.get(endpoint,', "params={'name':", 'name},', 'headers=auth_headers)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'response', '=', 'json.loads(r.text)', 'if', "response['count']", ... | 971,931 |
ZumoLabs/zpy | logs.py | fetch_logs | fetch_logs | fetch logs Fetch LOG_TYPES for a backend run. | [
"fetch",
"logs",
"Fetch",
"LOG_TYPES",
"for",
"a",
"backend",
"run."
] | def fetch_logs(resource, name, path, url, auth_headers):
endpoint = f'{url}/api/v1/{resource}/'
r = requests.get(endpoint, params={'name': name}, headers=auth_headers)
if r.status_code != 200:
r.raise_for_status()
response = json.loads(r.text)
if response['count'] != 1:
raise NameErr... | ['def', 'fetch_logs(resource,', 'name,', 'path,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/{resource}/'", 'r', '=', 'requests.get(endpoint,', "params={'name':", 'name},', 'headers=auth_headers)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'response', '=', 'json.loads(r.text)', 'if', ... | 971,935 |
ZumoLabs/zpy | projects.py | create_project | create_project | create project Create empty project on ZumoLabs backend. | [
"create",
"project",
"Create",
"empty",
"project",
"on",
"ZumoLabs",
"backend."
] | def create_project(account_id, name, url, auth_headers):
endpoint = f'{url}/api/v1/projects/'
r = requests.post(endpoint, data={'account': account_id, 'name': name}, headers=auth_headers)
if r.status_code != 201:
r.raise_for_status() | ['def', 'create_project(account_id,', 'name,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/projects/'", 'r', '=', 'requests.post(endpoint,', "data={'account':", 'account_id,', "'name':", 'name},', 'headers=auth_headers)', 'if', 'r.status_code', '!=', '201:', 'r.raise_for_status()'] | 971,937 |
ZumoLabs/zpy | sims.py | fetch_sim | fetch_sim | fetch sim Fetch info on a sim by name from backend. | [
"fetch",
"sim",
"Fetch",
"info",
"on",
"a",
"sim",
"by",
"name",
"from",
"backend."
] | def fetch_sim(name, project, url, auth_headers):
endpoint = f'{url}/api/v1/sims/'
r = requests.get(endpoint, params={'name': name, 'project': project}, headers=auth_headers)
if r.status_code != 200:
r.raise_for_status()
response = json.loads(r.text)
return response['results'][0] | ['def', 'fetch_sim(name,', 'project,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/sims/'", 'r', '=', 'requests.get(endpoint,', "params={'name':", 'name,', "'project':", 'project},', 'headers=auth_headers)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'response', '=', 'json.loads(r.text)... | 971,938 |
ZumoLabs/zpy | sims.py | create_sim | create_sim | create sim Upload sim object to S3 through ZumoLabs backend and create the sim object. | [
"create",
"sim",
"Upload",
"sim",
"object",
"to",
"S3",
"through",
"ZumoLabs",
"backend",
"and",
"create",
"the",
"sim",
"object."
] | def create_sim(name, path, project, url, auth_headers):
endpoint = f'{url}/api/v1/sims/'
r = requests.post(endpoint, data={'name': name, 'project': project}, files={'file': open(path, 'rb')}, headers=auth_headers)
if r.status_code != 201:
r.raise_for_status() | ['def', 'create_sim(name,', 'path,', 'project,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/sims/'", 'r', '=', 'requests.post(endpoint,', "data={'name':", 'name,', "'project':", 'project},', "files={'file':", 'open(path,', "'rb')},", 'headers=auth_headers)', 'if', 'r.status_code', '!=', '201:', 'r.raise... | 971,939 |
ZumoLabs/zpy | sims.py | fetch_sims | fetch_sims | fetch sims Fetch sim objects from ZumoLabs backend. | [
"fetch",
"sims",
"Fetch",
"sim",
"objects",
"from",
"ZumoLabs",
"backend."
] | def fetch_sims(filters, url, auth_headers):
endpoint = f'{url}/api/v1/sims/'
r = requests.get(endpoint, headers=auth_headers, params=filters)
if r.status_code != 200:
r.raise_for_status()
return json.loads(r.text)['results'] | ['def', 'fetch_sims(filters,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/sims/'", 'r', '=', 'requests.get(endpoint,', 'headers=auth_headers,', 'params=filters)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'return', "json.loads(r.text)['results']"] | 971,941 |
ZumoLabs/zpy | transforms.py | fetch_transforms | fetch_transforms | fetch transforms Fetch transform objects from ZumoLabs backend. | [
"fetch",
"transforms",
"Fetch",
"transform",
"objects",
"from",
"ZumoLabs",
"backend."
] | def fetch_transforms(filters, url, auth_headers):
endpoint = f'{url}/api/v1/transforms/'
r = requests.get(endpoint, headers=auth_headers, params=filters)
if r.status_code != 200:
r.raise_for_status()
return json.loads(r.text)['results'] | ['def', 'fetch_transforms(filters,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/transforms/'", 'r', '=', 'requests.get(endpoint,', 'headers=auth_headers,', 'params=filters)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'return', "json.loads(r.text)['results']"] | 971,943 |
ZumoLabs/zpy | transforms.py | available_transforms | available_transforms | available transforms List all transforms available on the backend. | [
"available",
"transforms",
"List",
"all",
"transforms",
"available",
"on",
"the",
"backend."
] | def available_transforms(url, auth_headers):
endpoint = f'{url}/api/v1/transforms/available/'
r = requests.get(endpoint, headers=auth_headers)
if r.status_code != 200:
r.raise_for_status()
return json.loads(r.text) | ['def', 'available_transforms(url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/transforms/available/'", 'r', '=', 'requests.get(endpoint,', 'headers=auth_headers)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'return', 'json.loads(r.text)'] | 971,944 |
ZumoLabs/zpy | utils.py | download_url | download_url | download url Download from url to give output path and visualize using tqdm. | [
"download",
"url",
"Download",
"from",
"url",
"to",
"give",
"output",
"path",
"and",
"visualize",
"using",
"tqdm."
] | def download_url(url: str, output_path: Union[Path, str]):
u = urlopen(url)
h = u.info()
totalSize = int(h['Content-Length'])
fp = open(output_path, 'wb')
blockSize = 8192
with tqdm(total=totalSize) as pbar:
while True:
chunk = u.read(blockSize)
if not chunk:
... | ['def', 'download_url(url:', 'str,', 'output_path:', 'Union[Path,', 'str]):', 'u', '=', 'urlopen(url)', 'h', '=', 'u.info()', 'totalSize', '=', "int(h['Content-Length'])", 'fp', '=', 'open(output_path,', "'wb')", 'blockSize', '=', '8192', 'with', 'tqdm(total=totalSize)', 'as', 'pbar:', 'while', 'True:', 'chunk', '=', '... | 971,948 |
ZumoLabs/zpy | utils.py | fetch_auth | fetch_auth | fetch authentication Decorator to wrap functions providing the backend url and the correct authorization headers for requests. | [
"fetch",
"authentication",
"Decorator",
"to",
"wrap",
"functions",
"providing",
"the",
"backend",
"url",
"and",
"the",
"correct",
"authorization",
"headers",
"for",
"requests."
] | def fetch_auth(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
config = read_config()
endpoint = config['ENDPOINT']
auth_header = {'Authorization': 'token {}'.format(config['TOKEN'])}
return func(*args, **kwargs, url=endpoint, auth_headers=auth_header)
return wra... | ['def', 'fetch_auth(func):', '@functools.wraps(func)', 'def', 'wrapper(*args,', '**kwargs):', 'config', '=', 'read_config()', 'endpoint', '=', "config['ENDPOINT']", 'auth_header', '=', "{'Authorization':", "'token", "{}'.format(config['TOKEN'])}", 'return', 'func(*args,', '**kwargs,', 'url=endpoint,', 'auth_headers=aut... | 971,949 |
ZumoLabs/zpy | utils.py | print_list_as_columns | print_list_as_columns | Format and echo a list of strings into nicely formatted columns. | [
"Format",
"and",
"echo",
"a",
"list",
"of",
"strings",
"into",
"nicely",
"formatted",
"columns."
] | def print_list_as_columns(list_of_strings, num_cols=5, indent_prefix=' '):
count = len(list_of_strings)
col_width = max((len(string) for string in list_of_strings))
num_rows = math.ceil(count / num_cols)
for i in range(num_rows):
start_index = i * num_cols
end_index = (i + 1) * num_co... | ['def', 'print_list_as_columns(list_of_strings,', 'num_cols=5,', "indent_prefix='", "'):", 'count', '=', 'len(list_of_strings)', 'col_width', '=', 'max((len(string)', 'for', 'string', 'in', 'list_of_strings))', 'num_rows', '=', 'math.ceil(count', '/', 'num_cols)', 'for', 'i', 'in', 'range(num_rows):', 'start_index', '=... | 971,950 |
ZumoLabs/zpy | blender.py | step | step | Steps the sim forward (Blender frames). | [
"Steps",
"the",
"sim",
"forward",
"(Blender",
"frames)."
] | def step(num_steps: int=3, framerate: int=1, start_frame: int=1, refresh_ui: bool=False) -> int:
assert num_steps is not None, 'Invalid num_steps'
assert num_steps > 0, 'Invalid num_steps'
scene = zpy.blender.verify_blender_scene()
step_idx = 0
if framerate > 0:
start = scene.frame_start
... | ['def', 'step(num_steps:', 'int=3,', 'framerate:', 'int=1,', 'start_frame:', 'int=1,', 'refresh_ui:', 'bool=False)', '->', 'int:', 'assert', 'num_steps', 'is', 'not', 'None,', "'Invalid", "num_steps'", 'assert', 'num_steps', '>', '0,', "'Invalid", "num_steps'", 'scene', '=', 'zpy.blender.verify_blender_scene()', 'step_... | 971,963 |
ZumoLabs/zpy | blender.py | verify_blender_scene | verify_blender_scene | Get and set the scene in Blender. | [
"Get",
"and",
"set",
"the",
"scene",
"in",
"Blender."
] | def verify_blender_scene(blender_scene_name: str='Scene') -> bpy.types.Scene:
scene = bpy.data.scenes.get(blender_scene_name, None)
if scene is None:
log.debug(f'Could not find scene {blender_scene_name}')
scene = bpy.data.scenes[0]
log.debug(f'Setting scene to {scene.name}')
bpy.context... | ['def', 'verify_blender_scene(blender_scene_name:', "str='Scene')", '->', 'bpy.types.Scene:', 'scene', '=', 'bpy.data.scenes.get(blender_scene_name,', 'None)', 'if', 'scene', 'is', 'None:', "log.debug(f'Could", 'not', 'find', 'scene', "{blender_scene_name}')", 'scene', '=', 'bpy.data.scenes[0]', "log.debug(f'Setting", ... | 971,965 |
ZumoLabs/zpy | blender.py | parse_config | parse_config | Parses the gin config text in Blender. | [
"Parses",
"the",
"gin",
"config",
"text",
"in",
"Blender."
] | def parse_config(text_name: str='config') -> None:
_text = bpy.data.texts.get(text_name, None)
if _text is None:
log.warning(f'Could not find {text_name} in texts.')
return
log.info(f'Loading gin config {text_name}')
gin.enter_interactive_mode()
with gin.unlock_config():
gin.... | ['def', 'parse_config(text_name:', "str='config')", '->', 'None:', '_text', '=', 'bpy.data.texts.get(text_name,', 'None)', 'if', '_text', 'is', 'None:', "log.warning(f'Could", 'not', 'find', '{text_name}', 'in', "texts.')", 'return', "log.info(f'Loading", 'gin', 'config', "{text_name}')", 'gin.enter_interactive_mode()'... | 971,966 |
ZumoLabs/zpy | blender.py | save_and_revert | save_and_revert | Decorator for saving blenderfile before execution, and reverting after execution. | [
"Decorator",
"for",
"saving",
"blenderfile",
"before",
"execution,",
"and",
"reverting",
"after",
"execution."
] | def save_and_revert(_func):
@wraps(_func)
def wrapped_func(*args, **kwargs) -> None:
log.info('Saving the sim.')
bpy.ops.wm.save_mainfile()
try:
_func(*args, **kwargs)
except Exception as e:
log.error(f'Executing {_func.__name__} failed with exception {e}... | ['def', 'save_and_revert(_func):', '@wraps(_func)', 'def', 'wrapped_func(*args,', '**kwargs)', '->', 'None:', "log.info('Saving", 'the', "sim.')", 'bpy.ops.wm.save_mainfile()', 'try:', '_func(*args,', '**kwargs)', 'except', 'Exception', 'as', 'e:', "log.error(f'Executing", '{_func.__name__}', 'failed', 'with', 'excepti... | 971,967 |
ZumoLabs/zpy | blender.py | connect_addon | connect_addon | Connects a Blender Addon. | [
"Connects",
"a",
"Blender",
"Addon."
] | def connect_addon(name: str='zpy_addon', addon_dir: Union[Path, str]='$BLENDERADDONS') -> None:
log.debug(f'Connecting Addon {name}.')
path = f'$BLENDERADDONS/{name}/__init__.py'
path = zpy.files.verify_path(path, make=False)
bpy.ops.preferences.addon_install(filepath=str(path))
bpy.ops.preferences.... | ['def', 'connect_addon(name:', "str='zpy_addon',", 'addon_dir:', 'Union[Path,', "str]='$BLENDERADDONS')", '->', 'None:', "log.debug(f'Connecting", 'Addon', "{name}.')", 'path', '=', "f'$BLENDERADDONS/{name}/__init__.py'", 'path', '=', 'zpy.files.verify_path(path,', 'make=False)', 'bpy.ops.preferences.addon_install(file... | 971,969 |
ZumoLabs/zpy | camera.py | is_child_hit | is_child_hit | Recursive function to check if a child object is the hit object. | [
"Recursive",
"function",
"to",
"check",
"if",
"a",
"child",
"object",
"is",
"the",
"hit",
"object."
] | def is_child_hit(obj: Union[bpy.types.Object, str], hit_obj: Union[bpy.types.Object, str]) -> bool:
obj = zpy.objects.verify(obj)
hit_obj = zpy.objects.verify(hit_obj)
if obj == hit_obj:
return True
else:
for child in obj.children:
if is_child_hit(child, hit_obj):
... | ['def', 'is_child_hit(obj:', 'Union[bpy.types.Object,', 'str],', 'hit_obj:', 'Union[bpy.types.Object,', 'str])', '->', 'bool:', 'obj', '=', 'zpy.objects.verify(obj)', 'hit_obj', '=', 'zpy.objects.verify(hit_obj)', 'if', 'obj', '==', 'hit_obj:', 'return', 'True', 'else:', 'for', 'child', 'in', 'obj.children:', 'if', 'is... | 971,979 |
ZumoLabs/zpy | camera.py | is_visible | is_visible | Cast a ray to determine if object is visible from camera. | [
"Cast",
"a",
"ray",
"to",
"determine",
"if",
"object",
"is",
"visible",
"from",
"camera."
] | def is_visible(location: Union[Tuple[float], mathutils.Vector], obj_to_hit: Union[bpy.types.Object, str], camera: Union[bpy.types.Object, bpy.types.Camera, str]=None) -> bool:
camera = zpy.camera.verify(camera)
obj_to_hit = zpy.objects.verify(obj_to_hit)
if not isinstance(location, mathutils.Vector):
... | ['def', 'is_visible(location:', 'Union[Tuple[float],', 'mathutils.Vector],', 'obj_to_hit:', 'Union[bpy.types.Object,', 'str],', 'camera:', 'Union[bpy.types.Object,', 'bpy.types.Camera,', 'str]=None)', '->', 'bool:', 'camera', '=', 'zpy.camera.verify(camera)', 'obj_to_hit', '=', 'zpy.objects.verify(obj_to_hit)', 'if', '... | 971,980 |
ZumoLabs/zpy | camera.py | is_in_view | is_in_view | Is a location visible from a camera (within some epsilon). | [
"Is",
"a",
"location",
"visible",
"from",
"a",
"camera",
"(within",
"some",
"epsilon)."
] | def is_in_view(location: Union[Tuple[float], mathutils.Vector], camera: Union[bpy.types.Object, bpy.types.Camera, str]=None, epsilon: float=0.05) -> bool:
camera = zpy.camera.verify(camera)
if not isinstance(location, mathutils.Vector):
location = mathutils.Vector(location)
(x, y, z) = camera_xyz(lo... | ['def', 'is_in_view(location:', 'Union[Tuple[float],', 'mathutils.Vector],', 'camera:', 'Union[bpy.types.Object,', 'bpy.types.Camera,', 'str]=None,', 'epsilon:', 'float=0.05)', '->', 'bool:', 'camera', '=', 'zpy.camera.verify(camera)', 'if', 'not', 'isinstance(location,', 'mathutils.Vector):', 'location', '=', 'mathuti... | 971,981 |
ZumoLabs/zpy | client.py | preview | preview | Generate a preview of output data for a given DatasetConfig. | [
"Generate",
"a",
"preview",
"of",
"output",
"data",
"for",
"a",
"given",
"DatasetConfig."
] | def preview(dataset_config: DatasetConfig, num_samples=10):
print(f'Generating preview:')
config_filters = {} if is_empty(dataset_config.config) else {'config': to_query_param_value(dataset_config.config)}
filter_params = {'project': _project['id'], 'sim': dataset_config.sim['id'], 'state': 'READY', 'page-s... | ['def', 'preview(dataset_config:', 'DatasetConfig,', 'num_samples=10):', "print(f'Generating", "preview:')", 'config_filters', '=', '{}', 'if', 'is_empty(dataset_config.config)', 'else', "{'config':", 'to_query_param_value(dataset_config.config)}', 'filter_params', '=', "{'project':", "_project['id'],", "'sim':", "data... | 971,983 |
ZumoLabs/zpy | client.py | DatasetConfig.config | config | A dict representing a json object of gin config parameters. | [
"A",
"dict",
"representing",
"a",
"json",
"object",
"of",
"gin",
"config",
"parameters."
] | def config(self):
return self._config | ['def', 'config(self):', 'return', 'self._config'] | 971,984 |
ZumoLabs/zpy | client.py | DatasetConfig.set | set | Set a value for a configurable parameter. | [
"Set",
"a",
"value",
"for",
"a",
"configurable",
"parameter."
] | def set(self, path: str, value: any):
set_(self._config, path, value) | ['def', 'set(self,', 'path:', 'str,', 'value:', 'any):', 'set_(self._config,', 'path,', 'value)'] | 971,985 |
ZumoLabs/zpy | client.py | DatasetConfig.unset | unset | Remove a configurable parameter. | [
"Remove",
"a",
"configurable",
"parameter."
] | def unset(self, path):
unset(self._config, path) | ['def', 'unset(self,', 'path):', 'unset(self._config,', 'path)'] | 971,986 |
ZumoLabs/zpy | color.py | hex_to_irgb | hex_to_irgb | Convert hex value to integer rgb (0 to 255). | [
"Convert",
"hex",
"value",
"to",
"integer",
"rgb",
"(0",
"to",
"255)."
] | def hex_to_irgb(hex_value: str) -> Tuple[int]:
hex_value = int(hex_value[1:], 16)
b = hex_value & 255
g = hex_value >> 8 & 255
r = hex_value >> 16 & 255
return (r, g, b) | ['def', 'hex_to_irgb(hex_value:', 'str)', '->', 'Tuple[int]:', 'hex_value', '=', 'int(hex_value[1:],', '16)', 'b', '=', 'hex_value', '&', '255', 'g', '=', 'hex_value', '>>', '8', '&', '255', 'r', '=', 'hex_value', '>>', '16', '&', '255', 'return', '(r,', 'g,', 'b)'] | 971,996 |
ZumoLabs/zpy | color.py | hex_to_frgb | hex_to_frgb | Convert hex value to float rgb (0 to 1). | [
"Convert",
"hex",
"value",
"to",
"float",
"rgb",
"(0",
"to",
"1)."
] | def hex_to_frgb(hex_value: str) -> Tuple[float]:
return irgb_to_frgb(hex_to_irgb(hex_value)) | ['def', 'hex_to_frgb(hex_value:', 'str)', '->', 'Tuple[float]:', 'return', 'irgb_to_frgb(hex_to_irgb(hex_value))'] | 971,998 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.