hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fdc45c3e5bc671f098e4530eaf326692dfbc53ff | xlrtx/JsonAnalysis | src/json_analysis.py | [
"MIT"
] | Python | merge_list | <not_specific> | def merge_list(this, other, cb, comp=lambda o: type(o)):
"""
Merge two lists by their children's type,
for each given list, their children must be unique in type.
:param this:
:param other:
:param cb:
:param comp: a function to get children's type, defaults to type()
:return:
"""
... |
Merge two lists by their children's type,
for each given list, their children must be unique in type.
:param this:
:param other:
:param cb:
:param comp: a function to get children's type, defaults to type()
:return:
| Merge two lists by their children's type,
for each given list, their children must be unique in type. | [
"Merge",
"two",
"lists",
"by",
"their",
"children",
"'",
"s",
"type",
"for",
"each",
"given",
"list",
"their",
"children",
"must",
"be",
"unique",
"in",
"type",
"."
] | def merge_list(this, other, cb, comp=lambda o: type(o)):
result = []
dict_this = list_to_dict(this, comp)
dict_other = list_to_dict(other, comp)
ret = merge_dict(dict_this, dict_other, cb)
for value in ret.values():
result.append(value)
return result | [
"def",
"merge_list",
"(",
"this",
",",
"other",
",",
"cb",
",",
"comp",
"=",
"lambda",
"o",
":",
"type",
"(",
"o",
")",
")",
":",
"result",
"=",
"[",
"]",
"dict_this",
"=",
"list_to_dict",
"(",
"this",
",",
"comp",
")",
"dict_other",
"=",
"list_to_... | Merge two lists by their children's type,
for each given list, their children must be unique in type. | [
"Merge",
"two",
"lists",
"by",
"their",
"children",
"'",
"s",
"type",
"for",
"each",
"given",
"list",
"their",
"children",
"must",
"be",
"unique",
"in",
"type",
"."
] | [
"\"\"\"\n Merge two lists by their children's type,\n for each given list, their children must be unique in type.\n :param this:\n :param other:\n :param cb:\n :param comp: a function to get children's type, defaults to type()\n :return:\n \"\"\"",
"# assert isinstance(this, list)",
"# a... | [
{
"param": "this",
"type": null
},
{
"param": "other",
"type": null
},
{
"param": "cb",
"type": null
},
{
"param": "comp",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "this",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
... |
fdc45c3e5bc671f098e4530eaf326692dfbc53ff | xlrtx/JsonAnalysis | src/json_analysis.py | [
"MIT"
] | Python | flat_vars | <not_specific> | def flat_vars(doc):
"""
Flat given nested dict, but keep the last layer of dict object unchanged.
:param doc: nested dict object, consisted solely by dict objects.
:return: flattened dict, with only last layer of dict un-flattened.
"""
me = {}
has_next_layer = False
for key, value in doc... |
Flat given nested dict, but keep the last layer of dict object unchanged.
:param doc: nested dict object, consisted solely by dict objects.
:return: flattened dict, with only last layer of dict un-flattened.
| Flat given nested dict, but keep the last layer of dict object unchanged. | [
"Flat",
"given",
"nested",
"dict",
"but",
"keep",
"the",
"last",
"layer",
"of",
"dict",
"object",
"unchanged",
"."
] | def flat_vars(doc):
me = {}
has_next_layer = False
for key, value in doc.items():
if isinstance(value, dict):
has_next_layer = True
child, is_final_layer = flat_vars(value)
if is_final_layer:
me[key] = child
else:
for ch... | [
"def",
"flat_vars",
"(",
"doc",
")",
":",
"me",
"=",
"{",
"}",
"has_next_layer",
"=",
"False",
"for",
"key",
",",
"value",
"in",
"doc",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"has_next_layer",
"=",
"Tr... | Flat given nested dict, but keep the last layer of dict object unchanged. | [
"Flat",
"given",
"nested",
"dict",
"but",
"keep",
"the",
"last",
"layer",
"of",
"dict",
"object",
"unchanged",
"."
] | [
"\"\"\"\n Flat given nested dict, but keep the last layer of dict object unchanged.\n :param doc: nested dict object, consisted solely by dict objects.\n :return: flattened dict, with only last layer of dict un-flattened.\n \"\"\""
] | [
{
"param": "doc",
"type": null
}
] | {
"returns": [
{
"docstring": "flattened dict, with only last layer of dict un-flattened.",
"docstring_tokens": [
"flattened",
"dict",
"with",
"only",
"last",
"layer",
"of",
"dict",
"un",
"-",
"flattened",
... |
2c482a53a43a5381a595d655e6a28b5c4849fdac | whuscity/citation-recommendation | examples/node2vec_main.py | [
"MIT"
] | Python | read_graph | <not_specific> | def read_graph():
'''
Reads the input network in networkx.
'''
if args.weighted:
G = nx.read_edgelist(args.input, nodetype=int, data=(('weight', float),), create_using=nx.DiGraph())
else:
G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.DiGraph())
for edge in G.... |
Reads the input network in networkx.
| Reads the input network in networkx. | [
"Reads",
"the",
"input",
"network",
"in",
"networkx",
"."
] | def read_graph():
if args.weighted:
G = nx.read_edgelist(args.input, nodetype=int, data=(('weight', float),), create_using=nx.DiGraph())
else:
G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.DiGraph())
for edge in G.edges():
G[edge[0]][edge[1]]['weight'] = 1
... | [
"def",
"read_graph",
"(",
")",
":",
"if",
"args",
".",
"weighted",
":",
"G",
"=",
"nx",
".",
"read_edgelist",
"(",
"args",
".",
"input",
",",
"nodetype",
"=",
"int",
",",
"data",
"=",
"(",
"(",
"'weight'",
",",
"float",
")",
",",
")",
",",
"creat... | Reads the input network in networkx. | [
"Reads",
"the",
"input",
"network",
"in",
"networkx",
"."
] | [
"'''\n Reads the input network in networkx.\n '''"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
2c482a53a43a5381a595d655e6a28b5c4849fdac | whuscity/citation-recommendation | examples/node2vec_main.py | [
"MIT"
] | Python | learn_embeddings | <not_specific> | def learn_embeddings(walks):
'''
Learn embeddings by optimizing the Skipgram objective using SGD.
'''
walks = [list(map(str, walk)) for walk in walks]
model = Word2Vec(walks, size=args.dimensions, window=args.window_size, min_count=0, sg=1, workers=args.workers,
iter=args.iter)
... |
Learn embeddings by optimizing the Skipgram objective using SGD.
| Learn embeddings by optimizing the Skipgram objective using SGD. | [
"Learn",
"embeddings",
"by",
"optimizing",
"the",
"Skipgram",
"objective",
"using",
"SGD",
"."
] | def learn_embeddings(walks):
walks = [list(map(str, walk)) for walk in walks]
model = Word2Vec(walks, size=args.dimensions, window=args.window_size, min_count=0, sg=1, workers=args.workers,
iter=args.iter)
model.wv.save_word2vec_format(args.output)
print("保存完毕")
return | [
"def",
"learn_embeddings",
"(",
"walks",
")",
":",
"walks",
"=",
"[",
"list",
"(",
"map",
"(",
"str",
",",
"walk",
")",
")",
"for",
"walk",
"in",
"walks",
"]",
"model",
"=",
"Word2Vec",
"(",
"walks",
",",
"size",
"=",
"args",
".",
"dimensions",
","... | Learn embeddings by optimizing the Skipgram objective using SGD. | [
"Learn",
"embeddings",
"by",
"optimizing",
"the",
"Skipgram",
"objective",
"using",
"SGD",
"."
] | [
"'''\n Learn embeddings by optimizing the Skipgram objective using SGD.\n '''"
] | [
{
"param": "walks",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "walks",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
2c482a53a43a5381a595d655e6a28b5c4849fdac | whuscity/citation-recommendation | examples/node2vec_main.py | [
"MIT"
] | Python | main | null | def main(args):
'''
Pipeline for representational learning for all nodes in a graph.
'''
nx_G = read_graph()
G = Graph(nx_G, args.directed, args.p, args.q)
G.preprocess_transition_probs()
walks = G.simulate_walks(args.num_walks, args.walk_length)
print("开始执行")
learn_embeddings(walks) |
Pipeline for representational learning for all nodes in a graph.
| Pipeline for representational learning for all nodes in a graph. | [
"Pipeline",
"for",
"representational",
"learning",
"for",
"all",
"nodes",
"in",
"a",
"graph",
"."
] | def main(args):
nx_G = read_graph()
G = Graph(nx_G, args.directed, args.p, args.q)
G.preprocess_transition_probs()
walks = G.simulate_walks(args.num_walks, args.walk_length)
print("开始执行")
learn_embeddings(walks) | [
"def",
"main",
"(",
"args",
")",
":",
"nx_G",
"=",
"read_graph",
"(",
")",
"G",
"=",
"Graph",
"(",
"nx_G",
",",
"args",
".",
"directed",
",",
"args",
".",
"p",
",",
"args",
".",
"q",
")",
"G",
".",
"preprocess_transition_probs",
"(",
")",
"walks",
... | Pipeline for representational learning for all nodes in a graph. | [
"Pipeline",
"for",
"representational",
"learning",
"for",
"all",
"nodes",
"in",
"a",
"graph",
"."
] | [
"'''\n Pipeline for representational learning for all nodes in a graph.\n '''"
] | [
{
"param": "args",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "args",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
8f1f8f225af9855e9c1645ec3ce76d16bc31c42f | whuscity/citation-recommendation | examples/metapath2vec_main.py | [
"MIT"
] | Python | learn_embeddings | null | def learn_embeddings(walks, model_path, window_size, min_number):
'''
Learn embeddings by optimizing the Skipgram objective using SGD.
'''
walks = [list(map(str, walk)) for walk in walks]
model = Word2Vec(walks, size=128, window=window_size, min_count=min_number, sg=1, workers=12,
... |
Learn embeddings by optimizing the Skipgram objective using SGD.
| Learn embeddings by optimizing the Skipgram objective using SGD. | [
"Learn",
"embeddings",
"by",
"optimizing",
"the",
"Skipgram",
"objective",
"using",
"SGD",
"."
] | def learn_embeddings(walks, model_path, window_size, min_number):
walks = [list(map(str, walk)) for walk in walks]
model = Word2Vec(walks, size=128, window=window_size, min_count=min_number, sg=1, workers=12,
iter=1)
model.wv.save_word2vec_format(model_path)
print("保存完毕") | [
"def",
"learn_embeddings",
"(",
"walks",
",",
"model_path",
",",
"window_size",
",",
"min_number",
")",
":",
"walks",
"=",
"[",
"list",
"(",
"map",
"(",
"str",
",",
"walk",
")",
")",
"for",
"walk",
"in",
"walks",
"]",
"model",
"=",
"Word2Vec",
"(",
"... | Learn embeddings by optimizing the Skipgram objective using SGD. | [
"Learn",
"embeddings",
"by",
"optimizing",
"the",
"Skipgram",
"objective",
"using",
"SGD",
"."
] | [
"'''\n Learn embeddings by optimizing the Skipgram objective using SGD.\n '''"
] | [
{
"param": "walks",
"type": null
},
{
"param": "model_path",
"type": null
},
{
"param": "window_size",
"type": null
},
{
"param": "min_number",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "walks",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "model_path",
"type": null,
"docstring": null,
"docstring_tok... |
00b2b15200b1b005fe791cb0d026f17b3557f5b3 | Andrew-Foote/lisp3 | base.py | [
"MIT"
] | Python | basedigit | int | def basedigit(c: str, base: int) -> int:
"""Interpret a character as a single-digit integer in the given
base."""
if len(c) != 1:
raise TypeError(
f'basedigit() expected a character, but string of length {len(c)}'
'found'
)
if base <= 10:
digit = ord(c) -... | Interpret a character as a single-digit integer in the given
base. | Interpret a character as a single-digit integer in the given
base. | [
"Interpret",
"a",
"character",
"as",
"a",
"single",
"-",
"digit",
"integer",
"in",
"the",
"given",
"base",
"."
] | def basedigit(c: str, base: int) -> int:
if len(c) != 1:
raise TypeError(
f'basedigit() expected a character, but string of length {len(c)}'
'found'
)
if base <= 10:
digit = ord(c) - ord('0')
if 0 <= digit < 10:
return digit
raise Value... | [
"def",
"basedigit",
"(",
"c",
":",
"str",
",",
"base",
":",
"int",
")",
"->",
"int",
":",
"if",
"len",
"(",
"c",
")",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"f'basedigit() expected a character, but string of length {len(c)}'",
"'found'",
")",
"if",
"base... | Interpret a character as a single-digit integer in the given
base. | [
"Interpret",
"a",
"character",
"as",
"a",
"single",
"-",
"digit",
"integer",
"in",
"the",
"given",
"base",
"."
] | [
"\"\"\"Interpret a character as a single-digit integer in the given\n base.\"\"\""
] | [
{
"param": "c",
"type": "str"
},
{
"param": "base",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "c",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "base",
"type": "int",
"docstring": null,
"docstring_tokens": []... |
8922afd648cc812bc89e3162cda7ca436e5fd703 | Andrew-Foote/lisp3 | scanner.py | [
"MIT"
] | Python | enumerate_file_with_locations | t.Iterator[t.Tuple[Location, str]] | def enumerate_file_with_locations(filename: str, f: t.TextIO)\
-> t.Iterator[t.Tuple[Location, str]]:
"""Iterate over the `Locations` within the given file, yielding pairs
consisting of the `Location` and the character at that location."""
for line_number, line in enumerate(f, start=1):
for col, c i... | Iterate over the `Locations` within the given file, yielding pairs
consisting of the `Location` and the character at that location. | Iterate over the `Locations` within the given file, yielding pairs
consisting of the `Location` and the character at that location. | [
"Iterate",
"over",
"the",
"`",
"Locations",
"`",
"within",
"the",
"given",
"file",
"yielding",
"pairs",
"consisting",
"of",
"the",
"`",
"Location",
"`",
"and",
"the",
"character",
"at",
"that",
"location",
"."
] | def enumerate_file_with_locations(filename: str, f: t.TextIO)\
-> t.Iterator[t.Tuple[Location, str]]:
for line_number, line in enumerate(f, start=1):
for col, c in enumerate(line):
yield Location(filename, line_number, line[:-1], col), c | [
"def",
"enumerate_file_with_locations",
"(",
"filename",
":",
"str",
",",
"f",
":",
"t",
".",
"TextIO",
")",
"->",
"t",
".",
"Iterator",
"[",
"t",
".",
"Tuple",
"[",
"Location",
",",
"str",
"]",
"]",
":",
"for",
"line_number",
",",
"line",
"in",
"enu... | Iterate over the `Locations` within the given file, yielding pairs
consisting of the `Location` and the character at that location. | [
"Iterate",
"over",
"the",
"`",
"Locations",
"`",
"within",
"the",
"given",
"file",
"yielding",
"pairs",
"consisting",
"of",
"the",
"`",
"Location",
"`",
"and",
"the",
"character",
"at",
"that",
"location",
"."
] | [
"\"\"\"Iterate over the `Locations` within the given file, yielding pairs\n consisting of the `Location` and the character at that location.\"\"\""
] | [
{
"param": "filename",
"type": "str"
},
{
"param": "f",
"type": "t.TextIO"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filename",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "f",
"type": "t.TextIO",
"docstring": null,
"docstring_to... |
e08962dd1d8358796882a4b8f56b3382663a68bd | jamesward/Python-Random-Number-Generator | appengine/standard_python37/hello_world/main.py | [
"Apache-2.0"
] | Python | hello | <not_specific> | def hello():
"""Return a friendly HTTP greeting."""
style = "\"color:white;font-size:10rem;position: absolute; top: 30%;left: 50%;-moz-transform: translateX(-50%) translateY(-50%);-webkit-transform: translateX(-50%) translateY(-50%);transform: translateX(-50%) translateY(-50%);\""
num = randrange(1000001)
... | Return a friendly HTTP greeting. | Return a friendly HTTP greeting. | [
"Return",
"a",
"friendly",
"HTTP",
"greeting",
"."
] | def hello():
style = "\"color:white;font-size:10rem;position: absolute; top: 30%;left: 50%;-moz-transform: translateX(-50%) translateY(-50%);-webkit-transform: translateX(-50%) translateY(-50%);transform: translateX(-50%) translateY(-50%);\""
num = randrange(1000001)
ret = "<!doctypehtml><html><head><title>... | [
"def",
"hello",
"(",
")",
":",
"style",
"=",
"\"\\\"color:white;font-size:10rem;position: absolute; top: 30%;left: 50%;-moz-transform: translateX(-50%) translateY(-50%);-webkit-transform: translateX(-50%) translateY(-50%);transform: translateX(-50%) translateY(-50%);\\\"\"",
"num",
"=",
"randran... | Return a friendly HTTP greeting. | [
"Return",
"a",
"friendly",
"HTTP",
"greeting",
"."
] | [
"\"\"\"Return a friendly HTTP greeting.\"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
ea3be7bebcf2c4d54c94085a715e294534f61d4c | JustineKay/psychic-octo-carnival | ask/config/config.py | [
"MIT"
] | Python | read_from_user | <not_specific> | def read_from_user(input_type, *args, **kwargs):
'''
Helper function to prompt user for input of a specific type
e.g. float, str, int
Designed to work with both python 2 and 3
Yes I know this is ugly.
'''
def _read_in(*args, **kwargs):
while True:
try: tmp = raw_inpu... |
Helper function to prompt user for input of a specific type
e.g. float, str, int
Designed to work with both python 2 and 3
Yes I know this is ugly.
| Helper function to prompt user for input of a specific type
e.g. float, str, int
Designed to work with both python 2 and 3
Yes I know this is ugly. | [
"Helper",
"function",
"to",
"prompt",
"user",
"for",
"input",
"of",
"a",
"specific",
"type",
"e",
".",
"g",
".",
"float",
"str",
"int",
"Designed",
"to",
"work",
"with",
"both",
"python",
"2",
"and",
"3",
"Yes",
"I",
"know",
"this",
"is",
"ugly",
"."... | def read_from_user(input_type, *args, **kwargs):
def _read_in(*args, **kwargs):
while True:
try: tmp = raw_input(*args, **kwargs)
except NameError: tmp = input(*args, **kwargs)
try: return input_type(tmp)
except: print ('Expected type', input_type)
retur... | [
"def",
"read_from_user",
"(",
"input_type",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"def",
"_read_in",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"tmp",
"=",
"raw_input",
"(",
"*",
"args",
",",
"**",... | Helper function to prompt user for input of a specific type
e.g. | [
"Helper",
"function",
"to",
"prompt",
"user",
"for",
"input",
"of",
"a",
"specific",
"type",
"e",
".",
"g",
"."
] | [
"'''\n Helper function to prompt user for input of a specific type \n e.g. float, str, int \n Designed to work with both python 2 and 3 \n Yes I know this is ugly.\n '''"
] | [
{
"param": "input_type",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "input_type",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ea3be7bebcf2c4d54c94085a715e294534f61d4c | JustineKay/psychic-octo-carnival | ask/config/config.py | [
"MIT"
] | Python | load_builtin_slots | <not_specific> | def load_builtin_slots():
'''
Helper function to load builtin slots from the data location
'''
builtin_slots = {}
for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)):
o = line.strip().split('\t')
builtin_slots[index] = {'name' : o[0],
'descript... |
Helper function to load builtin slots from the data location
| Helper function to load builtin slots from the data location | [
"Helper",
"function",
"to",
"load",
"builtin",
"slots",
"from",
"the",
"data",
"location"
] | def load_builtin_slots():
builtin_slots = {}
for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)):
o = line.strip().split('\t')
builtin_slots[index] = {'name' : o[0],
'description' : o[1] }
return builtin_slots | [
"def",
"load_builtin_slots",
"(",
")",
":",
"builtin_slots",
"=",
"{",
"}",
"for",
"index",
",",
"line",
"in",
"enumerate",
"(",
"open",
"(",
"BUILTIN_SLOTS_LOCATION",
")",
")",
":",
"o",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",... | Helper function to load builtin slots from the data location | [
"Helper",
"function",
"to",
"load",
"builtin",
"slots",
"from",
"the",
"data",
"location"
] | [
"'''\n Helper function to load builtin slots from the data location\n '''"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
17edb6e313e13bfc87ff0ed5b78e2c974c5cb35f | JustineKay/psychic-octo-carnival | spreadsheet.py | [
"MIT"
] | Python | main | null | def main():
"""
Gets restaurants out of the shared google spreadsheet
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4'... |
Gets restaurants out of the shared google spreadsheet
| Gets restaurants out of the shared google spreadsheet | [
"Gets",
"restaurants",
"out",
"of",
"the",
"shared",
"google",
"spreadsheet"
] | def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl... | [
"def",
"main",
"(",
")",
":",
"credentials",
"=",
"get_credentials",
"(",
")",
"http",
"=",
"credentials",
".",
"authorize",
"(",
"httplib2",
".",
"Http",
"(",
")",
")",
"discoveryUrl",
"=",
"(",
"'https://sheets.googleapis.com/$discovery/rest?'",
"'version=v4'",
... | Gets restaurants out of the shared google spreadsheet | [
"Gets",
"restaurants",
"out",
"of",
"the",
"shared",
"google",
"spreadsheet"
] | [
"\"\"\"\n Gets restaurants out of the shared google spreadsheet\n\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | sim_matrix | <not_specific> | def sim_matrix(found_list, ground_list, metric):
"""Calculate pairwise similarity of found/ground communities using the given
metric.
"""
# TODO: declare types and remove boundschecking and wrapping with Cython.
sims = np.zeros((len(found_list), len(ground_list)))
for i, found in enumerate(found... | Calculate pairwise similarity of found/ground communities using the given
metric.
| Calculate pairwise similarity of found/ground communities using the given
metric. | [
"Calculate",
"pairwise",
"similarity",
"of",
"found",
"/",
"ground",
"communities",
"using",
"the",
"given",
"metric",
"."
] | def sim_matrix(found_list, ground_list, metric):
sims = np.zeros((len(found_list), len(ground_list)))
for i, found in enumerate(found_list):
sims[i] = [metric(ground, found) for ground in ground_list]
return sims | [
"def",
"sim_matrix",
"(",
"found_list",
",",
"ground_list",
",",
"metric",
")",
":",
"sims",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"found_list",
")",
",",
"len",
"(",
"ground_list",
")",
")",
")",
"for",
"i",
",",
"found",
"in",
"enumerate",... | Calculate pairwise similarity of found/ground communities using the given
metric. | [
"Calculate",
"pairwise",
"similarity",
"of",
"found",
"/",
"ground",
"communities",
"using",
"the",
"given",
"metric",
"."
] | [
"\"\"\"Calculate pairwise similarity of found/ground communities using the given\n metric.\n \"\"\"",
"# TODO: declare types and remove boundschecking and wrapping with Cython."
] | [
{
"param": "found_list",
"type": null
},
{
"param": "ground_list",
"type": null
},
{
"param": "metric",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "found_list",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ground_list",
"type": null,
"docstring": null,
"docstri... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | fpr_matrix | <not_specific> | def fpr_matrix(found_list, ground_list):
"""Compute the false positive rate matrix for the found communities when
compared to the ground truth communities given.
"""
all_ground = np.array(list(itertools.chain.from_iterable(ground_list)))
size_all_ground = float(len(np.unique(all_ground)))
glens ... | Compute the false positive rate matrix for the found communities when
compared to the ground truth communities given.
| Compute the false positive rate matrix for the found communities when
compared to the ground truth communities given. | [
"Compute",
"the",
"false",
"positive",
"rate",
"matrix",
"for",
"the",
"found",
"communities",
"when",
"compared",
"to",
"the",
"ground",
"truth",
"communities",
"given",
"."
] | def fpr_matrix(found_list, ground_list):
all_ground = np.array(list(itertools.chain.from_iterable(ground_list)))
size_all_ground = float(len(np.unique(all_ground)))
glens = np.array([float(len(g)) for g in ground_list])
negatives = size_all_ground - glens
fp_mat = np.zeros((len(found_list), len(grou... | [
"def",
"fpr_matrix",
"(",
"found_list",
",",
"ground_list",
")",
":",
"all_ground",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"ground_list",
")",
")",
")",
"size_all_ground",
"=",
"float",
"(",
"len",
... | Compute the false positive rate matrix for the found communities when
compared to the ground truth communities given. | [
"Compute",
"the",
"false",
"positive",
"rate",
"matrix",
"for",
"the",
"found",
"communities",
"when",
"compared",
"to",
"the",
"ground",
"truth",
"communities",
"given",
"."
] | [
"\"\"\"Compute the false positive rate matrix for the found communities when\n compared to the ground truth communities given.\n \"\"\""
] | [
{
"param": "found_list",
"type": null
},
{
"param": "ground_list",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "found_list",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ground_list",
"type": null,
"docstring": null,
"docstri... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | similarity_matrices | <not_specific> | def similarity_matrices(found_list, ground_list):
"""Compute the recall, precision, f1-score and jaccard similarity.
:param list found_list: List of found communities to evaluate.
:param list ground_list: List of ground truth communities to compare
against.
:return: tuple of (recall, precision... | Compute the recall, precision, f1-score and jaccard similarity.
:param list found_list: List of found communities to evaluate.
:param list ground_list: List of ground truth communities to compare
against.
:return: tuple of (recall, precision, f1-score, and jaccard similarity)
| Compute the recall, precision, f1-score and jaccard similarity. | [
"Compute",
"the",
"recall",
"precision",
"f1",
"-",
"score",
"and",
"jaccard",
"similarity",
"."
] | def similarity_matrices(found_list, ground_list):
gsets = [set(g) for g in ground_list]
glens = np.array([float(len(g)) for g in ground_list])
flens = np.matrix([float(len(f)) for f in found_list])
flens = np.array(np.tile(flens.transpose(), len(ground_list)))
logging.info('calculating true positive... | [
"def",
"similarity_matrices",
"(",
"found_list",
",",
"ground_list",
")",
":",
"gsets",
"=",
"[",
"set",
"(",
"g",
")",
"for",
"g",
"in",
"ground_list",
"]",
"glens",
"=",
"np",
".",
"array",
"(",
"[",
"float",
"(",
"len",
"(",
"g",
")",
")",
"for"... | Compute the recall, precision, f1-score and jaccard similarity. | [
"Compute",
"the",
"recall",
"precision",
"f1",
"-",
"score",
"and",
"jaccard",
"similarity",
"."
] | [
"\"\"\"Compute the recall, precision, f1-score and jaccard similarity.\n\n :param list found_list: List of found communities to evaluate.\n :param list ground_list: List of ground truth communities to compare\n against.\n :return: tuple of (recall, precision, f1-score, and jaccard similarity)\n ... | [
{
"param": "found_list",
"type": null
},
{
"param": "ground_list",
"type": null
}
] | {
"returns": [
{
"docstring": "tuple of (recall, precision, f1-score, and jaccard similarity)",
"docstring_tokens": [
"tuple",
"of",
"(",
"recall",
"precision",
"f1",
"-",
"score",
"and",
"jaccard",
"similarity",
... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | recall_matrix | <not_specific> | def recall_matrix(found_list, ground_list):
"""Compute pairwise recall for a list of found communities when compared to
the given ground truth communities.
"""
gsets = [set(g) for g in ground_list]
glens = np.array([float(len(g)) for g in ground_list])
tp_mat = np.zeros((len(found_list), len(gro... | Compute pairwise recall for a list of found communities when compared to
the given ground truth communities.
| Compute pairwise recall for a list of found communities when compared to
the given ground truth communities. | [
"Compute",
"pairwise",
"recall",
"for",
"a",
"list",
"of",
"found",
"communities",
"when",
"compared",
"to",
"the",
"given",
"ground",
"truth",
"communities",
"."
] | def recall_matrix(found_list, ground_list):
gsets = [set(g) for g in ground_list]
glens = np.array([float(len(g)) for g in ground_list])
tp_mat = np.zeros((len(found_list), len(ground_list)))
for i, found in enumerate(found_list):
tp_mat[i] = [len(ground.intersection(found)) for ground in gsets]... | [
"def",
"recall_matrix",
"(",
"found_list",
",",
"ground_list",
")",
":",
"gsets",
"=",
"[",
"set",
"(",
"g",
")",
"for",
"g",
"in",
"ground_list",
"]",
"glens",
"=",
"np",
".",
"array",
"(",
"[",
"float",
"(",
"len",
"(",
"g",
")",
")",
"for",
"g... | Compute pairwise recall for a list of found communities when compared to
the given ground truth communities. | [
"Compute",
"pairwise",
"recall",
"for",
"a",
"list",
"of",
"found",
"communities",
"when",
"compared",
"to",
"the",
"given",
"ground",
"truth",
"communities",
"."
] | [
"\"\"\"Compute pairwise recall for a list of found communities when compared to\n the given ground truth communities.\n \"\"\""
] | [
{
"param": "found_list",
"type": null
},
{
"param": "ground_list",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "found_list",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ground_list",
"type": null,
"docstring": null,
"docstri... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | precision_matrix | <not_specific> | def precision_matrix(found_list, ground_list):
"""Compute pairwise precision for a list of found communities when compared
to the given ground truth communities.
"""
gsets = [set(g) for g in ground_list]
flens = np.matrix([float(len(f)) for f in found_list])
tp_mat = np.zeros((len(found_list), l... | Compute pairwise precision for a list of found communities when compared
to the given ground truth communities.
| Compute pairwise precision for a list of found communities when compared
to the given ground truth communities. | [
"Compute",
"pairwise",
"precision",
"for",
"a",
"list",
"of",
"found",
"communities",
"when",
"compared",
"to",
"the",
"given",
"ground",
"truth",
"communities",
"."
] | def precision_matrix(found_list, ground_list):
gsets = [set(g) for g in ground_list]
flens = np.matrix([float(len(f)) for f in found_list])
tp_mat = np.zeros((len(found_list), len(ground_list)))
for i, found in enumerate(found_list):
tp_mat[i] = [len(ground.intersection(found)) for ground in gse... | [
"def",
"precision_matrix",
"(",
"found_list",
",",
"ground_list",
")",
":",
"gsets",
"=",
"[",
"set",
"(",
"g",
")",
"for",
"g",
"in",
"ground_list",
"]",
"flens",
"=",
"np",
".",
"matrix",
"(",
"[",
"float",
"(",
"len",
"(",
"f",
")",
")",
"for",
... | Compute pairwise precision for a list of found communities when compared
to the given ground truth communities. | [
"Compute",
"pairwise",
"precision",
"for",
"a",
"list",
"of",
"found",
"communities",
"when",
"compared",
"to",
"the",
"given",
"ground",
"truth",
"communities",
"."
] | [
"\"\"\"Compute pairwise precision for a list of found communities when compared\n to the given ground truth communities.\n \"\"\""
] | [
{
"param": "found_list",
"type": null
},
{
"param": "ground_list",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "found_list",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ground_list",
"type": null,
"docstring": null,
"docstri... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | jaccard_matrix | <not_specific> | def jaccard_matrix(found_list, ground_list):
"""Compute pairwise jaccard similarity for a list of found communities when
compared to the given ground truth communities.
"""
gsets = [set(g) for g in ground_list]
int_mat = np.zeros((len(found_list), len(ground_list)))
union_mat = np.zeros((len(fou... | Compute pairwise jaccard similarity for a list of found communities when
compared to the given ground truth communities.
| Compute pairwise jaccard similarity for a list of found communities when
compared to the given ground truth communities. | [
"Compute",
"pairwise",
"jaccard",
"similarity",
"for",
"a",
"list",
"of",
"found",
"communities",
"when",
"compared",
"to",
"the",
"given",
"ground",
"truth",
"communities",
"."
] | def jaccard_matrix(found_list, ground_list):
gsets = [set(g) for g in ground_list]
int_mat = np.zeros((len(found_list), len(ground_list)))
union_mat = np.zeros((len(found_list), len(ground_list)))
for i, found in enumerate(found_list):
int_mat[i] = [len(ground.intersection(found)) for ground in ... | [
"def",
"jaccard_matrix",
"(",
"found_list",
",",
"ground_list",
")",
":",
"gsets",
"=",
"[",
"set",
"(",
"g",
")",
"for",
"g",
"in",
"ground_list",
"]",
"int_mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"found_list",
")",
",",
"len",
"(",
"... | Compute pairwise jaccard similarity for a list of found communities when
compared to the given ground truth communities. | [
"Compute",
"pairwise",
"jaccard",
"similarity",
"for",
"a",
"list",
"of",
"found",
"communities",
"when",
"compared",
"to",
"the",
"given",
"ground",
"truth",
"communities",
"."
] | [
"\"\"\"Compute pairwise jaccard similarity for a list of found communities when\n compared to the given ground truth communities.\n \"\"\""
] | [
{
"param": "found_list",
"type": null
},
{
"param": "ground_list",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "found_list",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ground_list",
"type": null,
"docstring": null,
"docstri... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | extract_edcar_comms | <not_specific> | def extract_edcar_comms(lines):
"""The last 2 lines in an EDCAR found community file are statistics. Each
remaining line must be parsed to get the node IDs. See `get_edcar_comm` for
more info.
"""
rows = [row.split() for row in lines[:-2]] # last 2 are stats
return [get_edcar_comm(row) for row ... | The last 2 lines in an EDCAR found community file are statistics. Each
remaining line must be parsed to get the node IDs. See `get_edcar_comm` for
more info.
| The last 2 lines in an EDCAR found community file are statistics. Each
remaining line must be parsed to get the node IDs. See `get_edcar_comm` for
more info. | [
"The",
"last",
"2",
"lines",
"in",
"an",
"EDCAR",
"found",
"community",
"file",
"are",
"statistics",
".",
"Each",
"remaining",
"line",
"must",
"be",
"parsed",
"to",
"get",
"the",
"node",
"IDs",
".",
"See",
"`",
"get_edcar_comm",
"`",
"for",
"more",
"info... | def extract_edcar_comms(lines):
rows = [row.split() for row in lines[:-2]]
return [get_edcar_comm(row) for row in rows] | [
"def",
"extract_edcar_comms",
"(",
"lines",
")",
":",
"rows",
"=",
"[",
"row",
".",
"split",
"(",
")",
"for",
"row",
"in",
"lines",
"[",
":",
"-",
"2",
"]",
"]",
"return",
"[",
"get_edcar_comm",
"(",
"row",
")",
"for",
"row",
"in",
"rows",
"]"
] | The last 2 lines in an EDCAR found community file are statistics. | [
"The",
"last",
"2",
"lines",
"in",
"an",
"EDCAR",
"found",
"community",
"file",
"are",
"statistics",
"."
] | [
"\"\"\"The last 2 lines in an EDCAR found community file are statistics. Each\n remaining line must be parsed to get the node IDs. See `get_edcar_comm` for\n more info.\n \"\"\"",
"# last 2 are stats"
] | [
{
"param": "lines",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "lines",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | read_communities | <not_specific> | def read_communities(fpath):
"""Takes the path of a found community data file and returns the name of the
file (minus the extension), with the list of communities read from the file.
:param str fpath: Path of the found community file. The name will be used as
the name of the method in statistical o... | Takes the path of a found community data file and returns the name of the
file (minus the extension), with the list of communities read from the file.
:param str fpath: Path of the found community file. The name will be used as
the name of the method in statistical output, and the extension will be
... | Takes the path of a found community data file and returns the name of the
file (minus the extension), with the list of communities read from the file. | [
"Takes",
"the",
"path",
"of",
"a",
"found",
"community",
"data",
"file",
"and",
"returns",
"the",
"name",
"of",
"the",
"file",
"(",
"minus",
"the",
"extension",
")",
"with",
"the",
"list",
"of",
"communities",
"read",
"from",
"the",
"file",
"."
] | def read_communities(fpath):
lines = read_lines(fpath)
basename = os.path.basename(fpath)
pieces = os.path.splitext(basename)
name, ext = pieces[0], pieces[1].replace('.','')
if ext == 'txt':
return (name, extract_comms(lines, ' '))
elif ext == 'csv':
return (name, extract_comms(... | [
"def",
"read_communities",
"(",
"fpath",
")",
":",
"lines",
"=",
"read_lines",
"(",
"fpath",
")",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fpath",
")",
"pieces",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"basename",
")",
"name",
... | Takes the path of a found community data file and returns the name of the
file (minus the extension), with the list of communities read from the file. | [
"Takes",
"the",
"path",
"of",
"a",
"found",
"community",
"data",
"file",
"and",
"returns",
"the",
"name",
"of",
"the",
"file",
"(",
"minus",
"the",
"extension",
")",
"with",
"the",
"list",
"of",
"communities",
"read",
"from",
"the",
"file",
"."
] | [
"\"\"\"Takes the path of a found community data file and returns the name of the\n file (minus the extension), with the list of communities read from the file.\n\n :param str fpath: Path of the found community file. The name will be used as\n the name of the method in statistical output, and the extens... | [
{
"param": "fpath",
"type": null
}
] | {
"returns": [
{
"docstring": "list of lists of strings, where each string is a node id.",
"docstring_tokens": [
"list",
"of",
"lists",
"of",
"strings",
"where",
"each",
"string",
"is",
"a",
"node",
"id",
... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | iterfound | <not_specific> | def iterfound(fdir=None):
"""Iterate through files in `fdir`, treating each as a file of found
communities and reading them with `read_communities`. A generator is returned that
yields each found community list in alphabetic order by file name.
:return: generator which yields tuples of (name, communiti... | Iterate through files in `fdir`, treating each as a file of found
communities and reading them with `read_communities`. A generator is returned that
yields each found community list in alphabetic order by file name.
:return: generator which yields tuples of (name, communities), where
communities is... | Iterate through files in `fdir`, treating each as a file of found
communities and reading them with `read_communities`. A generator is returned that
yields each found community list in alphabetic order by file name. | [
"Iterate",
"through",
"files",
"in",
"`",
"fdir",
"`",
"treating",
"each",
"as",
"a",
"file",
"of",
"found",
"communities",
"and",
"reading",
"them",
"with",
"`",
"read_communities",
"`",
".",
"A",
"generator",
"is",
"returned",
"that",
"yields",
"each",
"... | def iterfound(fdir=None):
fdir = os.path.join(os.getcwd(), 'found') if fdir is None else fdir
foundfiles = sorted([os.path.join(fdir, f) for f in os.listdir(fdir)])
logging.info(
'discovered %d found community files to evaluate' % len(foundfiles))
return (read_communities(f) for f in foundfiles) | [
"def",
"iterfound",
"(",
"fdir",
"=",
"None",
")",
":",
"fdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'found'",
")",
"if",
"fdir",
"is",
"None",
"else",
"fdir",
"foundfiles",
"=",
"sorted",
"(",
"[",
"os",... | Iterate through files in `fdir`, treating each as a file of found
communities and reading them with `read_communities`. | [
"Iterate",
"through",
"files",
"in",
"`",
"fdir",
"`",
"treating",
"each",
"as",
"a",
"file",
"of",
"found",
"communities",
"and",
"reading",
"them",
"with",
"`",
"read_communities",
"`",
"."
] | [
"\"\"\"Iterate through files in `fdir`, treating each as a file of found\n communities and reading them with `read_communities`. A generator is returned that\n yields each found community list in alphabetic order by file name.\n\n :return: generator which yields tuples of (name, communities), where\n ... | [
{
"param": "fdir",
"type": null
}
] | {
"returns": [
{
"docstring": "generator which yields tuples of (name, communities), where\ncommunities is a list of lists of strings.",
"docstring_tokens": [
"generator",
"which",
"yields",
"tuples",
"of",
"(",
"name",
"communities",
... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | write_matching | null | def write_matching(fpath, matching, scores, order='row'):
"""Take an array of values and interpet it either as row indices or column
indices. It is assumed the matching was in order from 0 to len(matching).
:param str fpath: Path of file to write matches to.
:param arr matching: Iterable of ints, with ... | Take an array of values and interpet it either as row indices or column
indices. It is assumed the matching was in order from 0 to len(matching).
:param str fpath: Path of file to write matches to.
:param arr matching: Iterable of ints, with each int being a row or col
index, depending on the value... | Take an array of values and interpet it either as row indices or column
indices. It is assumed the matching was in order from 0 to len(matching). | [
"Take",
"an",
"array",
"of",
"values",
"and",
"interpet",
"it",
"either",
"as",
"row",
"indices",
"or",
"column",
"indices",
".",
"It",
"is",
"assumed",
"the",
"matching",
"was",
"in",
"order",
"from",
"0",
"to",
"len",
"(",
"matching",
")",
"."
] | def write_matching(fpath, matching, scores, order='row'):
with open(fpath, 'w') as f:
if order == 'row':
matchings = ["%s,%s,%f" % (row, col, scores[col])
for col, row in enumerate(matching)]
else:
matchings = ["%s,%s,%f" % (row, col, scores[row])
... | [
"def",
"write_matching",
"(",
"fpath",
",",
"matching",
",",
"scores",
",",
"order",
"=",
"'row'",
")",
":",
"with",
"open",
"(",
"fpath",
",",
"'w'",
")",
"as",
"f",
":",
"if",
"order",
"==",
"'row'",
":",
"matchings",
"=",
"[",
"\"%s,%s,%f\"",
"%",... | Take an array of values and interpet it either as row indices or column
indices. | [
"Take",
"an",
"array",
"of",
"values",
"and",
"interpet",
"it",
"either",
"as",
"row",
"indices",
"or",
"column",
"indices",
"."
] | [
"\"\"\"Take an array of values and interpet it either as row indices or column\n indices. It is assumed the matching was in order from 0 to len(matching).\n\n :param str fpath: Path of file to write matches to.\n :param arr matching: Iterable of ints, with each int being a row or col\n index, depend... | [
{
"param": "fpath",
"type": null
},
{
"param": "matching",
"type": null
},
{
"param": "scores",
"type": null
},
{
"param": "order",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fpath",
"type": null,
"docstring": "Path of file to write matches to.",
"docstring_tokens": [
"Path",
"of",
"file",
"to",
"write",
"matches",
"to",
"."
],
... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | write_barplot | null | def write_barplot(fname, df, labels, sortby='f1', title=''):
"""Write a barplot from the DataFrame given.
:param str fname: Path of file to write barplot to. If no extension is
given, pdf will be used.
:param list labels: Ordering of bars to use in each column.
:param str sortby: Column to sort... | Write a barplot from the DataFrame given.
:param str fname: Path of file to write barplot to. If no extension is
given, pdf will be used.
:param list labels: Ordering of bars to use in each column.
:param str sortby: Column to sort methods by (greatest -> least).
:param str title: Title of the ... | Write a barplot from the DataFrame given. | [
"Write",
"a",
"barplot",
"from",
"the",
"DataFrame",
"given",
"."
] | def write_barplot(fname, df, labels, sortby='f1', title=''):
plt.cla()
fig, ax = plt.subplots()
frame = df[labels].reindex_axis(labels, 1).sort(sortby, ascending=False)
frame.plot(kind='bar', color=palette[:len(labels)], width=0.85,
title=title, figsize=(24,16), ax=ax)
ncols = len(lab... | [
"def",
"write_barplot",
"(",
"fname",
",",
"df",
",",
"labels",
",",
"sortby",
"=",
"'f1'",
",",
"title",
"=",
"''",
")",
":",
"plt",
".",
"cla",
"(",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"frame",
"=",
"df",
"[",
"label... | Write a barplot from the DataFrame given. | [
"Write",
"a",
"barplot",
"from",
"the",
"DataFrame",
"given",
"."
] | [
"\"\"\"Write a barplot from the DataFrame given.\n\n :param str fname: Path of file to write barplot to. If no extension is\n given, pdf will be used.\n :param list labels: Ordering of bars to use in each column.\n :param str sortby: Column to sort methods by (greatest -> least).\n :param str tit... | [
{
"param": "fname",
"type": null
},
{
"param": "df",
"type": null
},
{
"param": "labels",
"type": null
},
{
"param": "sortby",
"type": null
},
{
"param": "title",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fname",
"type": null,
"docstring": "Path of file to write barplot to. If no extension is\ngiven, pdf will be used.",
"docstring_tokens": [
"Path",
"of",
"file",
"to",
"write",
"b... |
5bae5bd5d285224bc4da12a964223f71913ab3cc | yuqil/688proj | pipeline/evaluate.py | [
"MIT"
] | Python | plot_roc_curve | null | def plot_roc_curve(csvfile):
"""`csvfile` should be the csvfile of the evaluation statistics from the
SENC parameter sweep.
"""
df = pd.DataFrame.from_csv(csvfile)
fig, ax = plt.subplots()
frame = df[['fpr', 'r']].sort('fpr')
ax.plot(frame['fpr'], frame['r'], color='black', alpha=0.85,
... | `csvfile` should be the csvfile of the evaluation statistics from the
SENC parameter sweep.
| `csvfile` should be the csvfile of the evaluation statistics from the
SENC parameter sweep. | [
"`",
"csvfile",
"`",
"should",
"be",
"the",
"csvfile",
"of",
"the",
"evaluation",
"statistics",
"from",
"the",
"SENC",
"parameter",
"sweep",
"."
] | def plot_roc_curve(csvfile):
df = pd.DataFrame.from_csv(csvfile)
fig, ax = plt.subplots()
frame = df[['fpr', 'r']].sort('fpr')
ax.plot(frame['fpr'], frame['r'], color='black', alpha=0.85,
linewidth=3)
ax.set_title('ROC Curve')
ax.set_ylabel('TPR')
ax.set_xlabel('FPR')
ax.set_... | [
"def",
"plot_roc_curve",
"(",
"csvfile",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
".",
"from_csv",
"(",
"csvfile",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"frame",
"=",
"df",
"[",
"[",
"'fpr'",
",",
"'r'",
"]",
"]",
".",... | `csvfile` should be the csvfile of the evaluation statistics from the
SENC parameter sweep. | [
"`",
"csvfile",
"`",
"should",
"be",
"the",
"csvfile",
"of",
"the",
"evaluation",
"statistics",
"from",
"the",
"SENC",
"parameter",
"sweep",
"."
] | [
"\"\"\"`csvfile` should be the csvfile of the evaluation statistics from the\n SENC parameter sweep.\n \"\"\"",
"# x values are FPR and y values are RECALL",
"# metrics obtained from comparison on connected components ground truth",
"#ax.plot(cesna_x, cesna_y, color='r', alpha=0.8, marker='o', ms=10)",
... | [
{
"param": "csvfile",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "csvfile",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
50600fb1e5ab29d2737d59ceaf077a085c4482eb | yuqil/688proj | api/scholar.py | [
"MIT"
] | Python | parse | null | def parse(self, html):
"""
This method initiates parsing of HTML content, cleans resulting
content as needed, and notifies the parser instance of
resulting instances via the handle_article callback.
"""
self.soup = BeautifulSoup(html)
# This parses any global, no... |
This method initiates parsing of HTML content, cleans resulting
content as needed, and notifies the parser instance of
resulting instances via the handle_article callback.
| This method initiates parsing of HTML content, cleans resulting
content as needed, and notifies the parser instance of
resulting instances via the handle_article callback. | [
"This",
"method",
"initiates",
"parsing",
"of",
"HTML",
"content",
"cleans",
"resulting",
"content",
"as",
"needed",
"and",
"notifies",
"the",
"parser",
"instance",
"of",
"resulting",
"instances",
"via",
"the",
"handle_article",
"callback",
"."
] | def parse(self, html):
self.soup = BeautifulSoup(html)
self._parse_globals()
for div in self.soup.findAll(ScholarArticleParser._tag_results_checker):
self._parse_article(div)
self._clean_article()
if self.article['title']:
self.handle_article(s... | [
"def",
"parse",
"(",
"self",
",",
"html",
")",
":",
"self",
".",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
")",
"self",
".",
"_parse_globals",
"(",
")",
"for",
"div",
"in",
"self",
".",
"soup",
".",
"findAll",
"(",
"ScholarArticleParser",
".",
"_tag_r... | This method initiates parsing of HTML content, cleans resulting
content as needed, and notifies the parser instance of
resulting instances via the handle_article callback. | [
"This",
"method",
"initiates",
"parsing",
"of",
"HTML",
"content",
"cleans",
"resulting",
"content",
"as",
"needed",
"and",
"notifies",
"the",
"parser",
"instance",
"of",
"resulting",
"instances",
"via",
"the",
"handle_article",
"callback",
"."
] | [
"\"\"\"\n This method initiates parsing of HTML content, cleans resulting\n content as needed, and notifies the parser instance of\n resulting instances via the handle_article callback.\n \"\"\"",
"# This parses any global, non-itemized attributes from the page.",
"# Now parse out li... | [
{
"param": "self",
"type": null
},
{
"param": "html",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "html",
"type": null,
"docstring": null,
"docstring_tokens": [... |
50600fb1e5ab29d2737d59ceaf077a085c4482eb | yuqil/688proj | api/scholar.py | [
"MIT"
] | Python | apply_settings | <not_specific> | def apply_settings(self, settings):
"""
Applies settings as provided by a ScholarSettings instance.
"""
if settings is None or not settings.is_configured():
return True
self.settings = settings
# This is a bit of work. We need to actually retrieve the
... |
Applies settings as provided by a ScholarSettings instance.
| Applies settings as provided by a ScholarSettings instance. | [
"Applies",
"settings",
"as",
"provided",
"by",
"a",
"ScholarSettings",
"instance",
"."
] | def apply_settings(self, settings):
if settings is None or not settings.is_configured():
return True
self.settings = settings
html = self._get_http_response(url=self.GET_SETTINGS_URL,
log_msg='dump of settings form HTML',
... | [
"def",
"apply_settings",
"(",
"self",
",",
"settings",
")",
":",
"if",
"settings",
"is",
"None",
"or",
"not",
"settings",
".",
"is_configured",
"(",
")",
":",
"return",
"True",
"self",
".",
"settings",
"=",
"settings",
"html",
"=",
"self",
".",
"_get_htt... | Applies settings as provided by a ScholarSettings instance. | [
"Applies",
"settings",
"as",
"provided",
"by",
"a",
"ScholarSettings",
"instance",
"."
] | [
"\"\"\"\n Applies settings as provided by a ScholarSettings instance.\n \"\"\"",
"# This is a bit of work. We need to actually retrieve the",
"# contents of the Settings pane HTML in order to extract",
"# hidden fields before we can compose the query for updating",
"# the settings.",
"# Now ... | [
{
"param": "self",
"type": null
},
{
"param": "settings",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "settings",
"type": null,
"docstring": null,
"docstring_tokens... |
1e1b3512a18f3b95b61f17dbdd710c43d96a3804 | yuqil/688proj | api/dblp_sql.py | [
"MIT"
] | Python | insert | <not_specific> | def insert(conn, ins):
"""Attempt to run an insertion statement; return results, None if error."""
try:
ins_res = conn.execute(ins)
except sa.exc.IntegrityError as err:
# a paper already exists with this id
logging.error(str(err))
return None
except Exception as e:
... | Attempt to run an insertion statement; return results, None if error. | Attempt to run an insertion statement; return results, None if error. | [
"Attempt",
"to",
"run",
"an",
"insertion",
"statement",
";",
"return",
"results",
"None",
"if",
"error",
"."
] | def insert(conn, ins):
try:
ins_res = conn.execute(ins)
except sa.exc.IntegrityError as err:
logging.error(str(err))
return None
except Exception as e:
logging.error('unexpected exception\n%s', str(e))
return None
else:
return ins_res | [
"def",
"insert",
"(",
"conn",
",",
"ins",
")",
":",
"try",
":",
"ins_res",
"=",
"conn",
".",
"execute",
"(",
"ins",
")",
"except",
"sa",
".",
"exc",
".",
"IntegrityError",
"as",
"err",
":",
"logging",
".",
"error",
"(",
"str",
"(",
"err",
")",
")... | Attempt to run an insertion statement; return results, None if error. | [
"Attempt",
"to",
"run",
"an",
"insertion",
"statement",
";",
"return",
"results",
"None",
"if",
"error",
"."
] | [
"\"\"\"Attempt to run an insertion statement; return results, None if error.\"\"\"",
"# a paper already exists with this id"
] | [
{
"param": "conn",
"type": null
},
{
"param": "ins",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "conn",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ins",
"type": null,
"docstring": null,
"docstring_tokens": []... |
1e1b3512a18f3b95b61f17dbdd710c43d96a3804 | yuqil/688proj | api/dblp_sql.py | [
"MIT"
] | Python | process_record | <not_specific> | def process_record(record):
"""Update the database with the contents of the record."""
logging.debug('processing record\n%s' % record);
conn = db.engine.connect()
paper_id = record.id
ins = db.papers.insert().\
values(id=paper_id, title=record.title,
venue=record.venu... | Update the database with the contents of the record. | Update the database with the contents of the record. | [
"Update",
"the",
"database",
"with",
"the",
"contents",
"of",
"the",
"record",
"."
] | def process_record(record):
logging.debug('processing record\n%s' % record);
conn = db.engine.connect()
paper_id = record.id
ins = db.papers.insert().\
values(id=paper_id, title=record.title,
venue=record.venue, year=record.year,
abstract=record.abstract... | [
"def",
"process_record",
"(",
"record",
")",
":",
"logging",
".",
"debug",
"(",
"'processing record\\n%s'",
"%",
"record",
")",
";",
"conn",
"=",
"db",
".",
"engine",
".",
"connect",
"(",
")",
"paper_id",
"=",
"record",
".",
"id",
"ins",
"=",
"db",
"."... | Update the database with the contents of the record. | [
"Update",
"the",
"database",
"with",
"the",
"contents",
"of",
"the",
"record",
"."
] | [
"\"\"\"Update the database with the contents of the record.\"\"\"",
"# attempt to insert a new paper into the db",
"# since ids come from data, we've already processed this record",
"# make new records for each author",
"# may fail, but we don't really care"
] | [
{
"param": "record",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "record",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
1e1b3512a18f3b95b61f17dbdd710c43d96a3804 | yuqil/688proj | api/dblp_sql.py | [
"MIT"
] | Python | process_records | null | def process_records(fpath):
"""Process all records in data file."""
processed = 0
successful = 0
for record in iterrecords(fpath):
try:
success = process_record(record)
except Exception as e:
logging.info('unexpected exception in `process_record`')
lo... | Process all records in data file. | Process all records in data file. | [
"Process",
"all",
"records",
"in",
"data",
"file",
"."
] | def process_records(fpath):
processed = 0
successful = 0
for record in iterrecords(fpath):
try:
success = process_record(record)
except Exception as e:
logging.info('unexpected exception in `process_record`')
logging.error(str(e))
success = Fal... | [
"def",
"process_records",
"(",
"fpath",
")",
":",
"processed",
"=",
"0",
"successful",
"=",
"0",
"for",
"record",
"in",
"iterrecords",
"(",
"fpath",
")",
":",
"try",
":",
"success",
"=",
"process_record",
"(",
"record",
")",
"except",
"Exception",
"as",
... | Process all records in data file. | [
"Process",
"all",
"records",
"in",
"data",
"file",
"."
] | [
"\"\"\"Process all records in data file.\"\"\""
] | [
{
"param": "fpath",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fpath",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
3e2b20c5af46514303355680a05df19d725ab00c | yuqil/688proj | api/dblpv7.py | [
"MIT"
] | Python | nextrecord | <not_specific> | def nextrecord(f):
"""Assume file pos is at beginning of record and read to end. Returns all
components as a dict.
"""
paperid = fmatch(f, id_pattern)
title = fmatch(f, title_pattern)
if title is None:
return None
authors = fmatch(f, author_pattern)
f.readline() # discard affil... | Assume file pos is at beginning of record and read to end. Returns all
components as a dict.
| Assume file pos is at beginning of record and read to end. Returns all
components as a dict. | [
"Assume",
"file",
"pos",
"is",
"at",
"beginning",
"of",
"record",
"and",
"read",
"to",
"end",
".",
"Returns",
"all",
"components",
"as",
"a",
"dict",
"."
] | def nextrecord(f):
paperid = fmatch(f, id_pattern)
title = fmatch(f, title_pattern)
if title is None:
return None
authors = fmatch(f, author_pattern)
f.readline()
year = fmatch(f, year_pattern)
venue = fmatch(f, venue_pattern)
refs = []
line = f.readline()
m = match(lin... | [
"def",
"nextrecord",
"(",
"f",
")",
":",
"paperid",
"=",
"fmatch",
"(",
"f",
",",
"id_pattern",
")",
"title",
"=",
"fmatch",
"(",
"f",
",",
"title_pattern",
")",
"if",
"title",
"is",
"None",
":",
"return",
"None",
"authors",
"=",
"fmatch",
"(",
"f",
... | Assume file pos is at beginning of record and read to end. | [
"Assume",
"file",
"pos",
"is",
"at",
"beginning",
"of",
"record",
"and",
"read",
"to",
"end",
"."
] | [
"\"\"\"Assume file pos is at beginning of record and read to end. Returns all\n components as a dict.\n \"\"\"",
"# discard affiliation info",
"# read out reference list",
"# consume blank line"
] | [
{
"param": "f",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "f",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
3e2b20c5af46514303355680a05df19d725ab00c | yuqil/688proj | api/dblpv7.py | [
"MIT"
] | Python | write_records_to_csv | null | def write_records_to_csv(records, ppath='papers.csv', rpath='refs.csv'):
"""Write the records to csv files.
:param str ppath: Path of file to write paper records to.
:param str rpath: Path of file to write paper references to.
"""
pf = open(ppath, 'w')
rf = open(rpath, 'w')
paper_writer = Un... | Write the records to csv files.
:param str ppath: Path of file to write paper records to.
:param str rpath: Path of file to write paper references to.
| Write the records to csv files. | [
"Write",
"the",
"records",
"to",
"csv",
"files",
"."
] | def write_records_to_csv(records, ppath='papers.csv', rpath='refs.csv'):
pf = open(ppath, 'w')
rf = open(rpath, 'w')
paper_writer = UnicodeWriter(pf)
refs_writer = csv.writer(rf)
paper_writer.writerow(Record.csv_header)
refs_writer.writerow(('paper_id', 'ref_id'))
venues = set()
years ... | [
"def",
"write_records_to_csv",
"(",
"records",
",",
"ppath",
"=",
"'papers.csv'",
",",
"rpath",
"=",
"'refs.csv'",
")",
":",
"pf",
"=",
"open",
"(",
"ppath",
",",
"'w'",
")",
"rf",
"=",
"open",
"(",
"rpath",
",",
"'w'",
")",
"paper_writer",
"=",
"Unico... | Write the records to csv files. | [
"Write",
"the",
"records",
"to",
"csv",
"files",
"."
] | [
"\"\"\"Write the records to csv files.\n :param str ppath: Path of file to write paper records to.\n :param str rpath: Path of file to write paper references to.\n \"\"\"",
"# handle titles/abstracts",
"# write csv column headers",
"# accumulate list of unique years and venues"
] | [
{
"param": "records",
"type": null
},
{
"param": "ppath",
"type": null
},
{
"param": "rpath",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "records",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ppath",
"type": null,
"docstring": "Path of file to write paper ... |
4dba778b8739e458c2bc929e3e8c162a17ad3bdf | yuqil/688proj | pipeline/util.py | [
"MIT"
] | Python | write_csv_to_fwrapper | null | def write_csv_to_fwrapper(fwrapper, header, rows):
"""Write csv records to already opened file handle."""
with fwrapper.open('w') as f:
writer = csv.writer(f)
if header: writer.writerow(header)
writer.writerows(rows) | Write csv records to already opened file handle. | Write csv records to already opened file handle. | [
"Write",
"csv",
"records",
"to",
"already",
"opened",
"file",
"handle",
"."
] | def write_csv_to_fwrapper(fwrapper, header, rows):
with fwrapper.open('w') as f:
writer = csv.writer(f)
if header: writer.writerow(header)
writer.writerows(rows) | [
"def",
"write_csv_to_fwrapper",
"(",
"fwrapper",
",",
"header",
",",
"rows",
")",
":",
"with",
"fwrapper",
".",
"open",
"(",
"'w'",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
")",
"if",
"header",
":",
"writer",
".",
"writerow... | Write csv records to already opened file handle. | [
"Write",
"csv",
"records",
"to",
"already",
"opened",
"file",
"handle",
"."
] | [
"\"\"\"Write csv records to already opened file handle.\"\"\""
] | [
{
"param": "fwrapper",
"type": null
},
{
"param": "header",
"type": null
},
{
"param": "rows",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fwrapper",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "header",
"type": null,
"docstring": null,
"docstring_toke... |
4dba778b8739e458c2bc929e3e8c162a17ad3bdf | yuqil/688proj | pipeline/util.py | [
"MIT"
] | Python | write_csv | null | def write_csv(fname, header, rows):
"""Write an iterable of records to a csv file with optional header."""
if not fname.endswith('.csv'):
fname = '%s.csv' % os.path.splitext(fname)[0]
with open(fname, 'w') as f:
writer = csv.writer(f)
if header: writer.writerow(header)
write... | Write an iterable of records to a csv file with optional header. | Write an iterable of records to a csv file with optional header. | [
"Write",
"an",
"iterable",
"of",
"records",
"to",
"a",
"csv",
"file",
"with",
"optional",
"header",
"."
] | def write_csv(fname, header, rows):
if not fname.endswith('.csv'):
fname = '%s.csv' % os.path.splitext(fname)[0]
with open(fname, 'w') as f:
writer = csv.writer(f)
if header: writer.writerow(header)
writer.writerows(rows) | [
"def",
"write_csv",
"(",
"fname",
",",
"header",
",",
"rows",
")",
":",
"if",
"not",
"fname",
".",
"endswith",
"(",
"'.csv'",
")",
":",
"fname",
"=",
"'%s.csv'",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"[",
"0",
"]",
"with",
"... | Write an iterable of records to a csv file with optional header. | [
"Write",
"an",
"iterable",
"of",
"records",
"to",
"a",
"csv",
"file",
"with",
"optional",
"header",
"."
] | [
"\"\"\"Write an iterable of records to a csv file with optional header.\"\"\""
] | [
{
"param": "fname",
"type": null
},
{
"param": "header",
"type": null
},
{
"param": "rows",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fname",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "header",
"type": null,
"docstring": null,
"docstring_tokens"... |
4dba778b8739e458c2bc929e3e8c162a17ad3bdf | yuqil/688proj | pipeline/util.py | [
"MIT"
] | Python | yield_csv_records | null | def yield_csv_records(csv_file):
"""Iterate over csv records, returning each as a list of strings."""
f = csv_file if isinstance(csv_file, file) else open(csv_file)
reader = csv.reader(f)
reader.next()
for record in reader:
yield record
f.close() | Iterate over csv records, returning each as a list of strings. | Iterate over csv records, returning each as a list of strings. | [
"Iterate",
"over",
"csv",
"records",
"returning",
"each",
"as",
"a",
"list",
"of",
"strings",
"."
] | def yield_csv_records(csv_file):
f = csv_file if isinstance(csv_file, file) else open(csv_file)
reader = csv.reader(f)
reader.next()
for record in reader:
yield record
f.close() | [
"def",
"yield_csv_records",
"(",
"csv_file",
")",
":",
"f",
"=",
"csv_file",
"if",
"isinstance",
"(",
"csv_file",
",",
"file",
")",
"else",
"open",
"(",
"csv_file",
")",
"reader",
"=",
"csv",
".",
"reader",
"(",
"f",
")",
"reader",
".",
"next",
"(",
... | Iterate over csv records, returning each as a list of strings. | [
"Iterate",
"over",
"csv",
"records",
"returning",
"each",
"as",
"a",
"list",
"of",
"strings",
"."
] | [
"\"\"\"Iterate over csv records, returning each as a list of strings.\"\"\""
] | [
{
"param": "csv_file",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "csv_file",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
4dba778b8739e458c2bc929e3e8c162a17ad3bdf | yuqil/688proj | pipeline/util.py | [
"MIT"
] | Python | build_and_save_idmap | <not_specific> | def build_and_save_idmap(graph, outfile, idname='author'):
"""Save vertex ID to vertex name mapping and then return it."""
first_col = '%s_id' % idname
idmap = {v['name']: v.index for v in graph.vs}
rows = sorted(idmap.items())
write_csv(outfile, (first_col, 'node_id'), rows)
return idmap | Save vertex ID to vertex name mapping and then return it. | Save vertex ID to vertex name mapping and then return it. | [
"Save",
"vertex",
"ID",
"to",
"vertex",
"name",
"mapping",
"and",
"then",
"return",
"it",
"."
] | def build_and_save_idmap(graph, outfile, idname='author'):
first_col = '%s_id' % idname
idmap = {v['name']: v.index for v in graph.vs}
rows = sorted(idmap.items())
write_csv(outfile, (first_col, 'node_id'), rows)
return idmap | [
"def",
"build_and_save_idmap",
"(",
"graph",
",",
"outfile",
",",
"idname",
"=",
"'author'",
")",
":",
"first_col",
"=",
"'%s_id'",
"%",
"idname",
"idmap",
"=",
"{",
"v",
"[",
"'name'",
"]",
":",
"v",
".",
"index",
"for",
"v",
"in",
"graph",
".",
"vs... | Save vertex ID to vertex name mapping and then return it. | [
"Save",
"vertex",
"ID",
"to",
"vertex",
"name",
"mapping",
"and",
"then",
"return",
"it",
"."
] | [
"\"\"\"Save vertex ID to vertex name mapping and then return it.\"\"\""
] | [
{
"param": "graph",
"type": null
},
{
"param": "outfile",
"type": null
},
{
"param": "idname",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "graph",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "outfile",
"type": null,
"docstring": null,
"docstring_tokens... |
4dba778b8739e458c2bc929e3e8c162a17ad3bdf | yuqil/688proj | pipeline/util.py | [
"MIT"
] | Python | build_undirected_graph | <not_specific> | def build_undirected_graph(nodes, edges):
"""Build an undirected graph, removing duplicates edges."""
graph = igraph.Graph()
graph.add_vertices(nodes)
graph.add_edges(edges)
graph.simplify()
return graph | Build an undirected graph, removing duplicates edges. | Build an undirected graph, removing duplicates edges. | [
"Build",
"an",
"undirected",
"graph",
"removing",
"duplicates",
"edges",
"."
] | def build_undirected_graph(nodes, edges):
graph = igraph.Graph()
graph.add_vertices(nodes)
graph.add_edges(edges)
graph.simplify()
return graph | [
"def",
"build_undirected_graph",
"(",
"nodes",
",",
"edges",
")",
":",
"graph",
"=",
"igraph",
".",
"Graph",
"(",
")",
"graph",
".",
"add_vertices",
"(",
"nodes",
")",
"graph",
".",
"add_edges",
"(",
"edges",
")",
"graph",
".",
"simplify",
"(",
")",
"r... | Build an undirected graph, removing duplicates edges. | [
"Build",
"an",
"undirected",
"graph",
"removing",
"duplicates",
"edges",
"."
] | [
"\"\"\"Build an undirected graph, removing duplicates edges.\"\"\""
] | [
{
"param": "nodes",
"type": null
},
{
"param": "edges",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "nodes",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "edges",
"type": null,
"docstring": null,
"docstring_tokens":... |
69740b19646e4403cd5fdc85441c3604361023c5 | yuqil/688proj | api/dblpv6.py | [
"MIT"
] | Python | nextrecord | <not_specific> | def nextrecord(f):
"""Assume file pos is at beginning of record and read to end. Returns all
components as a Record. Assume components are listed in the following order:
title
authors
year
venue
id
arnetid
references (0 or more lines)
abstract (0 ... | Assume file pos is at beginning of record and read to end. Returns all
components as a Record. Assume components are listed in the following order:
title
authors
year
venue
id
arnetid
references (0 or more lines)
abstract (0 or 1 line)
| Assume file pos is at beginning of record and read to end. Returns all
components as a Record. Assume components are listed in the following order.
title
authors
year
venue
id
arnetid
references (0 or more lines)
abstract (0 or 1 line) | [
"Assume",
"file",
"pos",
"is",
"at",
"beginning",
"of",
"record",
"and",
"read",
"to",
"end",
".",
"Returns",
"all",
"components",
"as",
"a",
"Record",
".",
"Assume",
"components",
"are",
"listed",
"in",
"the",
"following",
"order",
".",
"title",
"authors"... | def nextrecord(f):
title = fmatch(f, title_pattern)
if title is None:
return None
if len(title) > 255:
title = title[0:255]
authors = fmatch(f, author_pattern)
year = fmatch(f, year_pattern)
venue = fmatch(f, venue_pattern)
citation_num = fmatch(f, citation_pattern)
paper... | [
"def",
"nextrecord",
"(",
"f",
")",
":",
"title",
"=",
"fmatch",
"(",
"f",
",",
"title_pattern",
")",
"if",
"title",
"is",
"None",
":",
"return",
"None",
"if",
"len",
"(",
"title",
")",
">",
"255",
":",
"title",
"=",
"title",
"[",
"0",
":",
"255"... | Assume file pos is at beginning of record and read to end. | [
"Assume",
"file",
"pos",
"is",
"at",
"beginning",
"of",
"record",
"and",
"read",
"to",
"end",
"."
] | [
"\"\"\"Assume file pos is at beginning of record and read to end. Returns all\n components as a Record. Assume components are listed in the following order:\n\n title\n authors\n year\n venue\n id\n arnetid\n references (0 or more lines)\n abstract (0 or 1 ... | [
{
"param": "f",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "f",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
9a89b208e93921f11b22bd13c0b301c1c18928c7 | yuqil/688proj | api/csv_to_graph.py | [
"MIT"
] | Python | read_nodes | null | def read_nodes(csvfile, id_colname):
"""Return a generator which yields the node ids from the given csv file.
:param str csvfile: Path of the csv file to read node ids from.
:param str id_colname: Name of the csv column for the ids.
"""
try:
f = open(csvfile)
except IOError:
logg... | Return a generator which yields the node ids from the given csv file.
:param str csvfile: Path of the csv file to read node ids from.
:param str id_colname: Name of the csv column for the ids.
| Return a generator which yields the node ids from the given csv file. | [
"Return",
"a",
"generator",
"which",
"yields",
"the",
"node",
"ids",
"from",
"the",
"given",
"csv",
"file",
"."
] | def read_nodes(csvfile, id_colname):
try:
f = open(csvfile)
except IOError:
logging.error('id file %s not present' % csvfile)
sys.exit(NO_SUCH_NODE_FILE)
reader = csv.reader(f)
headers = reader.next()
try:
id_idx = headers.index(id_colname)
except ValueError:
... | [
"def",
"read_nodes",
"(",
"csvfile",
",",
"id_colname",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"csvfile",
")",
"except",
"IOError",
":",
"logging",
".",
"error",
"(",
"'id file %s not present'",
"%",
"csvfile",
")",
"sys",
".",
"exit",
"(",
"NO_SUC... | Return a generator which yields the node ids from the given csv file. | [
"Return",
"a",
"generator",
"which",
"yields",
"the",
"node",
"ids",
"from",
"the",
"given",
"csv",
"file",
"."
] | [
"\"\"\"Return a generator which yields the node ids from the given csv file.\n :param str csvfile: Path of the csv file to read node ids from.\n :param str id_colname: Name of the csv column for the ids.\n \"\"\""
] | [
{
"param": "csvfile",
"type": null
},
{
"param": "id_colname",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "csvfile",
"type": null,
"docstring": "Path of the csv file to read node ids from.",
"docstring_tokens": [
"Path",
"of",
"the",
"csv",
"file",
"to",
"read",
"node"... |
9a89b208e93921f11b22bd13c0b301c1c18928c7 | yuqil/688proj | api/csv_to_graph.py | [
"MIT"
] | Python | add_nodes | <not_specific> | def add_nodes(nodes, graph):
"""Add the nodes to the graph and return a dictionary which maps ids as read
from the csv data files to the ids as assigned by igraph.
"""
graph.add_vertices(nodes)
idmap = {v['name']: v.index for v in graph.vs}
return idmap | Add the nodes to the graph and return a dictionary which maps ids as read
from the csv data files to the ids as assigned by igraph.
| Add the nodes to the graph and return a dictionary which maps ids as read
from the csv data files to the ids as assigned by igraph. | [
"Add",
"the",
"nodes",
"to",
"the",
"graph",
"and",
"return",
"a",
"dictionary",
"which",
"maps",
"ids",
"as",
"read",
"from",
"the",
"csv",
"data",
"files",
"to",
"the",
"ids",
"as",
"assigned",
"by",
"igraph",
"."
] | def add_nodes(nodes, graph):
graph.add_vertices(nodes)
idmap = {v['name']: v.index for v in graph.vs}
return idmap | [
"def",
"add_nodes",
"(",
"nodes",
",",
"graph",
")",
":",
"graph",
".",
"add_vertices",
"(",
"nodes",
")",
"idmap",
"=",
"{",
"v",
"[",
"'name'",
"]",
":",
"v",
".",
"index",
"for",
"v",
"in",
"graph",
".",
"vs",
"}",
"return",
"idmap"
] | Add the nodes to the graph and return a dictionary which maps ids as read
from the csv data files to the ids as assigned by igraph. | [
"Add",
"the",
"nodes",
"to",
"the",
"graph",
"and",
"return",
"a",
"dictionary",
"which",
"maps",
"ids",
"as",
"read",
"from",
"the",
"csv",
"data",
"files",
"to",
"the",
"ids",
"as",
"assigned",
"by",
"igraph",
"."
] | [
"\"\"\"Add the nodes to the graph and return a dictionary which maps ids as read\n from the csv data files to the ids as assigned by igraph.\n \"\"\""
] | [
{
"param": "nodes",
"type": null
},
{
"param": "graph",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "nodes",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "graph",
"type": null,
"docstring": null,
"docstring_tokens":... |
9a89b208e93921f11b22bd13c0b301c1c18928c7 | yuqil/688proj | api/csv_to_graph.py | [
"MIT"
] | Python | read_edges | null | def read_edges(csvfile):
"""Return a generator with edges from the csv file. These will need to be
converted to vertex ids if those are not contiguous starting from 0. This
function assumes the source is the first column and the target is the
second.
:param str csvfile: Path of the csv file to read ... | Return a generator with edges from the csv file. These will need to be
converted to vertex ids if those are not contiguous starting from 0. This
function assumes the source is the first column and the target is the
second.
:param str csvfile: Path of the csv file to read edges from.
| Return a generator with edges from the csv file. These will need to be
converted to vertex ids if those are not contiguous starting from 0. This
function assumes the source is the first column and the target is the
second. | [
"Return",
"a",
"generator",
"with",
"edges",
"from",
"the",
"csv",
"file",
".",
"These",
"will",
"need",
"to",
"be",
"converted",
"to",
"vertex",
"ids",
"if",
"those",
"are",
"not",
"contiguous",
"starting",
"from",
"0",
".",
"This",
"function",
"assumes",... | def read_edges(csvfile):
try:
f = open(csvfile)
except IOError:
logging.error('edge id file %s not present' % csvfile)
sys.exit(NO_SUCH_EDGE_FILE)
reader = csv.reader(f)
reader.next()
for row in reader:
yield (row[0], row[1]) | [
"def",
"read_edges",
"(",
"csvfile",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"csvfile",
")",
"except",
"IOError",
":",
"logging",
".",
"error",
"(",
"'edge id file %s not present'",
"%",
"csvfile",
")",
"sys",
".",
"exit",
"(",
"NO_SUCH_EDGE_FILE",
")... | Return a generator with edges from the csv file. | [
"Return",
"a",
"generator",
"with",
"edges",
"from",
"the",
"csv",
"file",
"."
] | [
"\"\"\"Return a generator with edges from the csv file. These will need to be\n converted to vertex ids if those are not contiguous starting from 0. This\n function assumes the source is the first column and the target is the\n second.\n :param str csvfile: Path of the csv file to read edges from.\n ... | [
{
"param": "csvfile",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "csvfile",
"type": null,
"docstring": "Path of the csv file to read edges from.",
"docstring_tokens": [
"Path",
"of",
"the",
"csv",
"file",
"to",
"read",
"edges",
... |
9a89b208e93921f11b22bd13c0b301c1c18928c7 | yuqil/688proj | api/csv_to_graph.py | [
"MIT"
] | Python | convert_edges | null | def convert_edges(edges, idmap):
"""Convert the edge ids read from the csv file to their vertex id
equivalents. This is necessary because igraph assigns its own vertex ids
rather than using the ones used to add edges.
:param iterator edges: An iterable for the edges to be converted. Should be
(s... | Convert the edge ids read from the csv file to their vertex id
equivalents. This is necessary because igraph assigns its own vertex ids
rather than using the ones used to add edges.
:param iterator edges: An iterable for the edges to be converted. Should be
(src, target) tuples
:param dict idmap... | Convert the edge ids read from the csv file to their vertex id
equivalents. This is necessary because igraph assigns its own vertex ids
rather than using the ones used to add edges. | [
"Convert",
"the",
"edge",
"ids",
"read",
"from",
"the",
"csv",
"file",
"to",
"their",
"vertex",
"id",
"equivalents",
".",
"This",
"is",
"necessary",
"because",
"igraph",
"assigns",
"its",
"own",
"vertex",
"ids",
"rather",
"than",
"using",
"the",
"ones",
"u... | def convert_edges(edges, idmap):
for e1, e2 in edges:
try:
src = idmap[e1]
except KeyError:
logging.error('edge src id not present in id file: %s' % e1)
continue
try:
target = idmap[e2]
except KeyError:
logging.error('edge t... | [
"def",
"convert_edges",
"(",
"edges",
",",
"idmap",
")",
":",
"for",
"e1",
",",
"e2",
"in",
"edges",
":",
"try",
":",
"src",
"=",
"idmap",
"[",
"e1",
"]",
"except",
"KeyError",
":",
"logging",
".",
"error",
"(",
"'edge src id not present in id file: %s'",
... | Convert the edge ids read from the csv file to their vertex id
equivalents. | [
"Convert",
"the",
"edge",
"ids",
"read",
"from",
"the",
"csv",
"file",
"to",
"their",
"vertex",
"id",
"equivalents",
"."
] | [
"\"\"\"Convert the edge ids read from the csv file to their vertex id\n equivalents. This is necessary because igraph assigns its own vertex ids\n rather than using the ones used to add edges.\n :param iterator edges: An iterable for the edges to be converted. Should be\n (src, target) tuples\n :... | [
{
"param": "edges",
"type": null
},
{
"param": "idmap",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "edges",
"type": null,
"docstring": "An iterable for the edges to be converted. Should be\n(src, target) tuples",
"docstring_tokens": [
"An",
"iterable",
"for",
"the",
"edges",
"t... |
aa4b198cb0af2f743e6e3cc9ab89d2653c64ecd2 | yuqil/688proj | data_process/get_paper_details.py | [
"MIT"
] | Python | extract_reviews | null | def extract_reviews(url):
"""
Parse the title and abstract of icml 2016
"""
path = "icml_abstracts.txt"
file = codecs.open(path, 'w', encoding='utf8')
if url != None:
response = requests.get(url)
root = BeautifulSoup(response.content, 'html.parser')
papers = root.find_al... |
Parse the title and abstract of icml 2016
| Parse the title and abstract of icml 2016 | [
"Parse",
"the",
"title",
"and",
"abstract",
"of",
"icml",
"2016"
] | def extract_reviews(url):
path = "icml_abstracts.txt"
file = codecs.open(path, 'w', encoding='utf8')
if url != None:
response = requests.get(url)
root = BeautifulSoup(response.content, 'html.parser')
papers = root.find_all("div", {"id" : "schedule"})[0].find_all("li")
print l... | [
"def",
"extract_reviews",
"(",
"url",
")",
":",
"path",
"=",
"\"icml_abstracts.txt\"",
"file",
"=",
"codecs",
".",
"open",
"(",
"path",
",",
"'w'",
",",
"encoding",
"=",
"'utf8'",
")",
"if",
"url",
"!=",
"None",
":",
"response",
"=",
"requests",
".",
"... | Parse the title and abstract of icml 2016 | [
"Parse",
"the",
"title",
"and",
"abstract",
"of",
"icml",
"2016"
] | [
"\"\"\"\n Parse the title and abstract of icml 2016\n \"\"\""
] | [
{
"param": "url",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "url",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
891aa4eddddc3e23206298d37b826b70d328aed7 | yuqil/688proj | pipeline/repdocs.py | [
"MIT"
] | Python | run | null | def run(self):
"""The repdoc for a single paper consists of its title and abstract,
concatenated with space between. The paper records are read from a csv
file and written out as (paper_id, repdoc) pairs.
"""
docs = self.read_paper_repdocs()
rows = ((docid, doc.encode('ut... | The repdoc for a single paper consists of its title and abstract,
concatenated with space between. The paper records are read from a csv
file and written out as (paper_id, repdoc) pairs.
| The repdoc for a single paper consists of its title and abstract,
concatenated with space between. The paper records are read from a csv
file and written out as (paper_id, repdoc) pairs. | [
"The",
"repdoc",
"for",
"a",
"single",
"paper",
"consists",
"of",
"its",
"title",
"and",
"abstract",
"concatenated",
"with",
"space",
"between",
".",
"The",
"paper",
"records",
"are",
"read",
"from",
"a",
"csv",
"file",
"and",
"written",
"out",
"as",
"(",
... | def run(self):
docs = self.read_paper_repdocs()
rows = ((docid, doc.encode('utf-8')) for docid, doc in docs)
util.write_csv_to_fwrapper(self.output(), ('paper_id', 'doc'), rows) | [
"def",
"run",
"(",
"self",
")",
":",
"docs",
"=",
"self",
".",
"read_paper_repdocs",
"(",
")",
"rows",
"=",
"(",
"(",
"docid",
",",
"doc",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"for",
"docid",
",",
"doc",
"in",
"docs",
")",
"util",
".",
"write... | The repdoc for a single paper consists of its title and abstract,
concatenated with space between. | [
"The",
"repdoc",
"for",
"a",
"single",
"paper",
"consists",
"of",
"its",
"title",
"and",
"abstract",
"concatenated",
"with",
"space",
"between",
"."
] | [
"\"\"\"The repdoc for a single paper consists of its title and abstract,\n concatenated with space between. The paper records are read from a csv\n file and written out as (paper_id, repdoc) pairs.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
891aa4eddddc3e23206298d37b826b70d328aed7 | yuqil/688proj | pipeline/repdocs.py | [
"MIT"
] | Python | read_lcc_author_repdocs | <not_specific> | def read_lcc_author_repdocs(self):
"""Read and return an iterator over the author repdoc corpus, which excludes
the authors not in the LCC.
"""
author_repdoc_file, _, lcc_idmap_file = self.input()
with lcc_idmap_file.open() as lcc_idmap_f:
lcc_author_df = pd.read_csv... | Read and return an iterator over the author repdoc corpus, which excludes
the authors not in the LCC.
| Read and return an iterator over the author repdoc corpus, which excludes
the authors not in the LCC. | [
"Read",
"and",
"return",
"an",
"iterator",
"over",
"the",
"author",
"repdoc",
"corpus",
"which",
"excludes",
"the",
"authors",
"not",
"in",
"the",
"LCC",
"."
] | def read_lcc_author_repdocs(self):
author_repdoc_file, _, lcc_idmap_file = self.input()
with lcc_idmap_file.open() as lcc_idmap_f:
lcc_author_df = pd.read_csv(lcc_idmap_f, header=0, usecols=(0,))
lcc_author_ids = lcc_author_df['author_id'].values
csv.field_size_limit(sys.... | [
"def",
"read_lcc_author_repdocs",
"(",
"self",
")",
":",
"author_repdoc_file",
",",
"_",
",",
"lcc_idmap_file",
"=",
"self",
".",
"input",
"(",
")",
"with",
"lcc_idmap_file",
".",
"open",
"(",
")",
"as",
"lcc_idmap_f",
":",
"lcc_author_df",
"=",
"pd",
".",
... | Read and return an iterator over the author repdoc corpus, which excludes
the authors not in the LCC. | [
"Read",
"and",
"return",
"an",
"iterator",
"over",
"the",
"author",
"repdoc",
"corpus",
"which",
"excludes",
"the",
"authors",
"not",
"in",
"the",
"LCC",
"."
] | [
"\"\"\"Read and return an iterator over the author repdoc corpus, which excludes\n the authors not in the LCC.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0673c4a962a67a0d0c6374c6703a20a7b3a8d1d0 | dalegaspi/bu-ms-s2-tp | app.py | [
"Unlicense"
] | Python | dump_configuration | null | def dump_configuration():
"""
Dumps the app configuration in log
:return:
"""
for skey, svalue in app_config.items():
for key, value in svalue.items():
logger.info("%s:%s = %s", skey, key, value) |
Dumps the app configuration in log
:return:
| Dumps the app configuration in log | [
"Dumps",
"the",
"app",
"configuration",
"in",
"log"
] | def dump_configuration():
for skey, svalue in app_config.items():
for key, value in svalue.items():
logger.info("%s:%s = %s", skey, key, value) | [
"def",
"dump_configuration",
"(",
")",
":",
"for",
"skey",
",",
"svalue",
"in",
"app_config",
".",
"items",
"(",
")",
":",
"for",
"key",
",",
"value",
"in",
"svalue",
".",
"items",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"%s:%s = %s\"",
",",
"sk... | Dumps the app configuration in log | [
"Dumps",
"the",
"app",
"configuration",
"in",
"log"
] | [
"\"\"\"\n Dumps the app configuration in log\n :return:\n \"\"\""
] | [] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
0673c4a962a67a0d0c6374c6703a20a7b3a8d1d0 | dalegaspi/bu-ms-s2-tp | app.py | [
"Unlicense"
] | Python | run | null | def run():
"""
Initialize and runs the app (blocks until the GUI is destroyed)
:return:
"""
dump_configuration()
state = AppState()
controller = AppController(state)
AppController.copy_to_clipboard('hello')
render_main_view(controller=controller) |
Initialize and runs the app (blocks until the GUI is destroyed)
:return:
| Initialize and runs the app (blocks until the GUI is destroyed) | [
"Initialize",
"and",
"runs",
"the",
"app",
"(",
"blocks",
"until",
"the",
"GUI",
"is",
"destroyed",
")"
] | def run():
dump_configuration()
state = AppState()
controller = AppController(state)
AppController.copy_to_clipboard('hello')
render_main_view(controller=controller) | [
"def",
"run",
"(",
")",
":",
"dump_configuration",
"(",
")",
"state",
"=",
"AppState",
"(",
")",
"controller",
"=",
"AppController",
"(",
"state",
")",
"AppController",
".",
"copy_to_clipboard",
"(",
"'hello'",
")",
"render_main_view",
"(",
"controller",
"=",
... | Initialize and runs the app (blocks until the GUI is destroyed) | [
"Initialize",
"and",
"runs",
"the",
"app",
"(",
"blocks",
"until",
"the",
"GUI",
"is",
"destroyed",
")"
] | [
"\"\"\"\n Initialize and runs the app (blocks until the GUI is destroyed)\n :return:\n \"\"\""
] | [] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
dd6a7a6ad908b50c5634c909b586708359fbb7b7 | dalegaspi/bu-ms-s2-tp | imageattributes.py | [
"Unlicense"
] | Python | __parse_exif | null | def __parse_exif(self):
"""
parses exif then stores internally in attr_dict
:return:
"""
self.attr_dict = {}
for k in EXIF_TAGS_OF_INTEREST:
try:
self.attr_dict[k] = self.exif[
ImageAttributes.exif_attribute_as_index(k)]
... |
parses exif then stores internally in attr_dict
:return:
| parses exif then stores internally in attr_dict | [
"parses",
"exif",
"then",
"stores",
"internally",
"in",
"attr_dict"
] | def __parse_exif(self):
self.attr_dict = {}
for k in EXIF_TAGS_OF_INTEREST:
try:
self.attr_dict[k] = self.exif[
ImageAttributes.exif_attribute_as_index(k)]
except (KeyError, Exception):
pass | [
"def",
"__parse_exif",
"(",
"self",
")",
":",
"self",
".",
"attr_dict",
"=",
"{",
"}",
"for",
"k",
"in",
"EXIF_TAGS_OF_INTEREST",
":",
"try",
":",
"self",
".",
"attr_dict",
"[",
"k",
"]",
"=",
"self",
".",
"exif",
"[",
"ImageAttributes",
".",
"exif_att... | parses exif then stores internally in attr_dict | [
"parses",
"exif",
"then",
"stores",
"internally",
"in",
"attr_dict"
] | [
"\"\"\"\n parses exif then stores internally in attr_dict\n\n :return:\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
dd6a7a6ad908b50c5634c909b586708359fbb7b7 | dalegaspi/bu-ms-s2-tp | imageattributes.py | [
"Unlicense"
] | Python | exif_attribute_as_index | <not_specific> | def exif_attribute_as_index(attribute_name):
"""
PIL.ExifTags.TAGS is a dictionary of indices with corresponding names.
This is a convenience function that returns the EXIF index for
the corresponding name to lessen the confusion
:param attribute_name:
:return:
"... |
PIL.ExifTags.TAGS is a dictionary of indices with corresponding names.
This is a convenience function that returns the EXIF index for
the corresponding name to lessen the confusion
:param attribute_name:
:return:
| PIL.ExifTags.TAGS is a dictionary of indices with corresponding names.
This is a convenience function that returns the EXIF index for
the corresponding name to lessen the confusion | [
"PIL",
".",
"ExifTags",
".",
"TAGS",
"is",
"a",
"dictionary",
"of",
"indices",
"with",
"corresponding",
"names",
".",
"This",
"is",
"a",
"convenience",
"function",
"that",
"returns",
"the",
"EXIF",
"index",
"for",
"the",
"corresponding",
"name",
"to",
"lesse... | def exif_attribute_as_index(attribute_name):
index = next(k for k, v in PIL.ExifTags.TAGS.items()
if v.lower() == attribute_name.lower())
return index | [
"def",
"exif_attribute_as_index",
"(",
"attribute_name",
")",
":",
"index",
"=",
"next",
"(",
"k",
"for",
"k",
",",
"v",
"in",
"PIL",
".",
"ExifTags",
".",
"TAGS",
".",
"items",
"(",
")",
"if",
"v",
".",
"lower",
"(",
")",
"==",
"attribute_name",
"."... | PIL.ExifTags.TAGS is a dictionary of indices with corresponding names. | [
"PIL",
".",
"ExifTags",
".",
"TAGS",
"is",
"a",
"dictionary",
"of",
"indices",
"with",
"corresponding",
"names",
"."
] | [
"\"\"\"\n PIL.ExifTags.TAGS is a dictionary of indices with corresponding names.\n This is a convenience function that returns the EXIF index for\n the corresponding name to lessen the confusion\n\n :param attribute_name:\n :return:\n \"\"\""
] | [
{
"param": "attribute_name",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "attribute_name",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": nu... |
dd6a7a6ad908b50c5634c909b586708359fbb7b7 | dalegaspi/bu-ms-s2-tp | imageattributes.py | [
"Unlicense"
] | Python | __attr_dict_as_string | <not_specific> | def __attr_dict_as_string(self):
"""
return the EXIF as a newline separated key-value pairs
:return:
"""
return 'No EXIF Data' if len(self.attr_dict) == 0 \
else '\n'.join([f'{k}: {v}' for k, v in self.attr_dict.items()]) |
return the EXIF as a newline separated key-value pairs
:return:
| return the EXIF as a newline separated key-value pairs | [
"return",
"the",
"EXIF",
"as",
"a",
"newline",
"separated",
"key",
"-",
"value",
"pairs"
] | def __attr_dict_as_string(self):
return 'No EXIF Data' if len(self.attr_dict) == 0 \
else '\n'.join([f'{k}: {v}' for k, v in self.attr_dict.items()]) | [
"def",
"__attr_dict_as_string",
"(",
"self",
")",
":",
"return",
"'No EXIF Data'",
"if",
"len",
"(",
"self",
".",
"attr_dict",
")",
"==",
"0",
"else",
"'\\n'",
".",
"join",
"(",
"[",
"f'{k}: {v}'",
"for",
"k",
",",
"v",
"in",
"self",
".",
"attr_dict",
... | return the EXIF as a newline separated key-value pairs | [
"return",
"the",
"EXIF",
"as",
"a",
"newline",
"separated",
"key",
"-",
"value",
"pairs"
] | [
"\"\"\"\n return the EXIF as a newline separated key-value pairs\n\n :return:\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
b023ffc4bd1b4eabb4a072efbe90ab2eb78bcec8 | dalegaspi/bu-ms-s2-tp | appstate.py | [
"Unlicense"
] | Python | has_catalog | <not_specific> | def has_catalog(self):
"""
returns true if there is a catalog
:return:
"""
return self.__image_catalog is not None |
returns true if there is a catalog
:return:
| returns true if there is a catalog | [
"returns",
"true",
"if",
"there",
"is",
"a",
"catalog"
] | def has_catalog(self):
return self.__image_catalog is not None | [
"def",
"has_catalog",
"(",
"self",
")",
":",
"return",
"self",
".",
"__image_catalog",
"is",
"not",
"None"
] | returns true if there is a catalog | [
"returns",
"true",
"if",
"there",
"is",
"a",
"catalog"
] | [
"\"\"\"\n returns true if there is a catalog\n\n :return:\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
b023ffc4bd1b4eabb4a072efbe90ab2eb78bcec8 | dalegaspi/bu-ms-s2-tp | appstate.py | [
"Unlicense"
] | Python | is_enabled | <not_specific> | def is_enabled(self):
"""
if the app state has no catalog associated with it, it should be
'disabled' state--i.e., the app will not have any of widgets available
for interaction
:return: True if enabled
"""
return self.has_catalog() |
if the app state has no catalog associated with it, it should be
'disabled' state--i.e., the app will not have any of widgets available
for interaction
:return: True if enabled
| if the app state has no catalog associated with it, it should be
'disabled' state--i.e., the app will not have any of widgets available
for interaction | [
"if",
"the",
"app",
"state",
"has",
"no",
"catalog",
"associated",
"with",
"it",
"it",
"should",
"be",
"'",
"disabled",
"'",
"state",
"--",
"i",
".",
"e",
".",
"the",
"app",
"will",
"not",
"have",
"any",
"of",
"widgets",
"available",
"for",
"interactio... | def is_enabled(self):
return self.has_catalog() | [
"def",
"is_enabled",
"(",
"self",
")",
":",
"return",
"self",
".",
"has_catalog",
"(",
")"
] | if the app state has no catalog associated with it, it should be
'disabled' state--i.e., the app will not have any of widgets available
for interaction | [
"if",
"the",
"app",
"state",
"has",
"no",
"catalog",
"associated",
"with",
"it",
"it",
"should",
"be",
"'",
"disabled",
"'",
"state",
"--",
"i",
".",
"e",
".",
"the",
"app",
"will",
"not",
"have",
"any",
"of",
"widgets",
"available",
"for",
"interactio... | [
"\"\"\"\n if the app state has no catalog associated with it, it should be\n 'disabled' state--i.e., the app will not have any of widgets available\n for interaction\n\n :return: True if enabled\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "True if enabled",
"docstring_tokens": [
"True",
"if",
"enabled"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
0064b760242ed3b2a8a930626fc8e9a330e65c9b | dalegaspi/bu-ms-s2-tp | imagecatalog.py | [
"Unlicense"
] | Python | __build_images | <not_specific> | def __build_images(image_files_list: list):
"""
create a list of records of images from the list of path
:param image_files_list: image paths
:return: record list
"""
# todo maybe optimize by lazy loading the 'img' property
return [{K_PATH: p, K_IMG: Image(p)} fo... |
create a list of records of images from the list of path
:param image_files_list: image paths
:return: record list
| create a list of records of images from the list of path | [
"create",
"a",
"list",
"of",
"records",
"of",
"images",
"from",
"the",
"list",
"of",
"path"
] | def __build_images(image_files_list: list):
return [{K_PATH: p, K_IMG: Image(p)} for p in image_files_list] | [
"def",
"__build_images",
"(",
"image_files_list",
":",
"list",
")",
":",
"return",
"[",
"{",
"K_PATH",
":",
"p",
",",
"K_IMG",
":",
"Image",
"(",
"p",
")",
"}",
"for",
"p",
"in",
"image_files_list",
"]"
] | create a list of records of images from the list of path | [
"create",
"a",
"list",
"of",
"records",
"of",
"images",
"from",
"the",
"list",
"of",
"path"
] | [
"\"\"\"\n create a list of records of images from the list of path\n\n :param image_files_list: image paths\n :return: record list\n \"\"\"",
"# todo maybe optimize by lazy loading the 'img' property"
] | [
{
"param": "image_files_list",
"type": "list"
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "image_files_list",
"type": "list",
"docstring": null,
"docstring_tokens": [
"None"
],
"default"... |
0064b760242ed3b2a8a930626fc8e9a330e65c9b | dalegaspi/bu-ms-s2-tp | imagecatalog.py | [
"Unlicense"
] | Python | __apply_ratings | null | def __apply_ratings(self, ratings):
"""
Internal method to apply the ratings to the images from the catalog
from the ratings file
:param ratings: ratings list
:return: None
"""
for rec in self.__image_records:
name = rec[K_IMG].get_name()
r... |
Internal method to apply the ratings to the images from the catalog
from the ratings file
:param ratings: ratings list
:return: None
| Internal method to apply the ratings to the images from the catalog
from the ratings file | [
"Internal",
"method",
"to",
"apply",
"the",
"ratings",
"to",
"the",
"images",
"from",
"the",
"catalog",
"from",
"the",
"ratings",
"file"
] | def __apply_ratings(self, ratings):
for rec in self.__image_records:
name = rec[K_IMG].get_name()
rating = ImageCatalog.__find_rating(name, ratings)
rec[K_IMG].set_rating(ImageRating(rating)) | [
"def",
"__apply_ratings",
"(",
"self",
",",
"ratings",
")",
":",
"for",
"rec",
"in",
"self",
".",
"__image_records",
":",
"name",
"=",
"rec",
"[",
"K_IMG",
"]",
".",
"get_name",
"(",
")",
"rating",
"=",
"ImageCatalog",
".",
"__find_rating",
"(",
"name",
... | Internal method to apply the ratings to the images from the catalog
from the ratings file | [
"Internal",
"method",
"to",
"apply",
"the",
"ratings",
"to",
"the",
"images",
"from",
"the",
"catalog",
"from",
"the",
"ratings",
"file"
] | [
"\"\"\"\n Internal method to apply the ratings to the images from the catalog\n from the ratings file\n :param ratings: ratings list\n :return: None\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "ratings",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
0064b760242ed3b2a8a930626fc8e9a330e65c9b | dalegaspi/bu-ms-s2-tp | imagecatalog.py | [
"Unlicense"
] | Python | __find_rating | <not_specific> | def __find_rating(name, ratings):
"""
find the rating in list with specified name; note that not all entries
in the directory will automatically have an entry in the ratings file
so we need to 'find' it; if not found return 0 (no rating)
:param name: name of image
:param... |
find the rating in list with specified name; note that not all entries
in the directory will automatically have an entry in the ratings file
so we need to 'find' it; if not found return 0 (no rating)
:param name: name of image
:param ratings: list
:return: ImageRating o... | find the rating in list with specified name; note that not all entries
in the directory will automatically have an entry in the ratings file
so we need to 'find' it; if not found return 0 (no rating) | [
"find",
"the",
"rating",
"in",
"list",
"with",
"specified",
"name",
";",
"note",
"that",
"not",
"all",
"entries",
"in",
"the",
"directory",
"will",
"automatically",
"have",
"an",
"entry",
"in",
"the",
"ratings",
"file",
"so",
"we",
"need",
"to",
"'",
"fi... | def __find_rating(name, ratings):
first_or_default = next(filter(lambda r: r[K_NAME] == name, ratings),
None)
try:
return ImageRating.MIN_RATING if first_or_default is None \
else int(first_or_default[K_RATING])
except ValueError as err... | [
"def",
"__find_rating",
"(",
"name",
",",
"ratings",
")",
":",
"first_or_default",
"=",
"next",
"(",
"filter",
"(",
"lambda",
"r",
":",
"r",
"[",
"K_NAME",
"]",
"==",
"name",
",",
"ratings",
")",
",",
"None",
")",
"try",
":",
"return",
"ImageRating",
... | find the rating in list with specified name; note that not all entries
in the directory will automatically have an entry in the ratings file
so we need to 'find' it; if not found return 0 (no rating) | [
"find",
"the",
"rating",
"in",
"list",
"with",
"specified",
"name",
";",
"note",
"that",
"not",
"all",
"entries",
"in",
"the",
"directory",
"will",
"automatically",
"have",
"an",
"entry",
"in",
"the",
"ratings",
"file",
"so",
"we",
"need",
"to",
"'",
"fi... | [
"\"\"\"\n find the rating in list with specified name; note that not all entries\n in the directory will automatically have an entry in the ratings file\n so we need to 'find' it; if not found return 0 (no rating)\n\n :param name: name of image\n :param ratings: list\n :ret... | [
{
"param": "name",
"type": null
},
{
"param": "ratings",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "name",
"type": null,
"docstring": "name of image",
"docstring_tokens": [
"name",
"of",
"ima... |
c7abf9c5b67fca74f13dc9593b50347b3323919c | mochaccino-latte/ur5-ros-control | forward_kinematics.py | [
"Apache-2.0"
] | Python | ur2ros | <not_specific> | def ur2ros(ur_pose):
"""Transform pose from UR format to ROS Pose format.
Args:
ur_pose: A pose in UR format [px, py, pz, rx, ry, rz]
(type: list)
Returns:
An HTM (type: Pose).
"""
# ROS pose
ros_pose = Pose()
# ROS position
ros_pose.position.x = ur_pose[0]
... | Transform pose from UR format to ROS Pose format.
Args:
ur_pose: A pose in UR format [px, py, pz, rx, ry, rz]
(type: list)
Returns:
An HTM (type: Pose).
| Transform pose from UR format to ROS Pose format. | [
"Transform",
"pose",
"from",
"UR",
"format",
"to",
"ROS",
"Pose",
"format",
"."
] | def ur2ros(ur_pose):
ros_pose = Pose()
ros_pose.position.x = ur_pose[0]
ros_pose.position.y = ur_pose[1]
ros_pose.position.z = ur_pose[2]
angle = sqrt(ur_pose[3] ** 2 + ur_pose[4] ** 2 + ur_pose[5] ** 2)
direction = [i / angle for i in ur_pose[3:6]]
np_T = tf.rotation_matrix(angle, direction... | [
"def",
"ur2ros",
"(",
"ur_pose",
")",
":",
"ros_pose",
"=",
"Pose",
"(",
")",
"ros_pose",
".",
"position",
".",
"x",
"=",
"ur_pose",
"[",
"0",
"]",
"ros_pose",
".",
"position",
".",
"y",
"=",
"ur_pose",
"[",
"1",
"]",
"ros_pose",
".",
"position",
"... | Transform pose from UR format to ROS Pose format. | [
"Transform",
"pose",
"from",
"UR",
"format",
"to",
"ROS",
"Pose",
"format",
"."
] | [
"\"\"\"Transform pose from UR format to ROS Pose format.\n\n Args:\n ur_pose: A pose in UR format [px, py, pz, rx, ry, rz]\n (type: list)\n\n Returns:\n An HTM (type: Pose).\n \"\"\"",
"# ROS pose",
"# ROS position",
"# Ros orientation"
] | [
{
"param": "ur_pose",
"type": null
}
] | {
"returns": [
{
"docstring": "An HTM (type: Pose).",
"docstring_tokens": [
"An",
"HTM",
"(",
"type",
":",
"Pose",
")",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "ur_pose",
"t... |
c7abf9c5b67fca74f13dc9593b50347b3323919c | mochaccino-latte/ur5-ros-control | forward_kinematics.py | [
"Apache-2.0"
] | Python | ros2np | <not_specific> | def ros2np(ros_pose):
"""Transform pose from ROS Pose format to np.array format.
Args:
ros_pose: A pose in ROS Pose format (type: Pose)
Returns:
An HTM (type: np.array).
"""
# orientation
np_pose = tf.quaternion_matrix([ros_pose.orientation.x, ros_pose.orientation.y, \
... | Transform pose from ROS Pose format to np.array format.
Args:
ros_pose: A pose in ROS Pose format (type: Pose)
Returns:
An HTM (type: np.array).
| Transform pose from ROS Pose format to np.array format. | [
"Transform",
"pose",
"from",
"ROS",
"Pose",
"format",
"to",
"np",
".",
"array",
"format",
"."
] | def ros2np(ros_pose):
np_pose = tf.quaternion_matrix([ros_pose.orientation.x, ros_pose.orientation.y, \
ros_pose.orientation.z, ros_pose.orientation.w])
np_pose[0][3] = ros_pose.position.x
np_pose[1][3] = ros_pose.position.y
np_pose[2][3] = ros_pose.position.z
ret... | [
"def",
"ros2np",
"(",
"ros_pose",
")",
":",
"np_pose",
"=",
"tf",
".",
"quaternion_matrix",
"(",
"[",
"ros_pose",
".",
"orientation",
".",
"x",
",",
"ros_pose",
".",
"orientation",
".",
"y",
",",
"ros_pose",
".",
"orientation",
".",
"z",
",",
"ros_pose",... | Transform pose from ROS Pose format to np.array format. | [
"Transform",
"pose",
"from",
"ROS",
"Pose",
"format",
"to",
"np",
".",
"array",
"format",
"."
] | [
"\"\"\"Transform pose from ROS Pose format to np.array format.\n\n Args:\n ros_pose: A pose in ROS Pose format (type: Pose)\n\n Returns:\n An HTM (type: np.array).\n \"\"\"",
"# orientation",
"# position"
] | [
{
"param": "ros_pose",
"type": null
}
] | {
"returns": [
{
"docstring": "An HTM (type: np.array).",
"docstring_tokens": [
"An",
"HTM",
"(",
"type",
":",
"np",
".",
"array",
")",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"... |
c7abf9c5b67fca74f13dc9593b50347b3323919c | mochaccino-latte/ur5-ros-control | forward_kinematics.py | [
"Apache-2.0"
] | Python | np2ros | <not_specific> | def np2ros(np_pose):
"""Transform pose from np.array format to ROS Pose format.
Args:
np_pose: A pose in np.array format (type: np.array)
Returns:
An HTM (type: Pose).
"""
# ROS pose
ros_pose = Pose()
# ROS position
ros_pose.position.x = np_pose[0, 3]
ros_pose.pos... | Transform pose from np.array format to ROS Pose format.
Args:
np_pose: A pose in np.array format (type: np.array)
Returns:
An HTM (type: Pose).
| Transform pose from np.array format to ROS Pose format. | [
"Transform",
"pose",
"from",
"np",
".",
"array",
"format",
"to",
"ROS",
"Pose",
"format",
"."
] | def np2ros(np_pose):
ros_pose = Pose()
ros_pose.position.x = np_pose[0, 3]
ros_pose.position.y = np_pose[1, 3]
ros_pose.position.z = np_pose[2, 3]
np_q = tf.quaternion_from_matrix(np_pose)
ros_pose.orientation.x = np_q[0]
ros_pose.orientation.y = np_q[1]
ros_pose.orientation.z = np_q[2]
... | [
"def",
"np2ros",
"(",
"np_pose",
")",
":",
"ros_pose",
"=",
"Pose",
"(",
")",
"ros_pose",
".",
"position",
".",
"x",
"=",
"np_pose",
"[",
"0",
",",
"3",
"]",
"ros_pose",
".",
"position",
".",
"y",
"=",
"np_pose",
"[",
"1",
",",
"3",
"]",
"ros_pos... | Transform pose from np.array format to ROS Pose format. | [
"Transform",
"pose",
"from",
"np",
".",
"array",
"format",
"to",
"ROS",
"Pose",
"format",
"."
] | [
"\"\"\"Transform pose from np.array format to ROS Pose format.\n\n Args:\n np_pose: A pose in np.array format (type: np.array)\n\n Returns:\n An HTM (type: Pose).\n \"\"\"",
"# ROS pose",
"# ROS position",
"# ROS orientation"
] | [
{
"param": "np_pose",
"type": null
}
] | {
"returns": [
{
"docstring": "An HTM (type: Pose).",
"docstring_tokens": [
"An",
"HTM",
"(",
"type",
":",
"Pose",
")",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "np_pose",
"t... |
c7abf9c5b67fca74f13dc9593b50347b3323919c | mochaccino-latte/ur5-ros-control | forward_kinematics.py | [
"Apache-2.0"
] | Python | select | <not_specific> | def select(q_sols, q_d, w=[1]*6):
"""Select the optimal solutions among a set of feasible joint value
solutions.
Args:
q_sols: A set of feasible joint value solutions (unit: radian)
q_d: A list of desired joint value solution (unit: radian)
w: A list of weight corresponding to ro... | Select the optimal solutions among a set of feasible joint value
solutions.
Args:
q_sols: A set of feasible joint value solutions (unit: radian)
q_d: A list of desired joint value solution (unit: radian)
w: A list of weight corresponding to robot joints
Returns:
A list o... | Select the optimal solutions among a set of feasible joint value
solutions. | [
"Select",
"the",
"optimal",
"solutions",
"among",
"a",
"set",
"of",
"feasible",
"joint",
"value",
"solutions",
"."
] | def select(q_sols, q_d, w=[1]*6):
error = []
for q in q_sols:
error.append(sum([w[i] * (q[i] - q_d[i]) ** 2 for i in range(6)]))
return q_sols[error.index(min(error))] | [
"def",
"select",
"(",
"q_sols",
",",
"q_d",
",",
"w",
"=",
"[",
"1",
"]",
"*",
"6",
")",
":",
"error",
"=",
"[",
"]",
"for",
"q",
"in",
"q_sols",
":",
"error",
".",
"append",
"(",
"sum",
"(",
"[",
"w",
"[",
"i",
"]",
"*",
"(",
"q",
"[",
... | Select the optimal solutions among a set of feasible joint value
solutions. | [
"Select",
"the",
"optimal",
"solutions",
"among",
"a",
"set",
"of",
"feasible",
"joint",
"value",
"solutions",
"."
] | [
"\"\"\"Select the optimal solutions among a set of feasible joint value\n solutions.\n\n Args:\n q_sols: A set of feasible joint value solutions (unit: radian)\n q_d: A list of desired joint value solution (unit: radian)\n w: A list of weight corresponding to robot joints\n\n Return... | [
{
"param": "q_sols",
"type": null
},
{
"param": "q_d",
"type": null
},
{
"param": "w",
"type": null
}
] | {
"returns": [
{
"docstring": "A list of optimal joint value solution.",
"docstring_tokens": [
"A",
"list",
"of",
"optimal",
"joint",
"value",
"solution",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
... |
c7abf9c5b67fca74f13dc9593b50347b3323919c | mochaccino-latte/ur5-ros-control | forward_kinematics.py | [
"Apache-2.0"
] | Python | HTM | <not_specific> | def HTM(i, theta):
"""Calculate the HTM between two links.
Args:
i: A target index of joint value.
theta: A list of joint value solution. (unit: radian)
Returns:
An HTM of Link l w.r.t. Link l-1, where l = i + 1.
"""
Rot_z = np.matrix(np.identity(4))
Rot_z[0, 0] = Rot_... | Calculate the HTM between two links.
Args:
i: A target index of joint value.
theta: A list of joint value solution. (unit: radian)
Returns:
An HTM of Link l w.r.t. Link l-1, where l = i + 1.
| Calculate the HTM between two links. | [
"Calculate",
"the",
"HTM",
"between",
"two",
"links",
"."
] | def HTM(i, theta):
Rot_z = np.matrix(np.identity(4))
Rot_z[0, 0] = Rot_z[1, 1] = cos(theta[i])
Rot_z[0, 1] = -sin(theta[i])
Rot_z[1, 0] = sin(theta[i])
Trans_z = np.matrix(np.identity(4))
Trans_z[2, 3] = d[i]
Trans_x = np.matrix(np.identity(4))
Trans_x[0, 3] = a[i]
Rot_x = np.matrix(... | [
"def",
"HTM",
"(",
"i",
",",
"theta",
")",
":",
"Rot_z",
"=",
"np",
".",
"matrix",
"(",
"np",
".",
"identity",
"(",
"4",
")",
")",
"Rot_z",
"[",
"0",
",",
"0",
"]",
"=",
"Rot_z",
"[",
"1",
",",
"1",
"]",
"=",
"cos",
"(",
"theta",
"[",
"i"... | Calculate the HTM between two links. | [
"Calculate",
"the",
"HTM",
"between",
"two",
"links",
"."
] | [
"\"\"\"Calculate the HTM between two links.\n\n Args:\n i: A target index of joint value.\n theta: A list of joint value solution. (unit: radian)\n\n Returns:\n An HTM of Link l w.r.t. Link l-1, where l = i + 1.\n \"\"\""
] | [
{
"param": "i",
"type": null
},
{
"param": "theta",
"type": null
}
] | {
"returns": [
{
"docstring": "An HTM of Link l w.r.t.",
"docstring_tokens": [
"An",
"HTM",
"of",
"Link",
"l",
"w",
".",
"r",
".",
"t",
"."
],
"type": null
}
],
"raises": [],
"params": [
{... |
c7abf9c5b67fca74f13dc9593b50347b3323919c | mochaccino-latte/ur5-ros-control | forward_kinematics.py | [
"Apache-2.0"
] | Python | fwd_kin | <not_specific> | def fwd_kin(theta, i_unit='r', o_unit='n'):
"""Solve the HTM based on a list of joint values.
Args:
theta: A list of joint values. (unit: radian)
i_unit: Output format. 'r' for radian; 'd' for degree.
o_unit: Output format. 'n' for np.array; 'p' for ROS Pose.
Returns:
The H... | Solve the HTM based on a list of joint values.
Args:
theta: A list of joint values. (unit: radian)
i_unit: Output format. 'r' for radian; 'd' for degree.
o_unit: Output format. 'n' for np.array; 'p' for ROS Pose.
Returns:
The HTM of end-effector joint w.r.t. base joint
| Solve the HTM based on a list of joint values. | [
"Solve",
"the",
"HTM",
"based",
"on",
"a",
"list",
"of",
"joint",
"values",
"."
] | def fwd_kin(theta, i_unit='r', o_unit='n'):
T_06 = np.matrix(np.identity(4))
if i_unit == 'd':
theta = [radians(i) for i in theta]
for i in range(6):
T_06 *= HTM(i, theta)
if o_unit == 'n':
return T_06
elif o_unit == 'p':
return np2ros(T_06) | [
"def",
"fwd_kin",
"(",
"theta",
",",
"i_unit",
"=",
"'r'",
",",
"o_unit",
"=",
"'n'",
")",
":",
"T_06",
"=",
"np",
".",
"matrix",
"(",
"np",
".",
"identity",
"(",
"4",
")",
")",
"if",
"i_unit",
"==",
"'d'",
":",
"theta",
"=",
"[",
"radians",
"(... | Solve the HTM based on a list of joint values. | [
"Solve",
"the",
"HTM",
"based",
"on",
"a",
"list",
"of",
"joint",
"values",
"."
] | [
"\"\"\"Solve the HTM based on a list of joint values.\n\n Args:\n theta: A list of joint values. (unit: radian)\n i_unit: Output format. 'r' for radian; 'd' for degree.\n o_unit: Output format. 'n' for np.array; 'p' for ROS Pose.\n\n Returns:\n The HTM of end-effector joint w.r.t. ... | [
{
"param": "theta",
"type": null
},
{
"param": "i_unit",
"type": null
},
{
"param": "o_unit",
"type": null
}
] | {
"returns": [
{
"docstring": "The HTM of end-effector joint w.r.t. base joint",
"docstring_tokens": [
"The",
"HTM",
"of",
"end",
"-",
"effector",
"joint",
"w",
".",
"r",
".",
"t",
".",
"bas... |
d261242c58a314cbd9572d3302545d35c222e3d7 | frankjoshua/docker-ros2-unity-tcp-endpoint | src/unity-ros-tcp-endpoint/ros_tcp_endpoint/service.py | [
"Apache-2.0"
] | Python | send | <not_specific> | def send(self, data):
"""
Takes in serialized message data from source outside of the ROS network,
deserializes it into it's class, calls the service with the message, and returns
the service's response.
Args:
data: The already serialized message_class data coming fr... |
Takes in serialized message data from source outside of the ROS network,
deserializes it into it's class, calls the service with the message, and returns
the service's response.
Args:
data: The already serialized message_class data coming from outside of ROS
Return... | Takes in serialized message data from source outside of the ROS network,
deserializes it into it's class, calls the service with the message, and returns
the service's response. | [
"Takes",
"in",
"serialized",
"message",
"data",
"from",
"source",
"outside",
"of",
"the",
"ROS",
"network",
"deserializes",
"it",
"into",
"it",
"'",
"s",
"class",
"calls",
"the",
"service",
"with",
"the",
"message",
"and",
"returns",
"the",
"service",
"'",
... | def send(self, data):
message_type = type(self.req)
message = deserialize_message(data, message_type)
if not self.cli.service_is_ready():
self.get_logger().error('Ignoring service call to {} - service is not ready.'.format(self.service_topic))
return None
self.fut... | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"message_type",
"=",
"type",
"(",
"self",
".",
"req",
")",
"message",
"=",
"deserialize_message",
"(",
"data",
",",
"message_type",
")",
"if",
"not",
"self",
".",
"cli",
".",
"service_is_ready",
"(",
"... | Takes in serialized message data from source outside of the ROS network,
deserializes it into it's class, calls the service with the message, and returns
the service's response. | [
"Takes",
"in",
"serialized",
"message",
"data",
"from",
"source",
"outside",
"of",
"the",
"ROS",
"network",
"deserializes",
"it",
"into",
"it",
"'",
"s",
"class",
"calls",
"the",
"service",
"with",
"the",
"message",
"and",
"returns",
"the",
"service",
"'",
... | [
"\"\"\"\n Takes in serialized message data from source outside of the ROS network,\n deserializes it into it's class, calls the service with the message, and returns\n the service's response.\n\n Args:\n data: The already serialized message_class data coming from outside of RO... | [
{
"param": "self",
"type": null
},
{
"param": "data",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
32b8ef37fe48f29534982666bdf40b8a723ad2ba | LucasVanHaaren/pelican-data-files | pelican/plugins/data_files/generators.py | [
"MIT"
] | Python | _get_data_files | <not_specific> | def _get_data_files(self):
"""Return list of valid files to load into context"""
data_dir = pathlib.Path(self.settings["DATA_FILES_DIR"])
valid_files = []
# turn path into absolute if not already
if not data_dir.is_absolute():
data_dir = pathlib.Path(self.settings["... | Return list of valid files to load into context | Return list of valid files to load into context | [
"Return",
"list",
"of",
"valid",
"files",
"to",
"load",
"into",
"context"
] | def _get_data_files(self):
data_dir = pathlib.Path(self.settings["DATA_FILES_DIR"])
valid_files = []
if not data_dir.is_absolute():
data_dir = pathlib.Path(self.settings["PATH"]).joinpath(data_dir)
if not data_dir.exists():
log.error("pelican-data-files: DATA_FILE... | [
"def",
"_get_data_files",
"(",
"self",
")",
":",
"data_dir",
"=",
"pathlib",
".",
"Path",
"(",
"self",
".",
"settings",
"[",
"\"DATA_FILES_DIR\"",
"]",
")",
"valid_files",
"=",
"[",
"]",
"if",
"not",
"data_dir",
".",
"is_absolute",
"(",
")",
":",
"data_d... | Return list of valid files to load into context | [
"Return",
"list",
"of",
"valid",
"files",
"to",
"load",
"into",
"context"
] | [
"\"\"\"Return list of valid files to load into context\"\"\"",
"# turn path into absolute if not already",
"# check if path exists",
"# return all valid files in path",
"# TODO check for duplicates (eg: profile.json and profile.yaml)"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f2b46e94ec5d2cd0fded74ae885d2aecebe5f914 | LucasVanHaaren/pelican-data-files | tasks.py | [
"MIT"
] | Python | black | null | def black(c, check=False, diff=False):
"""Run black formatter in check or diff mode"""
CF, DF = "", ""
if check:
CF = "--check"
if diff:
DF = "--diff"
c.run(f"{VENV}/bin/black {CF} {DF} {PKG_PATH} tasks.py setup.py") | Run black formatter in check or diff mode | Run black formatter in check or diff mode | [
"Run",
"black",
"formatter",
"in",
"check",
"or",
"diff",
"mode"
] | def black(c, check=False, diff=False):
CF, DF = "", ""
if check:
CF = "--check"
if diff:
DF = "--diff"
c.run(f"{VENV}/bin/black {CF} {DF} {PKG_PATH} tasks.py setup.py") | [
"def",
"black",
"(",
"c",
",",
"check",
"=",
"False",
",",
"diff",
"=",
"False",
")",
":",
"CF",
",",
"DF",
"=",
"\"\"",
",",
"\"\"",
"if",
"check",
":",
"CF",
"=",
"\"--check\"",
"if",
"diff",
":",
"DF",
"=",
"\"--diff\"",
"c",
".",
"run",
"("... | Run black formatter in check or diff mode | [
"Run",
"black",
"formatter",
"in",
"check",
"or",
"diff",
"mode"
] | [
"\"\"\"Run black formatter in check or diff mode\"\"\""
] | [
{
"param": "c",
"type": null
},
{
"param": "check",
"type": null
},
{
"param": "diff",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "c",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "check",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
854e7801d364827de247b486c3cd948c747c7bc8 | LucasVanHaaren/pelican-data-files | pelican/plugins/data_files/tools/cli.py | [
"MIT"
] | Python | _err | null | def _err(msg, die=None):
"""Print an error message and exits if an exit code is given"""
sys.stderr.write(f"ERROR: {msg}\n")
if die:
sys.exit(die if type(die) is int else 1) | Print an error message and exits if an exit code is given | Print an error message and exits if an exit code is given | [
"Print",
"an",
"error",
"message",
"and",
"exits",
"if",
"an",
"exit",
"code",
"is",
"given"
] | def _err(msg, die=None):
sys.stderr.write(f"ERROR: {msg}\n")
if die:
sys.exit(die if type(die) is int else 1) | [
"def",
"_err",
"(",
"msg",
",",
"die",
"=",
"None",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"f\"ERROR: {msg}\\n\"",
")",
"if",
"die",
":",
"sys",
".",
"exit",
"(",
"die",
"if",
"type",
"(",
"die",
")",
"is",
"int",
"else",
"1",
")"
] | Print an error message and exits if an exit code is given | [
"Print",
"an",
"error",
"message",
"and",
"exits",
"if",
"an",
"exit",
"code",
"is",
"given"
] | [
"\"\"\"Print an error message and exits if an exit code is given\"\"\""
] | [
{
"param": "msg",
"type": null
},
{
"param": "die",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "msg",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "die",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
ba68cabc7c66e032599173c6551135a98ea6fe9a | utcsilab/deep-jsense | utils.py | [
"MIT"
] | Python | itemize | <not_specific> | def itemize(x):
"""Converts a Tensor into a list of Python numbers.
"""
if len(x.shape) < 1:
x = x[None]
if x.shape[0] > 1:
return [xx.item() for xx in x]
else:
return x.item() | Converts a Tensor into a list of Python numbers.
| Converts a Tensor into a list of Python numbers. | [
"Converts",
"a",
"Tensor",
"into",
"a",
"list",
"of",
"Python",
"numbers",
"."
] | def itemize(x):
if len(x.shape) < 1:
x = x[None]
if x.shape[0] > 1:
return [xx.item() for xx in x]
else:
return x.item() | [
"def",
"itemize",
"(",
"x",
")",
":",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"<",
"1",
":",
"x",
"=",
"x",
"[",
"None",
"]",
"if",
"x",
".",
"shape",
"[",
"0",
"]",
">",
"1",
":",
"return",
"[",
"xx",
".",
"item",
"(",
")",
"for",
"x... | Converts a Tensor into a list of Python numbers. | [
"Converts",
"a",
"Tensor",
"into",
"a",
"list",
"of",
"Python",
"numbers",
"."
] | [
"\"\"\"Converts a Tensor into a list of Python numbers.\n \"\"\""
] | [
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
011acb0d544cc7e0abcc9cae2b8a7e6f8fe55c1e | yangtaokm/fairing | fairing/kubernetes/manager.py | [
"Apache-2.0"
] | Python | create_tf_job | <not_specific> | def create_tf_job(self, namespace, job):
"""Create the provided TFJob in the specified namespace"""
api_instance = client.CustomObjectsApi()
return api_instance.create_namespaced_custom_object(
TF_JOB_GROUP,
TF_JOB_VERSION,
namespace,
TF_JOB_PLURAL... | Create the provided TFJob in the specified namespace | Create the provided TFJob in the specified namespace | [
"Create",
"the",
"provided",
"TFJob",
"in",
"the",
"specified",
"namespace"
] | def create_tf_job(self, namespace, job):
api_instance = client.CustomObjectsApi()
return api_instance.create_namespaced_custom_object(
TF_JOB_GROUP,
TF_JOB_VERSION,
namespace,
TF_JOB_PLURAL,
job
) | [
"def",
"create_tf_job",
"(",
"self",
",",
"namespace",
",",
"job",
")",
":",
"api_instance",
"=",
"client",
".",
"CustomObjectsApi",
"(",
")",
"return",
"api_instance",
".",
"create_namespaced_custom_object",
"(",
"TF_JOB_GROUP",
",",
"TF_JOB_VERSION",
",",
"names... | Create the provided TFJob in the specified namespace | [
"Create",
"the",
"provided",
"TFJob",
"in",
"the",
"specified",
"namespace"
] | [
"\"\"\"Create the provided TFJob in the specified namespace\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "namespace",
"type": null
},
{
"param": "job",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "namespace",
"type": null,
"docstring": null,
"docstring_token... |
efd60ff5cedd9f879a3e026b34698b8d916689e8 | PipesNBottles/pycomm3 | pycomm3/packets/requests.py | [
"MIT"
] | Python | _build_header | bytes | def _build_header(self, command, length) -> bytes:
""" Build the encapsulate message header
The header is 24 bytes fixed length, and includes the command and the length of the optional data portion.
:return: the header
"""
try:
return b''.join([
com... | Build the encapsulate message header
The header is 24 bytes fixed length, and includes the command and the length of the optional data portion.
:return: the header
| Build the encapsulate message header
The header is 24 bytes fixed length, and includes the command and the length of the optional data portion.
:return: the header | [
"Build",
"the",
"encapsulate",
"message",
"header",
"The",
"header",
"is",
"24",
"bytes",
"fixed",
"length",
"and",
"includes",
"the",
"command",
"and",
"the",
"length",
"of",
"the",
"optional",
"data",
"portion",
".",
":",
"return",
":",
"the",
"header"
] | def _build_header(self, command, length) -> bytes:
try:
return b''.join([
command,
Pack.uint(length),
Pack.udint(self._plc._session),
b'\x00\x00\x00\x00',
self._plc.attribs['context'],
Pack.udint(... | [
"def",
"_build_header",
"(",
"self",
",",
"command",
",",
"length",
")",
"->",
"bytes",
":",
"try",
":",
"return",
"b''",
".",
"join",
"(",
"[",
"command",
",",
"Pack",
".",
"uint",
"(",
"length",
")",
",",
"Pack",
".",
"udint",
"(",
"self",
".",
... | Build the encapsulate message header
The header is 24 bytes fixed length, and includes the command and the length of the optional data portion. | [
"Build",
"the",
"encapsulate",
"message",
"header",
"The",
"header",
"is",
"24",
"bytes",
"fixed",
"length",
"and",
"includes",
"the",
"command",
"and",
"the",
"length",
"of",
"the",
"optional",
"data",
"portion",
"."
] | [
"\"\"\" Build the encapsulate message header\n\n The header is 24 bytes fixed length, and includes the command and the length of the optional data portion.\n\n :return: the header\n \"\"\"",
"# Length UINT",
"# Session Handle UDINT",
"# Status UDINT",
"# Sender Context 8 bytes",
"# O... | [
{
"param": "self",
"type": null
},
{
"param": "command",
"type": null
},
{
"param": "length",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "command",
"type": null,
"docstring": null,
"docstring_tokens"... |
efd60ff5cedd9f879a3e026b34698b8d916689e8 | PipesNBottles/pycomm3 | pycomm3/packets/requests.py | [
"MIT"
] | Python | _create_tag_rp | <not_specific> | def _create_tag_rp(tag, tag_cache, use_instance_ids):
"""
It returns the request packed wrapped around the tag passed.
If any error it returns none
"""
tags = tag.split('.')
if tags:
base, *attrs = tags
base_tag, index = _find_tag_index(base)
if use_instance_ids and bas... |
It returns the request packed wrapped around the tag passed.
If any error it returns none
| It returns the request packed wrapped around the tag passed.
If any error it returns none | [
"It",
"returns",
"the",
"request",
"packed",
"wrapped",
"around",
"the",
"tag",
"passed",
".",
"If",
"any",
"error",
"it",
"returns",
"none"
] | def _create_tag_rp(tag, tag_cache, use_instance_ids):
tags = tag.split('.')
if tags:
base, *attrs = tags
base_tag, index = _find_tag_index(base)
if use_instance_ids and base_tag in tag_cache:
rp = [CLASS_TYPE['8-bit'],
ClassCode.symbol_object,
... | [
"def",
"_create_tag_rp",
"(",
"tag",
",",
"tag_cache",
",",
"use_instance_ids",
")",
":",
"tags",
"=",
"tag",
".",
"split",
"(",
"'.'",
")",
"if",
"tags",
":",
"base",
",",
"*",
"attrs",
"=",
"tags",
"base_tag",
",",
"index",
"=",
"_find_tag_index",
"(... | It returns the request packed wrapped around the tag passed. | [
"It",
"returns",
"the",
"request",
"packed",
"wrapped",
"around",
"the",
"tag",
"passed",
"."
] | [
"\"\"\"\n\n It returns the request packed wrapped around the tag passed.\n If any error it returns none\n \"\"\"",
"# Create the request path",
"# Add pad byte because total length of Request path must be word-aligned",
"# Add any index"
] | [
{
"param": "tag",
"type": null
},
{
"param": "tag_cache",
"type": null
},
{
"param": "use_instance_ids",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "tag",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "tag_cache",
"type": null,
"docstring": null,
"docstring_tokens... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | with_forward_open | <not_specific> | def with_forward_open(func):
"""Decorator to ensure a forward open request has been completed with the plc"""
@wraps(func)
def wrapped(self, *args, **kwargs):
opened = False
if not self._forward_open():
if self.attribs['extended forward open']:
logger = logging.g... | Decorator to ensure a forward open request has been completed with the plc | Decorator to ensure a forward open request has been completed with the plc | [
"Decorator",
"to",
"ensure",
"a",
"forward",
"open",
"request",
"has",
"been",
"completed",
"with",
"the",
"plc"
] | def with_forward_open(func):
@wraps(func)
def wrapped(self, *args, **kwargs):
opened = False
if not self._forward_open():
if self.attribs['extended forward open']:
logger = logging.getLogger('pycomm3.clx.LogixDriver')
logger.info('Extended Forward Open... | [
"def",
"with_forward_open",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"opened",
"=",
"False",
"if",
"not",
"self",
".",
"_forward_open",
"(",
")",
":",
"if... | Decorator to ensure a forward open request has been completed with the plc | [
"Decorator",
"to",
"ensure",
"a",
"forward",
"open",
"request",
"has",
"been",
"completed",
"with",
"the",
"plc"
] | [
"\"\"\"Decorator to ensure a forward open request has been completed with the plc\"\"\""
] | [
{
"param": "func",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "func",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | open | <not_specific> | def open(self):
"""
Creates a new Ethernet/IP socket connection to target device and registers a CIP session.
:return: True if successful, False otherwise
"""
# handle the socket layer
if self._connection_opened:
return
try:
if self._sock ... |
Creates a new Ethernet/IP socket connection to target device and registers a CIP session.
:return: True if successful, False otherwise
| Creates a new Ethernet/IP socket connection to target device and registers a CIP session. | [
"Creates",
"a",
"new",
"Ethernet",
"/",
"IP",
"socket",
"connection",
"to",
"target",
"device",
"and",
"registers",
"a",
"CIP",
"session",
"."
] | def open(self):
if self._connection_opened:
return
try:
if self._sock is None:
self._sock = Socket()
self._sock.connect(self.attribs['ip address'], self.attribs['port'])
self._connection_opened = True
self.attribs['cid'] = urand... | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection_opened",
":",
"return",
"try",
":",
"if",
"self",
".",
"_sock",
"is",
"None",
":",
"self",
".",
"_sock",
"=",
"Socket",
"(",
")",
"self",
".",
"_sock",
".",
"connect",
"(",
"self... | Creates a new Ethernet/IP socket connection to target device and registers a CIP session. | [
"Creates",
"a",
"new",
"Ethernet",
"/",
"IP",
"socket",
"connection",
"to",
"target",
"device",
"and",
"registers",
"a",
"CIP",
"session",
"."
] | [
"\"\"\"\n Creates a new Ethernet/IP socket connection to target device and registers a CIP session.\n\n :return: True if successful, False otherwise\n \"\"\"",
"# handle the socket layer"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "True if successful, False otherwise",
"docstring_tokens": [
"True",
"if",
"successful",
"False",
"otherwise"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _register_session | Optional[int] | def _register_session(self) -> Optional[int]:
"""
Registers a new CIP session with the target.
:return: the session id if session registered successfully, else None
"""
if self._session:
return self._session
self._session = 0
request = self.new_reque... |
Registers a new CIP session with the target.
:return: the session id if session registered successfully, else None
| Registers a new CIP session with the target. | [
"Registers",
"a",
"new",
"CIP",
"session",
"with",
"the",
"target",
"."
] | def _register_session(self) -> Optional[int]:
if self._session:
return self._session
self._session = 0
request = self.new_request('register_session')
request.add(
self.attribs['protocol version'],
b'\x00\x00'
)
response = request.send()... | [
"def",
"_register_session",
"(",
"self",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"self",
".",
"_session",
":",
"return",
"self",
".",
"_session",
"self",
".",
"_session",
"=",
"0",
"request",
"=",
"self",
".",
"new_request",
"(",
"'register_se... | Registers a new CIP session with the target. | [
"Registers",
"a",
"new",
"CIP",
"session",
"with",
"the",
"target",
"."
] | [
"\"\"\"\n Registers a new CIP session with the target.\n\n :return: the session id if session registered successfully, else None\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "the session id if session registered successfully, else None",
"docstring_tokens": [
"the",
"session",
"id",
"if",
"session",
"registered",
"successfully",
"else",
"None"
],
"type": null
... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _forward_open | <not_specific> | def _forward_open(self):
"""
Opens a new connection with the target PLC using the *Forward Open* or *Extended Forward Open* service.
:return: True if connection is open or was successfully opened, False otherwise
"""
if self._target_is_connected:
return True
... |
Opens a new connection with the target PLC using the *Forward Open* or *Extended Forward Open* service.
:return: True if connection is open or was successfully opened, False otherwise
| Opens a new connection with the target PLC using the *Forward Open* or *Extended Forward Open* service. | [
"Opens",
"a",
"new",
"connection",
"with",
"the",
"target",
"PLC",
"using",
"the",
"*",
"Forward",
"Open",
"*",
"or",
"*",
"Extended",
"Forward",
"Open",
"*",
"service",
"."
] | def _forward_open(self):
if self._target_is_connected:
return True
if self._session == 0:
raise CommError("A Session Not Registered Before forward_open.")
init_net_params = 0b_0100_0010_0000_0000
if self.attribs['extended forward open']:
net_params =... | [
"def",
"_forward_open",
"(",
"self",
")",
":",
"if",
"self",
".",
"_target_is_connected",
":",
"return",
"True",
"if",
"self",
".",
"_session",
"==",
"0",
":",
"raise",
"CommError",
"(",
"\"A Session Not Registered Before forward_open.\"",
")",
"init_net_params",
... | Opens a new connection with the target PLC using the *Forward Open* or *Extended Forward Open* service. | [
"Opens",
"a",
"new",
"connection",
"with",
"the",
"target",
"PLC",
"using",
"the",
"*",
"Forward",
"Open",
"*",
"or",
"*",
"Extended",
"Forward",
"Open",
"*",
"service",
"."
] | [
"\"\"\"\n Opens a new connection with the target PLC using the *Forward Open* or *Extended Forward Open* service.\n\n :return: True if connection is open or was successfully opened, False otherwise\n \"\"\"",
"# CIP Vol 1 - 3-5.5.1.1"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "True if connection is open or was successfully opened, False otherwise",
"docstring_tokens": [
"True",
"if",
"connection",
"is",
"open",
"or",
"was",
"successfully",
"opened",
"False",
... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _un_register_session | null | def _un_register_session(self):
"""
Un-registers the current session with the target.
"""
request = self.new_request('unregister_session')
request.send()
self._session = None |
Un-registers the current session with the target.
| Un-registers the current session with the target. | [
"Un",
"-",
"registers",
"the",
"current",
"session",
"with",
"the",
"target",
"."
] | def _un_register_session(self):
request = self.new_request('unregister_session')
request.send()
self._session = None | [
"def",
"_un_register_session",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"new_request",
"(",
"'unregister_session'",
")",
"request",
".",
"send",
"(",
")",
"self",
".",
"_session",
"=",
"None"
] | Un-registers the current session with the target. | [
"Un",
"-",
"registers",
"the",
"current",
"session",
"with",
"the",
"target",
"."
] | [
"\"\"\"\n Un-registers the current session with the target.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _forward_close | <not_specific> | def _forward_close(self):
""" CIP implementation of the forward close message
Each connection opened with the forward open message need to be closed.
Refer to ODVA documentation Volume 1 3-5.5.3
:return: False if any error in the replayed message
"""
if self._session =... | CIP implementation of the forward close message
Each connection opened with the forward open message need to be closed.
Refer to ODVA documentation Volume 1 3-5.5.3
:return: False if any error in the replayed message
| CIP implementation of the forward close message
Each connection opened with the forward open message need to be closed.
Refer to ODVA documentation Volume 1 3-5.5.3 | [
"CIP",
"implementation",
"of",
"the",
"forward",
"close",
"message",
"Each",
"connection",
"opened",
"with",
"the",
"forward",
"open",
"message",
"need",
"to",
"be",
"closed",
".",
"Refer",
"to",
"ODVA",
"documentation",
"Volume",
"1",
"3",
"-",
"5",
".",
... | def _forward_close(self):
if self._session == 0:
raise CommError("A session need to be registered before to call forward_close.")
route_path = Pack.epath(self.attribs['cip_path'] + MSG_ROUTER_PATH, pad_len=True)
forward_close_msg = [
PRIORITY,
TIMEOUT_TICKS,
... | [
"def",
"_forward_close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"==",
"0",
":",
"raise",
"CommError",
"(",
"\"A session need to be registered before to call forward_close.\"",
")",
"route_path",
"=",
"Pack",
".",
"epath",
"(",
"self",
".",
"attribs"... | CIP implementation of the forward close message
Each connection opened with the forward open message need to be closed. | [
"CIP",
"implementation",
"of",
"the",
"forward",
"close",
"message",
"Each",
"connection",
"opened",
"with",
"the",
"forward",
"open",
"message",
"need",
"to",
"be",
"closed",
"."
] | [
"\"\"\" CIP implementation of the forward close message\n\n Each connection opened with the forward open message need to be closed.\n Refer to ODVA documentation Volume 1 3-5.5.3\n\n :return: False if any error in the replayed message\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "False if any error in the replayed message",
"docstring_tokens": [
"False",
"if",
"any",
"error",
"in",
"the",
"replayed",
"message"
],
"type": null
}
],
"raises": [],
"params": [
{... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _get_instance_attribute_list_service | <not_specific> | def _get_instance_attribute_list_service(self, program=None):
""" Step 1: Finding user-created controller scope tags in a Logix5000 controller
This service returns instance IDs for each created instance of the symbol class, along with a list
of the attribute data associated with the requested a... | Step 1: Finding user-created controller scope tags in a Logix5000 controller
This service returns instance IDs for each created instance of the symbol class, along with a list
of the attribute data associated with the requested attribute
| Step 1: Finding user-created controller scope tags in a Logix5000 controller
This service returns instance IDs for each created instance of the symbol class, along with a list
of the attribute data associated with the requested attribute | [
"Step",
"1",
":",
"Finding",
"user",
"-",
"created",
"controller",
"scope",
"tags",
"in",
"a",
"Logix5000",
"controller",
"This",
"service",
"returns",
"instance",
"IDs",
"for",
"each",
"created",
"instance",
"of",
"the",
"symbol",
"class",
"along",
"with",
... | def _get_instance_attribute_list_service(self, program=None):
try:
last_instance = 0
tag_list = []
while last_instance != -1:
path = []
if program:
if not program.startswith('Program:'):
program = f'P... | [
"def",
"_get_instance_attribute_list_service",
"(",
"self",
",",
"program",
"=",
"None",
")",
":",
"try",
":",
"last_instance",
"=",
"0",
"tag_list",
"=",
"[",
"]",
"while",
"last_instance",
"!=",
"-",
"1",
":",
"path",
"=",
"[",
"]",
"if",
"program",
":... | Step 1: Finding user-created controller scope tags in a Logix5000 controller
This service returns instance IDs for each created instance of the symbol class, along with a list
of the attribute data associated with the requested attribute | [
"Step",
"1",
":",
"Finding",
"user",
"-",
"created",
"controller",
"scope",
"tags",
"in",
"a",
"Logix5000",
"controller",
"This",
"service",
"returns",
"instance",
"IDs",
"for",
"each",
"created",
"instance",
"of",
"the",
"symbol",
"class",
"along",
"with",
... | [
"\"\"\" Step 1: Finding user-created controller scope tags in a Logix5000 controller\n\n This service returns instance IDs for each created instance of the symbol class, along with a list\n of the attribute data associated with the requested attribute\n \"\"\"",
"# Creating the Message Reques... | [
{
"param": "self",
"type": null
},
{
"param": "program",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "program",
"type": null,
"docstring": null,
"docstring_tokens"... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _parse_instance_attribute_list | <not_specific> | def _parse_instance_attribute_list(self, response, tag_list):
""" extract the tags list from the message received"""
tags_returned = response.data
tags_returned_length = len(tags_returned)
idx = count = instance = 0
try:
while idx < tags_returned_length:
... | extract the tags list from the message received | extract the tags list from the message received | [
"extract",
"the",
"tags",
"list",
"from",
"the",
"message",
"received"
] | def _parse_instance_attribute_list(self, response, tag_list):
tags_returned = response.data
tags_returned_length = len(tags_returned)
idx = count = instance = 0
try:
while idx < tags_returned_length:
instance = Unpack.dint(tags_returned[idx:idx + 4])
... | [
"def",
"_parse_instance_attribute_list",
"(",
"self",
",",
"response",
",",
"tag_list",
")",
":",
"tags_returned",
"=",
"response",
".",
"data",
"tags_returned_length",
"=",
"len",
"(",
"tags_returned",
")",
"idx",
"=",
"count",
"=",
"instance",
"=",
"0",
"try... | extract the tags list from the message received | [
"extract",
"the",
"tags",
"list",
"from",
"the",
"message",
"received"
] | [
"\"\"\" extract the tags list from the message received\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "response",
"type": null
},
{
"param": "tag_list",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "response",
"type": null,
"docstring": null,
"docstring_tokens... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _get_structure_makeup | <not_specific> | def _get_structure_makeup(self, instance_id):
"""
get the structure makeup for a specific structure
"""
if instance_id not in self._cache['id:struct']:
request = self.new_request('send_unit_data')
req_path = request_path(ClassCode.template_object, Pack.uint(instan... |
get the structure makeup for a specific structure
| get the structure makeup for a specific structure | [
"get",
"the",
"structure",
"makeup",
"for",
"a",
"specific",
"structure"
] | def _get_structure_makeup(self, instance_id):
if instance_id not in self._cache['id:struct']:
request = self.new_request('send_unit_data')
req_path = request_path(ClassCode.template_object, Pack.uint(instance_id))
request.add(
CommonService.get_attribute_list,... | [
"def",
"_get_structure_makeup",
"(",
"self",
",",
"instance_id",
")",
":",
"if",
"instance_id",
"not",
"in",
"self",
".",
"_cache",
"[",
"'id:struct'",
"]",
":",
"request",
"=",
"self",
".",
"new_request",
"(",
"'send_unit_data'",
")",
"req_path",
"=",
"requ... | get the structure makeup for a specific structure | [
"get",
"the",
"structure",
"makeup",
"for",
"a",
"specific",
"structure"
] | [
"\"\"\"\n get the structure makeup for a specific structure\n \"\"\"",
"# service data:",
"# Number of attributes",
"# Template Object Definition Size UDINT",
"# Template Structure Size UDINT",
"# Template Member Count UINT",
"# Structure Handle We can use this to read and write UINT"
] | [
{
"param": "self",
"type": null
},
{
"param": "instance_id",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "instance_id",
"type": null,
"docstring": null,
"docstring_tok... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | read | ReturnType | def read(self, *tags: str) -> ReturnType:
"""
Read the value of tag(s). Automatically will split tags into multiple requests by tracking the request and
response size. Will use the multi-service request to group many tags into a single packet and also will automatically
use fragmented ... |
Read the value of tag(s). Automatically will split tags into multiple requests by tracking the request and
response size. Will use the multi-service request to group many tags into a single packet and also will automatically
use fragmented read requests if the response size will not fit in a ... | Read the value of tag(s). Automatically will split tags into multiple requests by tracking the request and
response size. Will use the multi-service request to group many tags into a single packet and also will automatically
use fragmented read requests if the response size will not fit in a single packet. Supports ... | [
"Read",
"the",
"value",
"of",
"tag",
"(",
"s",
")",
".",
"Automatically",
"will",
"split",
"tags",
"into",
"multiple",
"requests",
"by",
"tracking",
"the",
"request",
"and",
"response",
"size",
".",
"Will",
"use",
"the",
"multi",
"-",
"service",
"request",... | def read(self, *tags: str) -> ReturnType:
parsed_requests = self._parse_requested_tags(tags)
requests = self._read_build_requests(parsed_requests)
read_results = self._send_requests(requests)
results = []
for tag in tags:
try:
request_data = parsed_req... | [
"def",
"read",
"(",
"self",
",",
"*",
"tags",
":",
"str",
")",
"->",
"ReturnType",
":",
"parsed_requests",
"=",
"self",
".",
"_parse_requested_tags",
"(",
"tags",
")",
"requests",
"=",
"self",
".",
"_read_build_requests",
"(",
"parsed_requests",
")",
"read_r... | Read the value of tag(s). | [
"Read",
"the",
"value",
"of",
"tag",
"(",
"s",
")",
"."
] | [
"\"\"\"\n Read the value of tag(s). Automatically will split tags into multiple requests by tracking the request and\n response size. Will use the multi-service request to group many tags into a single packet and also will automatically\n use fragmented read requests if the response size will... | [
{
"param": "self",
"type": null
},
{
"param": "tags",
"type": "str"
}
] | {
"returns": [
{
"docstring": "a single or list of ``Tag`` objects",
"docstring_tokens": [
"a",
"single",
"or",
"list",
"of",
"`",
"`",
"Tag",
"`",
"`",
"objects"
],
"type": null
}
],
"raises": ... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _read_build_multi_requests | <not_specific> | def _read_build_multi_requests(self, parsed_tags):
"""
creates a list of multi-request packets
"""
requests = []
response_size = MULTISERVICE_READ_OVERHEAD
current_request = self.new_request('multi_request')
requests.append(current_request)
tags_in_request... |
creates a list of multi-request packets
| creates a list of multi-request packets | [
"creates",
"a",
"list",
"of",
"multi",
"-",
"request",
"packets"
] | def _read_build_multi_requests(self, parsed_tags):
requests = []
response_size = MULTISERVICE_READ_OVERHEAD
current_request = self.new_request('multi_request')
requests.append(current_request)
tags_in_requests = set()
for tag, tag_data in parsed_tags.items():
... | [
"def",
"_read_build_multi_requests",
"(",
"self",
",",
"parsed_tags",
")",
":",
"requests",
"=",
"[",
"]",
"response_size",
"=",
"MULTISERVICE_READ_OVERHEAD",
"current_request",
"=",
"self",
".",
"new_request",
"(",
"'multi_request'",
")",
"requests",
".",
"append",... | creates a list of multi-request packets | [
"creates",
"a",
"list",
"of",
"multi",
"-",
"request",
"packets"
] | [
"\"\"\"\n creates a list of multi-request packets\n \"\"\"",
"# add 2 bytes for offset list in reply"
] | [
{
"param": "self",
"type": null
},
{
"param": "parsed_tags",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "parsed_tags",
"type": null,
"docstring": null,
"docstring_tok... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | _read_build_single_request | <not_specific> | def _read_build_single_request(self, parsed_tag):
"""
creates a single read_tag request packet
"""
if parsed_tag.get('error') is None:
return_size = _tag_return_size(parsed_tag)
if return_size > self.connection_size:
request = self.new_request('re... |
creates a single read_tag request packet
| creates a single read_tag request packet | [
"creates",
"a",
"single",
"read_tag",
"request",
"packet"
] | def _read_build_single_request(self, parsed_tag):
if parsed_tag.get('error') is None:
return_size = _tag_return_size(parsed_tag)
if return_size > self.connection_size:
request = self.new_request('read_tag_fragmented')
else:
request = self.new_r... | [
"def",
"_read_build_single_request",
"(",
"self",
",",
"parsed_tag",
")",
":",
"if",
"parsed_tag",
".",
"get",
"(",
"'error'",
")",
"is",
"None",
":",
"return_size",
"=",
"_tag_return_size",
"(",
"parsed_tag",
")",
"if",
"return_size",
">",
"self",
".",
"con... | creates a single read_tag request packet | [
"creates",
"a",
"single",
"read_tag",
"request",
"packet"
] | [
"\"\"\"\n creates a single read_tag request packet\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "parsed_tag",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "parsed_tag",
"type": null,
"docstring": null,
"docstring_toke... |
006d139ade5f44e1711ad3fc357d4818a9d37751 | PipesNBottles/pycomm3 | pycomm3/clx.py | [
"MIT"
] | Python | generic_message | Tag | def generic_message(self,
service: bytes,
class_code: bytes,
instance: bytes,
attribute: Optional[bytes] = b'',
request_data: Optional[bytes] = b'',
data_format: Optional[DataF... |
Perform a generic CIP message. Similar to how MSG instructions work in Logix.
:param service: service code for the request (single byte)
:param class_code: request object class ID
:param instance: instance ID of the class
:param attribute: (optional) attribute ID for the servi... | Perform a generic CIP message. Similar to how MSG instructions work in Logix. | [
"Perform",
"a",
"generic",
"CIP",
"message",
".",
"Similar",
"to",
"how",
"MSG",
"instructions",
"work",
"in",
"Logix",
"."
] | def generic_message(self,
service: bytes,
class_code: bytes,
instance: bytes,
attribute: Optional[bytes] = b'',
request_data: Optional[bytes] = b'',
data_format: Optional[DataF... | [
"def",
"generic_message",
"(",
"self",
",",
"service",
":",
"bytes",
",",
"class_code",
":",
"bytes",
",",
"instance",
":",
"bytes",
",",
"attribute",
":",
"Optional",
"[",
"bytes",
"]",
"=",
"b''",
",",
"request_data",
":",
"Optional",
"[",
"bytes",
"]"... | Perform a generic CIP message. | [
"Perform",
"a",
"generic",
"CIP",
"message",
"."
] | [
"\"\"\"\n Perform a generic CIP message. Similar to how MSG instructions work in Logix.\n\n :param service: service code for the request (single byte)\n :param class_code: request object class ID\n :param instance: instance ID of the class\n :param attribute: (optional) attribute... | [
{
"param": "self",
"type": null
},
{
"param": "service",
"type": "bytes"
},
{
"param": "class_code",
"type": "bytes"
},
{
"param": "instance",
"type": "bytes"
},
{
"param": "attribute",
"type": "Optional[bytes]"
},
{
"param": "request_data",
"type"... | {
"returns": [
{
"docstring": "a Tag with the result of the request. (Tag.value for writes will be the request_data)",
"docstring_tokens": [
"a",
"Tag",
"with",
"the",
"result",
"of",
"the",
"request",
".",
"(",
"T... |
899b751c52465e1d27159d03efc40cd4a462a36b | zebincai/imaginaire | imaginaire/trainers/cagan.py | [
"RSA-MD"
] | Python | _init_loss | null | def _init_loss(self, cfg):
r"""Initialize loss terms. In FUNIT, we have several loss terms
including the GAN loss, the image reconstruction loss, the feature
matching loss, and the gradient penalty loss.
Args:
cfg (obj): Global configuration.
"""
self... | r"""Initialize loss terms. In FUNIT, we have several loss terms
including the GAN loss, the image reconstruction loss, the feature
matching loss, and the gradient penalty loss.
Args:
cfg (obj): Global configuration.
| r"""Initialize loss terms. In FUNIT, we have several loss terms
including the GAN loss, the image reconstruction loss, the feature
matching loss, and the gradient penalty loss. | [
"r",
"\"",
"\"",
"\"",
"Initialize",
"loss",
"terms",
".",
"In",
"FUNIT",
"we",
"have",
"several",
"loss",
"terms",
"including",
"the",
"GAN",
"loss",
"the",
"image",
"reconstruction",
"loss",
"the",
"feature",
"matching",
"loss",
"and",
"the",
"gradient",
... | def _init_loss(self, cfg):
self.criteria['gen_basic'] = nn.BCELoss()
self.criteria['dis_basic'] = nn.BCELoss()
self.criteria['clycle_loss'] = nn.L1Loss()
for loss_name, loss_weight in cfg.trainer.loss_weight.__dict__.items():
if loss_weight > 0:
self.weights[l... | [
"def",
"_init_loss",
"(",
"self",
",",
"cfg",
")",
":",
"self",
".",
"criteria",
"[",
"'gen_basic'",
"]",
"=",
"nn",
".",
"BCELoss",
"(",
")",
"self",
".",
"criteria",
"[",
"'dis_basic'",
"]",
"=",
"nn",
".",
"BCELoss",
"(",
")",
"self",
".",
"crit... | r"""Initialize loss terms. | [
"r",
"\"",
"\"",
"\"",
"Initialize",
"loss",
"terms",
"."
] | [
"r\"\"\"Initialize loss terms. In FUNIT, we have several loss terms\r\n including the GAN loss, the image reconstruction loss, the feature\r\n matching loss, and the gradient penalty loss.\r\n\r\n Args:\r\n cfg (obj): Global configuration.\r\n \"\"\"",
"# self.criteria['dis_... | [
{
"param": "self",
"type": null
},
{
"param": "cfg",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "cfg",
"type": null,
"docstring": null,
"docstring_tokens": [
... |
899b751c52465e1d27159d03efc40cd4a462a36b | zebincai/imaginaire | imaginaire/trainers/cagan.py | [
"RSA-MD"
] | Python | _compute_fid | <not_specific> | def _compute_fid(self):
r"""Compute FID. We will compute a FID value per test class. That is
if you have 30 test classes, we will compute 30 different FID values.
We will then report the mean of the FID values as the final
performance number as described in the FUNIT paper.
... | r"""Compute FID. We will compute a FID value per test class. That is
if you have 30 test classes, we will compute 30 different FID values.
We will then report the mean of the FID values as the final
performance number as described in the FUNIT paper.
| r"""Compute FID. We will compute a FID value per test class. That is
if you have 30 test classes, we will compute 30 different FID values.
We will then report the mean of the FID values as the final
performance number as described in the FUNIT paper. | [
"r",
"\"",
"\"",
"\"",
"Compute",
"FID",
".",
"We",
"will",
"compute",
"a",
"FID",
"value",
"per",
"test",
"class",
".",
"That",
"is",
"if",
"you",
"have",
"30",
"test",
"classes",
"we",
"will",
"compute",
"30",
"different",
"FID",
"values",
".",
"We... | def _compute_fid(self):
return None | [
"def",
"_compute_fid",
"(",
"self",
")",
":",
"\"\"\"\r\n self.net_G.eval()\r\n all_fid_values = []\r\n fid_path = self._get_save_path(\"valid\", 'npy')\r\n fid_value = compute_fid(fid_path, self.val_data_loader,\r\n self.net_G, 'images_style',\... | r"""Compute FID. | [
"r",
"\"",
"\"",
"\"",
"Compute",
"FID",
"."
] | [
"r\"\"\"Compute FID. We will compute a FID value per test class. That is\r\n if you have 30 test classes, we will compute 30 different FID values.\r\n We will then report the mean of the FID values as the final\r\n performance number as described in the FUNIT paper.\r\n \"\"\"",
"\"\"\... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ba7ec067302a0ba55fc5c59ed790e9255517c5e1 | rpep/fmmgen | fmmgen/cse.py | [
"BSD-3-Clause"
] | Python | tree_cse | <not_specific> | def tree_cse(exprs, symbols, opt_subs=None, order='canonical', ignore=(), light_ignore=()):
"""
Perform raw CSE on expression tree, taking opt_subs into account.
Inputs:
exprs : list of sympy expressions
The expressions to reduce.
symbols : infinite iterator yielding unique Symbols
... |
Perform raw CSE on expression tree, taking opt_subs into account.
Inputs:
exprs : list of sympy expressions
The expressions to reduce.
symbols : infinite iterator yielding unique Symbols
The symbols used to label the common subexpressions which are pulled
out.
opt_subs : d... | Perform raw CSE on expression tree, taking opt_subs into account.
Inputs.
exprs : list of sympy expressions
The expressions to reduce.
symbols : infinite iterator yielding unique Symbols
The symbols used to label the common subexpressions which are pulled
out.
opt_subs : dictionary of expression substitutions
The expr... | [
"Perform",
"raw",
"CSE",
"on",
"expression",
"tree",
"taking",
"opt_subs",
"into",
"account",
".",
"Inputs",
".",
"exprs",
":",
"list",
"of",
"sympy",
"expressions",
"The",
"expressions",
"to",
"reduce",
".",
"symbols",
":",
"infinite",
"iterator",
"yielding",... | def tree_cse(exprs, symbols, opt_subs=None, order='canonical', ignore=(), light_ignore=()):
if opt_subs is None:
opt_subs = dict()
to_eliminate = set()
seen_subexp = set()
excluded_symbols = set()
def _find_repeated(expr):
if not isinstance(expr, (Basic, Unevaluated)):
re... | [
"def",
"tree_cse",
"(",
"exprs",
",",
"symbols",
",",
"opt_subs",
"=",
"None",
",",
"order",
"=",
"'canonical'",
",",
"ignore",
"=",
"(",
")",
",",
"light_ignore",
"=",
"(",
")",
")",
":",
"if",
"opt_subs",
"is",
"None",
":",
"opt_subs",
"=",
"dict",... | Perform raw CSE on expression tree, taking opt_subs into account. | [
"Perform",
"raw",
"CSE",
"on",
"expression",
"tree",
"taking",
"opt_subs",
"into",
"account",
"."
] | [
"\"\"\"\n Perform raw CSE on expression tree, taking opt_subs into account.\n\n Inputs:\n\n exprs : list of sympy expressions\n The expressions to reduce.\n symbols : infinite iterator yielding unique Symbols\n The symbols used to label the common subexpressions which are pulled\n o... | [
{
"param": "exprs",
"type": null
},
{
"param": "symbols",
"type": null
},
{
"param": "opt_subs",
"type": null
},
{
"param": "order",
"type": null
},
{
"param": "ignore",
"type": null
},
{
"param": "light_ignore",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "exprs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "symbols",
"type": null,
"docstring": null,
"docstring_tokens... |
4a4908ad2977bd089e0b833a59676f845ced4c42 | rpep/fmmgen | fmmgen/generator.py | [
"BSD-3-Clause"
] | Python | generate_M_operators | <not_specific> | def generate_M_operators(order, symbols, M_dict):
"""
generate_M_operators(order, symbols, index_dict):
Generates multipole operators up to order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which
define coor... |
generate_M_operators(order, symbols, index_dict):
Generates multipole operators up to order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which
define coordinate labels.
index_dict:
Forward mapping d... | generate_M_operators(order, symbols, index_dict):
Generates multipole operators up to order.
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which
define coordinate labels.
Forward mapping dictionary between
monomials of symbols and array indices,
generated by genera... | [
"generate_M_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"multipole",
"operators",
"up",
"to",
"order",
".",
"order",
"int",
":",
"Maximum",
"order",
"of",
"multipole",
"expansion",
"symbols",
"list",
":",
"List",
"of",
"sympy",
"s... | def generate_M_operators(order, symbols, M_dict):
x, y, z = symbols
M_operators = []
for n in M_dict.keys():
M_operators.append(M(n, symbols))
return M_operators | [
"def",
"generate_M_operators",
"(",
"order",
",",
"symbols",
",",
"M_dict",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"symbols",
"M_operators",
"=",
"[",
"]",
"for",
"n",
"in",
"M_dict",
".",
"keys",
"(",
")",
":",
"M_operators",
".",
"append",
"(",
... | generate_M_operators(order, symbols, index_dict):
Generates multipole operators up to order. | [
"generate_M_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"multipole",
"operators",
"up",
"to",
"order",
"."
] | [
"\"\"\"\n generate_M_operators(order, symbols, index_dict):\n\n Generates multipole operators up to order.\n\n Input:\n order, int:\n Maximum order of multipole expansion\n\n symbols, list:\n List of sympy symbol type objects which\n define coordinate labels.\n\n index_dict:\n... | [
{
"param": "order",
"type": null
},
{
"param": "symbols",
"type": null
},
{
"param": "M_dict",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "order",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "symbols",
"type": null,
"docstring": null,
"docstring_tokens... |
4a4908ad2977bd089e0b833a59676f845ced4c42 | rpep/fmmgen | fmmgen/generator.py | [
"BSD-3-Clause"
] | Python | generate_M_shift_operators | <not_specific> | def generate_M_shift_operators(order, symbols, M_dict, source_order=0):
"""
generate_M_shift_operators(order, symbols, index_dict):
Generates multipole shifting operators up to order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol t... |
generate_M_shift_operators(order, symbols, index_dict):
Generates multipole shifting operators up to order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which define coordinate labels.
index_dict:
Forward ma... | generate_M_shift_operators(order, symbols, index_dict):
Generates multipole shifting operators up to order.
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which define coordinate labels.
Forward mapping dictionary between
monomials of symbols and array indices, gene... | [
"generate_M_shift_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"multipole",
"shifting",
"operators",
"up",
"to",
"order",
".",
"order",
"int",
":",
"Maximum",
"order",
"of",
"multipole",
"expansion",
"symbols",
"list",
":",
"List",
"... | def generate_M_shift_operators(order, symbols, M_dict, source_order=0):
x, y, z = symbols
M_operators = []
for n in M_dict.keys():
M_operators.append(M_shift(n, order, symbols, M_dict,
source_order=source_order))
return M_operators | [
"def",
"generate_M_shift_operators",
"(",
"order",
",",
"symbols",
",",
"M_dict",
",",
"source_order",
"=",
"0",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"symbols",
"M_operators",
"=",
"[",
"]",
"for",
"n",
"in",
"M_dict",
".",
"keys",
"(",
")",
":",
... | generate_M_shift_operators(order, symbols, index_dict):
Generates multipole shifting operators up to order. | [
"generate_M_shift_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"multipole",
"shifting",
"operators",
"up",
"to",
"order",
"."
] | [
"\"\"\"\n generate_M_shift_operators(order, symbols, index_dict):\n\n Generates multipole shifting operators up to order.\n\n Input:\n order, int:\n Maximum order of multipole expansion\n\n symbols, list:\n List of sympy symbol type objects which define coordinate labels.\n\n index_d... | [
{
"param": "order",
"type": null
},
{
"param": "symbols",
"type": null
},
{
"param": "M_dict",
"type": null
},
{
"param": "source_order",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "order",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "symbols",
"type": null,
"docstring": null,
"docstring_tokens... |
4a4908ad2977bd089e0b833a59676f845ced4c42 | rpep/fmmgen | fmmgen/generator.py | [
"BSD-3-Clause"
] | Python | generate_L_operators | <not_specific> | def generate_L_operators(order, symbols, M_dict, L_dict, source_order=0):
"""
generate_L_operators(order, symbols, index_dict):
Generates local expansion operators up to given order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol ty... |
generate_L_operators(order, symbols, index_dict):
Generates local expansion operators up to given order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which define coordinate labels.
index_dict:
Forward mappi... | generate_L_operators(order, symbols, index_dict):
Generates local expansion operators up to given order.
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which define coordinate labels.
Forward mapping dictionary between
monomials of symbols and array indices, generat... | [
"generate_L_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"local",
"expansion",
"operators",
"up",
"to",
"given",
"order",
".",
"order",
"int",
":",
"Maximum",
"order",
"of",
"multipole",
"expansion",
"symbols",
"list",
":",
"List",
... | def generate_L_operators(order, symbols, M_dict, L_dict, source_order=0):
x, y, z = symbols
L_operators = []
for n in L_dict.keys():
L_operators.append(L(n, order, symbols, M_dict, source_order=source_order, eval_derivs=False))
return L_operators | [
"def",
"generate_L_operators",
"(",
"order",
",",
"symbols",
",",
"M_dict",
",",
"L_dict",
",",
"source_order",
"=",
"0",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"symbols",
"L_operators",
"=",
"[",
"]",
"for",
"n",
"in",
"L_dict",
".",
"keys",
"(",
... | generate_L_operators(order, symbols, index_dict):
Generates local expansion operators up to given order. | [
"generate_L_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"local",
"expansion",
"operators",
"up",
"to",
"given",
"order",
"."
] | [
"\"\"\"\n generate_L_operators(order, symbols, index_dict):\n\n Generates local expansion operators up to given order.\n\n Input:\n order, int:\n Maximum order of multipole expansion\n\n symbols, list:\n List of sympy symbol type objects which define coordinate labels.\n\n index_dict... | [
{
"param": "order",
"type": null
},
{
"param": "symbols",
"type": null
},
{
"param": "M_dict",
"type": null
},
{
"param": "L_dict",
"type": null
},
{
"param": "source_order",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "order",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "symbols",
"type": null,
"docstring": null,
"docstring_tokens... |
4a4908ad2977bd089e0b833a59676f845ced4c42 | rpep/fmmgen | fmmgen/generator.py | [
"BSD-3-Clause"
] | Python | generate_L_shift_operators | <not_specific> | def generate_L_shift_operators(order, symbols, L_dict, source_order=0):
"""
generate_L_shift_operators(order, symbols, index_dict):
Generates multiple operators up to order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type object... |
generate_L_shift_operators(order, symbols, index_dict):
Generates multiple operators up to order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which
define coordinate labels.
index_dict:
Forward mapp... | generate_L_shift_operators(order, symbols, index_dict):
Generates multiple operators up to order.
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which
define coordinate labels.
Forward mapping dictionary between
monomials of symbols and array indices,
generated by g... | [
"generate_L_shift_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"multiple",
"operators",
"up",
"to",
"order",
".",
"order",
"int",
":",
"Maximum",
"order",
"of",
"multipole",
"expansion",
"symbols",
"list",
":",
"List",
"of",
"sympy",... | def generate_L_shift_operators(order, symbols, L_dict, source_order=0):
x, y, z = symbols
L_shift_operators = []
for n in L_dict.keys():
L_shift_operators.append(L_shift(n, order, symbols, L_dict, source_order=source_order))
return L_shift_operators | [
"def",
"generate_L_shift_operators",
"(",
"order",
",",
"symbols",
",",
"L_dict",
",",
"source_order",
"=",
"0",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"symbols",
"L_shift_operators",
"=",
"[",
"]",
"for",
"n",
"in",
"L_dict",
".",
"keys",
"(",
")",
... | generate_L_shift_operators(order, symbols, index_dict):
Generates multiple operators up to order. | [
"generate_L_shift_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"multiple",
"operators",
"up",
"to",
"order",
"."
] | [
"\"\"\"\n generate_L_shift_operators(order, symbols, index_dict):\n\n Generates multiple operators up to order.\n\n Input:\n order, int:\n Maximum order of multipole expansion\n\n symbols, list:\n List of sympy symbol type objects which\n define coordinate labels.\n\n index_di... | [
{
"param": "order",
"type": null
},
{
"param": "symbols",
"type": null
},
{
"param": "L_dict",
"type": null
},
{
"param": "source_order",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "order",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "symbols",
"type": null,
"docstring": null,
"docstring_tokens... |
4a4908ad2977bd089e0b833a59676f845ced4c42 | rpep/fmmgen | fmmgen/generator.py | [
"BSD-3-Clause"
] | Python | generate_M2P_operators | <not_specific> | def generate_M2P_operators(order, symbols, M_dict,
potential=True, field=True, source_order=0,
harmonic_derivs=False):
"""
generate_M2L_operators(order, symbols, index_dict)
Generates potential and field calculation operators for the
Barnes-Hut meth... |
generate_M2L_operators(order, symbols, index_dict)
Generates potential and field calculation operators for the
Barnes-Hut method up to order.
| generate_M2L_operators(order, symbols, index_dict)
Generates potential and field calculation operators for the
Barnes-Hut method up to order. | [
"generate_M2L_operators",
"(",
"order",
"symbols",
"index_dict",
")",
"Generates",
"potential",
"and",
"field",
"calculation",
"operators",
"for",
"the",
"Barnes",
"-",
"Hut",
"method",
"up",
"to",
"order",
"."
] | def generate_M2P_operators(order, symbols, M_dict,
potential=True, field=True, source_order=0,
harmonic_derivs=False):
x, y, z = symbols
R = (x**2 + y**2 + z**2)**0.5
terms = []
V = L((0, 0, 0), order, symbols, M_dict, source_order=source_order, eval... | [
"def",
"generate_M2P_operators",
"(",
"order",
",",
"symbols",
",",
"M_dict",
",",
"potential",
"=",
"True",
",",
"field",
"=",
"True",
",",
"source_order",
"=",
"0",
",",
"harmonic_derivs",
"=",
"False",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"symbol... | generate_M2L_operators(order, symbols, index_dict)
Generates potential and field calculation operators for the
Barnes-Hut method up to order. | [
"generate_M2L_operators",
"(",
"order",
"symbols",
"index_dict",
")",
"Generates",
"potential",
"and",
"field",
"calculation",
"operators",
"for",
"the",
"Barnes",
"-",
"Hut",
"method",
"up",
"to",
"order",
"."
] | [
"\"\"\"\n generate_M2L_operators(order, symbols, index_dict)\n\n Generates potential and field calculation operators for the\n Barnes-Hut method up to order.\n \"\"\""
] | [
{
"param": "order",
"type": null
},
{
"param": "symbols",
"type": null
},
{
"param": "M_dict",
"type": null
},
{
"param": "potential",
"type": null
},
{
"param": "field",
"type": null
},
{
"param": "source_order",
"type": null
},
{
"param":... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "order",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "symbols",
"type": null,
"docstring": null,
"docstring_tokens... |
4a4908ad2977bd089e0b833a59676f845ced4c42 | rpep/fmmgen | fmmgen/generator.py | [
"BSD-3-Clause"
] | Python | generate_L2P_operators | <not_specific> | def generate_L2P_operators(order, symbols, L_dict, potential=True, field=True):
"""
generate_L2P_operators(order, symbols, index_dict):
Generates potential and field calculation operators for the Fast
Multipole Method up to order.
Input:
order, int:
Maximum order of multipole expansion... |
generate_L2P_operators(order, symbols, index_dict):
Generates potential and field calculation operators for the Fast
Multipole Method up to order.
Input:
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which define coordinate ... | generate_L2P_operators(order, symbols, index_dict):
Generates potential and field calculation operators for the Fast
Multipole Method up to order.
order, int:
Maximum order of multipole expansion
symbols, list:
List of sympy symbol type objects which define coordinate labels.
Forward mapping dictionary between monom... | [
"generate_L2P_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"potential",
"and",
"field",
"calculation",
"operators",
"for",
"the",
"Fast",
"Multipole",
"Method",
"up",
"to",
"order",
".",
"order",
"int",
":",
"Maximum",
"order",
"of",... | def generate_L2P_operators(order, symbols, L_dict, potential=True, field=True):
x, y, z = symbols
terms = []
if potential:
V = phi_deriv(order, symbols, L_dict, deriv=(0, 0, 0))
terms.append(V)
if field:
Fx = -phi_deriv(order, symbols, L_dict, deriv=(1, 0, 0))
Fy = -phi_d... | [
"def",
"generate_L2P_operators",
"(",
"order",
",",
"symbols",
",",
"L_dict",
",",
"potential",
"=",
"True",
",",
"field",
"=",
"True",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"symbols",
"terms",
"=",
"[",
"]",
"if",
"potential",
":",
"V",
"=",
"ph... | generate_L2P_operators(order, symbols, index_dict):
Generates potential and field calculation operators for the Fast
Multipole Method up to order. | [
"generate_L2P_operators",
"(",
"order",
"symbols",
"index_dict",
")",
":",
"Generates",
"potential",
"and",
"field",
"calculation",
"operators",
"for",
"the",
"Fast",
"Multipole",
"Method",
"up",
"to",
"order",
"."
] | [
"\"\"\"\n generate_L2P_operators(order, symbols, index_dict):\n\n Generates potential and field calculation operators for the Fast\n Multipole Method up to order.\n\n Input:\n order, int:\n Maximum order of multipole expansion\n\n symbols, list:\n List of sympy symbol type objects wh... | [
{
"param": "order",
"type": null
},
{
"param": "symbols",
"type": null
},
{
"param": "L_dict",
"type": null
},
{
"param": "potential",
"type": null
},
{
"param": "field",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "order",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "symbols",
"type": null,
"docstring": null,
"docstring_tokens... |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | check_dependencies | null | def check_dependencies():
"""Check that all necessary dependencies are installed, and have valid versions"""
python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
if python_vers < 3.5:
print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI[... | Check that all necessary dependencies are installed, and have valid versions | Check that all necessary dependencies are installed, and have valid versions | [
"Check",
"that",
"all",
"necessary",
"dependencies",
"are",
"installed",
"and",
"have",
"valid",
"versions"
] | def check_dependencies():
python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
if python_vers < 3.5:
print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
print(' See https://github.com/pirate/bo... | [
"def",
"check_dependencies",
"(",
")",
":",
"python_vers",
"=",
"float",
"(",
"'{}.{}'",
".",
"format",
"(",
"sys",
".",
"version_info",
".",
"major",
",",
"sys",
".",
"version_info",
".",
"minor",
")",
")",
"if",
"python_vers",
"<",
"3.5",
":",
"print",... | Check that all necessary dependencies are installed, and have valid versions | [
"Check",
"that",
"all",
"necessary",
"dependencies",
"are",
"installed",
"and",
"have",
"valid",
"versions"
] | [
"\"\"\"Check that all necessary dependencies are installed, and have valid versions\"\"\"",
"# parse chrome --version e.g. Google Chrome 61.0.3114.0 canary / Chromium 59.0.3029.110 built on Ubuntu, running on Ubuntu 16.04"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | progress | <not_specific> | def progress(seconds=TIMEOUT, prefix=''):
"""Show a (subprocess-controlled) progress bar with a <seconds> timeout,
returns end() function to instantly finish the progress
"""
if not SHOW_PROGRESS:
return lambda: None
chunk = '█' if sys.stdout.encoding == 'UTF-8' else '#'
chunks = TE... | Show a (subprocess-controlled) progress bar with a <seconds> timeout,
returns end() function to instantly finish the progress
| Show a (subprocess-controlled) progress bar with a timeout,
returns end() function to instantly finish the progress | [
"Show",
"a",
"(",
"subprocess",
"-",
"controlled",
")",
"progress",
"bar",
"with",
"a",
"timeout",
"returns",
"end",
"()",
"function",
"to",
"instantly",
"finish",
"the",
"progress"
] | def progress(seconds=TIMEOUT, prefix=''):
if not SHOW_PROGRESS:
return lambda: None
chunk = '█' if sys.stdout.encoding == 'UTF-8' else '#'
chunks = TERM_WIDTH - len(prefix) - 20
def progress_bar(seconds=seconds, prefix=prefix):
try:
for s in range(seconds * chunks):
... | [
"def",
"progress",
"(",
"seconds",
"=",
"TIMEOUT",
",",
"prefix",
"=",
"''",
")",
":",
"if",
"not",
"SHOW_PROGRESS",
":",
"return",
"lambda",
":",
"None",
"chunk",
"=",
"'█' i",
" s",
"s.s",
"t",
"dout.e",
"n",
"coding =",
" '",
"TF-8' e",
"se '",
"'",... | Show a (subprocess-controlled) progress bar with a <seconds> timeout,
returns end() function to instantly finish the progress | [
"Show",
"a",
"(",
"subprocess",
"-",
"controlled",
")",
"progress",
"bar",
"with",
"a",
"<seconds",
">",
"timeout",
"returns",
"end",
"()",
"function",
"to",
"instantly",
"finish",
"the",
"progress"
] | [
"\"\"\"Show a (subprocess-controlled) progress bar with a <seconds> timeout,\n returns end() function to instantly finish the progress\n \"\"\"",
"# number of progress chunks to show (aka max bar width)",
"\"\"\"show timer in the form of progress bar, with percentage and seconds remaining\"\"\"",
"# ... | [
{
"param": "seconds",
"type": null
},
{
"param": "prefix",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "seconds",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "prefix",
"type": null,
"docstring": null,
"docstring_token... |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | progress_bar | null | def progress_bar(seconds=seconds, prefix=prefix):
"""show timer in the form of progress bar, with percentage and seconds remaining"""
try:
for s in range(seconds * chunks):
progress = s / chunks / seconds * 100
bar_width = round(progress/(100/chunks))
... | show timer in the form of progress bar, with percentage and seconds remaining | show timer in the form of progress bar, with percentage and seconds remaining | [
"show",
"timer",
"in",
"the",
"form",
"of",
"progress",
"bar",
"with",
"percentage",
"and",
"seconds",
"remaining"
] | def progress_bar(seconds=seconds, prefix=prefix):
try:
for s in range(seconds * chunks):
progress = s / chunks / seconds * 100
bar_width = round(progress/(100/chunks))
sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
pref... | [
"def",
"progress_bar",
"(",
"seconds",
"=",
"seconds",
",",
"prefix",
"=",
"prefix",
")",
":",
"try",
":",
"for",
"s",
"in",
"range",
"(",
"seconds",
"*",
"chunks",
")",
":",
"progress",
"=",
"s",
"/",
"chunks",
"/",
"seconds",
"*",
"100",
"bar_width... | show timer in the form of progress bar, with percentage and seconds remaining | [
"show",
"timer",
"in",
"the",
"form",
"of",
"progress",
"bar",
"with",
"percentage",
"and",
"seconds",
"remaining"
] | [
"\"\"\"show timer in the form of progress bar, with percentage and seconds remaining\"\"\"",
"# ████████████████████ 0.9% (1/60sec)",
"# ██████████████████████████████████ 100.0% (60/60sec)"
] | [
{
"param": "seconds",
"type": null
},
{
"param": "prefix",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "seconds",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "prefix",
"type": null,
"docstring": null,
"docstring_token... |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | end | null | def end():
"""immediately finish progress and clear the progressbar line"""
p.terminate()
sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH), ANSI['reset'])) # clear whole terminal line
sys.stdout.flush() | immediately finish progress and clear the progressbar line | immediately finish progress and clear the progressbar line | [
"immediately",
"finish",
"progress",
"and",
"clear",
"the",
"progressbar",
"line"
] | def end():
p.terminate()
sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH), ANSI['reset']))
sys.stdout.flush() | [
"def",
"end",
"(",
")",
":",
"p",
".",
"terminate",
"(",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\r{}{}\\r'",
".",
"format",
"(",
"(",
"' '",
"*",
"TERM_WIDTH",
")",
",",
"ANSI",
"[",
"'reset'",
"]",
")",
")",
"sys",
".",
"stdout",
".",
... | immediately finish progress and clear the progressbar line | [
"immediately",
"finish",
"progress",
"and",
"clear",
"the",
"progressbar",
"line"
] | [
"\"\"\"immediately finish progress and clear the progressbar line\"\"\"",
"# clear whole terminal line"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | download_url | <not_specific> | def download_url(url):
"""download a given url's content into downloads/domain.txt"""
if not os.path.exists(SOURCES_DIR):
os.makedirs(SOURCES_DIR)
ts = str(datetime.now().timestamp()).split('.', 1)[0]
source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format(domain(url), ts))
print('[*]... | download a given url's content into downloads/domain.txt | download a given url's content into downloads/domain.txt | [
"download",
"a",
"given",
"url",
"'",
"s",
"content",
"into",
"downloads",
"/",
"domain",
".",
"txt"
] | def download_url(url):
if not os.path.exists(SOURCES_DIR):
os.makedirs(SOURCES_DIR)
ts = str(datetime.now().timestamp()).split('.', 1)[0]
source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format(domain(url), ts))
print('[*] [{}] Downloading {} > {}'.format(
datetime.now().strftime('%Y-... | [
"def",
"download_url",
"(",
"url",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"SOURCES_DIR",
")",
":",
"os",
".",
"makedirs",
"(",
"SOURCES_DIR",
")",
"ts",
"=",
"str",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"timestamp",
"("... | download a given url's content into downloads/domain.txt | [
"download",
"a",
"given",
"url",
"'",
"s",
"content",
"into",
"downloads",
"/",
"domain",
".",
"txt"
] | [
"\"\"\"download a given url's content into downloads/domain.txt\"\"\""
] | [
{
"param": "url",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "url",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | merge_links | <not_specific> | def merge_links(a, b):
"""deterministially merge two links, favoring longer field values over shorter,
and "cleaner" values over worse ones.
"""
longer = lambda key: a[key] if len(a[key]) > len(b[key]) else b[key]
earlier = lambda key: a[key] if a[key] < b[key] else b[key]
url = longer('url... | deterministially merge two links, favoring longer field values over shorter,
and "cleaner" values over worse ones.
| deterministially merge two links, favoring longer field values over shorter,
and "cleaner" values over worse ones. | [
"deterministially",
"merge",
"two",
"links",
"favoring",
"longer",
"field",
"values",
"over",
"shorter",
"and",
"\"",
"cleaner",
"\"",
"values",
"over",
"worse",
"ones",
"."
] | def merge_links(a, b):
longer = lambda key: a[key] if len(a[key]) > len(b[key]) else b[key]
earlier = lambda key: a[key] if a[key] < b[key] else b[key]
url = longer('url')
longest_title = longer('title')
cleanest_title = a['title'] if '://' not in a['title'] else b['title']
link = {
'tim... | [
"def",
"merge_links",
"(",
"a",
",",
"b",
")",
":",
"longer",
"=",
"lambda",
"key",
":",
"a",
"[",
"key",
"]",
"if",
"len",
"(",
"a",
"[",
"key",
"]",
")",
">",
"len",
"(",
"b",
"[",
"key",
"]",
")",
"else",
"b",
"[",
"key",
"]",
"earlier",... | deterministially merge two links, favoring longer field values over shorter,
and "cleaner" values over worse ones. | [
"deterministially",
"merge",
"two",
"links",
"favoring",
"longer",
"field",
"values",
"over",
"shorter",
"and",
"\"",
"cleaner",
"\"",
"values",
"over",
"worse",
"ones",
"."
] | [
"\"\"\"deterministially merge two links, favoring longer field values over shorter,\n and \"cleaner\" values over worse ones.\n \"\"\""
] | [
{
"param": "a",
"type": null
},
{
"param": "b",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "a",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "b",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | find_link | <not_specific> | def find_link(folder, links):
"""for a given archive folder, find the corresponding link object in links"""
url = parse_url(folder)
if url:
for link in links:
if (link['base_url'] in url) or (url in link['url']):
return link
timestamp = folder.split('.')[0]
for l... | for a given archive folder, find the corresponding link object in links | for a given archive folder, find the corresponding link object in links | [
"for",
"a",
"given",
"archive",
"folder",
"find",
"the",
"corresponding",
"link",
"object",
"in",
"links"
] | def find_link(folder, links):
url = parse_url(folder)
if url:
for link in links:
if (link['base_url'] in url) or (url in link['url']):
return link
timestamp = folder.split('.')[0]
for link in links:
if link['timestamp'].startswith(timestamp):
if li... | [
"def",
"find_link",
"(",
"folder",
",",
"links",
")",
":",
"url",
"=",
"parse_url",
"(",
"folder",
")",
"if",
"url",
":",
"for",
"link",
"in",
"links",
":",
"if",
"(",
"link",
"[",
"'base_url'",
"]",
"in",
"url",
")",
"or",
"(",
"url",
"in",
"lin... | for a given archive folder, find the corresponding link object in links | [
"for",
"a",
"given",
"archive",
"folder",
"find",
"the",
"corresponding",
"link",
"object",
"in",
"links"
] | [
"\"\"\"for a given archive folder, find the corresponding link object in links\"\"\"",
"# careful now, this isn't safe for most ppl"
] | [
{
"param": "folder",
"type": null
},
{
"param": "links",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "folder",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "links",
"type": null,
"docstring": null,
"docstring_tokens"... |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | parse_url | <not_specific> | def parse_url(folder):
"""for a given archive folder, figure out what url it's for"""
link_json = os.path.join(ARCHIVE_DIR, folder, 'index.json')
if os.path.exists(link_json):
with open(link_json, 'r') as f:
try:
link_json = f.read().strip()
if link_json:
... | for a given archive folder, figure out what url it's for | for a given archive folder, figure out what url it's for | [
"for",
"a",
"given",
"archive",
"folder",
"figure",
"out",
"what",
"url",
"it",
"'",
"s",
"for"
] | def parse_url(folder):
link_json = os.path.join(ARCHIVE_DIR, folder, 'index.json')
if os.path.exists(link_json):
with open(link_json, 'r') as f:
try:
link_json = f.read().strip()
if link_json:
link = json.loads(link_json)
... | [
"def",
"parse_url",
"(",
"folder",
")",
":",
"link_json",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ARCHIVE_DIR",
",",
"folder",
",",
"'index.json'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"link_json",
")",
":",
"with",
"open",
"(",
"link... | for a given archive folder, figure out what url it's for | [
"for",
"a",
"given",
"archive",
"folder",
"figure",
"out",
"what",
"url",
"it",
"'",
"s",
"for"
] | [
"\"\"\"for a given archive folder, figure out what url it's for\"\"\""
] | [
{
"param": "folder",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "folder",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | manually_merge_folders | <not_specific> | def manually_merge_folders(source, target):
"""prompt for user input to resolve a conflict between two archive folders"""
if not IS_TTY:
return
fname = lambda path: path.split('/')[-1]
print(' {} and {} have conflicting files, which do you want to keep?'.format(fname(source), fname(target)... | prompt for user input to resolve a conflict between two archive folders | prompt for user input to resolve a conflict between two archive folders | [
"prompt",
"for",
"user",
"input",
"to",
"resolve",
"a",
"conflict",
"between",
"two",
"archive",
"folders"
] | def manually_merge_folders(source, target):
if not IS_TTY:
return
fname = lambda path: path.split('/')[-1]
print(' {} and {} have conflicting files, which do you want to keep?'.format(fname(source), fname(target)))
print(' - [enter]: do nothing (keep both)')
print(' - a: p... | [
"def",
"manually_merge_folders",
"(",
"source",
",",
"target",
")",
":",
"if",
"not",
"IS_TTY",
":",
"return",
"fname",
"=",
"lambda",
"path",
":",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"print",
"(",
"' {} and {} have conflicting fi... | prompt for user input to resolve a conflict between two archive folders | [
"prompt",
"for",
"user",
"input",
"to",
"resolve",
"a",
"conflict",
"between",
"two",
"archive",
"folders"
] | [
"\"\"\"prompt for user input to resolve a conflict between two archive folders\"\"\""
] | [
{
"param": "source",
"type": null
},
{
"param": "target",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "source",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "target",
"type": null,
"docstring": null,
"docstring_tokens... |
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2 | xdsoar/pocket-archive-stream | archiver/util.py | [
"MIT"
] | Python | fix_folder_path | null | def fix_folder_path(archive_path, link_folder, link):
"""given a folder, merge it to the canonical 'correct' path for the given link object"""
source = os.path.join(archive_path, link_folder)
target = os.path.join(archive_path, link['timestamp'])
url_in_folder = parse_url(source)
if not (url_in_fol... | given a folder, merge it to the canonical 'correct' path for the given link object | given a folder, merge it to the canonical 'correct' path for the given link object | [
"given",
"a",
"folder",
"merge",
"it",
"to",
"the",
"canonical",
"'",
"correct",
"'",
"path",
"for",
"the",
"given",
"link",
"object"
] | def fix_folder_path(archive_path, link_folder, link):
source = os.path.join(archive_path, link_folder)
target = os.path.join(archive_path, link['timestamp'])
url_in_folder = parse_url(source)
if not (url_in_folder in link['base_url']
or link['base_url'] in url_in_folder):
raise Value... | [
"def",
"fix_folder_path",
"(",
"archive_path",
",",
"link_folder",
",",
"link",
")",
":",
"source",
"=",
"os",
".",
"path",
".",
"join",
"(",
"archive_path",
",",
"link_folder",
")",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"archive_path",
","... | given a folder, merge it to the canonical 'correct' path for the given link object | [
"given",
"a",
"folder",
"merge",
"it",
"to",
"the",
"canonical",
"'",
"correct",
"'",
"path",
"for",
"the",
"given",
"link",
"object"
] | [
"\"\"\"given a folder, merge it to the canonical 'correct' path for the given link object\"\"\"",
"# target doesn't exist so nothing needs merging, simply move A to B",
"# target folder exists, check for conflicting files and attempt manual merge"
] | [
{
"param": "archive_path",
"type": null
},
{
"param": "link_folder",
"type": null
},
{
"param": "link",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "archive_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "link_folder",
"type": null,
"docstring": null,
"docst... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.