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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d49984e35cd982e10a8e5e461a1af5a7427d2c7 | clementbosc/iot-tweet-search-engine | parser.py | [
"Apache-2.0"
] | Python | parsing_base_corpus_pandas | <not_specific> | def parsing_base_corpus_pandas(corpus_path, separator='\t', categorize=False):
"""
Parse the corpus and return a Pandas DataFrame
:param categorize: boolean to make the tweet and user ids start to 0
:param separator:
:param corpus_path: path of the corpus
:return: pandas.DataFrame
"""
df = pd.read_csv(... |
Parse the corpus and return a Pandas DataFrame
:param categorize: boolean to make the tweet and user ids start to 0
:param separator:
:param corpus_path: path of the corpus
:return: pandas.DataFrame
| Parse the corpus and return a Pandas DataFrame | [
"Parse",
"the",
"corpus",
"and",
"return",
"a",
"Pandas",
"DataFrame"
] | def parsing_base_corpus_pandas(corpus_path, separator='\t', categorize=False):
df = pd.read_csv(corpus_path, sep=separator, dtype={'User_ID': object})
df = df.dropna(subset=['User_ID'])
if categorize:
df['User_ID_u'] = df.User_ID.astype('category').cat.codes.values
df['TweetID_u'] = df.TweetID.astype('c... | [
"def",
"parsing_base_corpus_pandas",
"(",
"corpus_path",
",",
"separator",
"=",
"'\\t'",
",",
"categorize",
"=",
"False",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"corpus_path",
",",
"sep",
"=",
"separator",
",",
"dtype",
"=",
"{",
"'User_ID'",
":"... | Parse the corpus and return a Pandas DataFrame | [
"Parse",
"the",
"corpus",
"and",
"return",
"a",
"Pandas",
"DataFrame"
] | [
"\"\"\"\n\t\tParse the corpus and return a Pandas DataFrame\n\t\t:param categorize: boolean to make the tweet and user ids start to 0\n\t\t:param separator:\n\t\t:param corpus_path: path of the corpus\n\t\t:return: pandas.DataFrame\n\t\t\"\"\"",
"# , index_col=\"TweetID\"",
"# remove tweets without users"
] | [
{
"param": "corpus_path",
"type": null
},
{
"param": "separator",
"type": null
},
{
"param": "categorize",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "corpus_path",
"type": null,
"docstring": "path of the corpus",
"docstring_tokens": [
"path",
"of",
... |
3d49984e35cd982e10a8e5e461a1af5a7427d2c7 | clementbosc/iot-tweet-search-engine | parser.py | [
"Apache-2.0"
] | Python | add_vector_to_corpus | null | def add_vector_to_corpus(corpus_path, new_corpus_path, write_every=1000):
"""
Create a new CleanedText and Vector column on the corpus
Separate the URLs by space if many
:param write_every: write in the final file every x lines
:param corpus_path:
:param new_corpus_path:
:return:
"""
parser = Parser()... |
Create a new CleanedText and Vector column on the corpus
Separate the URLs by space if many
:param write_every: write in the final file every x lines
:param corpus_path:
:param new_corpus_path:
:return:
| Create a new CleanedText and Vector column on the corpus
Separate the URLs by space if many | [
"Create",
"a",
"new",
"CleanedText",
"and",
"Vector",
"column",
"on",
"the",
"corpus",
"Separate",
"the",
"URLs",
"by",
"space",
"if",
"many"
] | def add_vector_to_corpus(corpus_path, new_corpus_path, write_every=1000):
parser = Parser()
parser.load_w2v_model()
corpus = open(corpus_path, 'r', encoding='utf-8')
new_corpus = open(new_corpus_path, 'w', encoding='utf-8')
lines = corpus.readlines()
corpus.close()
new_lines = []
last_written = -1
new... | [
"def",
"add_vector_to_corpus",
"(",
"corpus_path",
",",
"new_corpus_path",
",",
"write_every",
"=",
"1000",
")",
":",
"parser",
"=",
"Parser",
"(",
")",
"parser",
".",
"load_w2v_model",
"(",
")",
"corpus",
"=",
"open",
"(",
"corpus_path",
",",
"'r'",
",",
... | Create a new CleanedText and Vector column on the corpus
Separate the URLs by space if many | [
"Create",
"a",
"new",
"CleanedText",
"and",
"Vector",
"column",
"on",
"the",
"corpus",
"Separate",
"the",
"URLs",
"by",
"space",
"if",
"many"
] | [
"\"\"\"\n\t\tCreate a new CleanedText and Vector column on the corpus\n\t\tSeparate the URLs by space if many\n\t\t:param write_every: write in the final file every x lines\n\t\t:param corpus_path:\n\t\t:param new_corpus_path:\n\t\t:return:\n\t\t\"\"\"",
"# TweetID Sentiment TopicID Country Gender",
"# URLs sep... | [
{
"param": "corpus_path",
"type": null
},
{
"param": "new_corpus_path",
"type": null
},
{
"param": "write_every",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "corpus_path",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,... |
329be49e263bc2f0e216b64aadd28e8e385ae99f | clementbosc/iot-tweet-search-engine | models/author.py | [
"Apache-2.0"
] | Python | predict_profile | null | def predict_profile(self, topics_classifier, prediction_profile):
"""
Call all the predictions models to fill the localisation, gender, etc
:return:
"""
self.localisation = prediction_profile.country_prediction(np.array(self.vector))
self.gender = prediction_profile.gender_prediction(np.array(self.vector))... |
Call all the predictions models to fill the localisation, gender, etc
:return:
| Call all the predictions models to fill the localisation, gender, etc | [
"Call",
"all",
"the",
"predictions",
"models",
"to",
"fill",
"the",
"localisation",
"gender",
"etc"
] | def predict_profile(self, topics_classifier, prediction_profile):
self.localisation = prediction_profile.country_prediction(np.array(self.vector))
self.gender = prediction_profile.gender_prediction(np.array(self.vector))
self.emotion = prediction_profile.sentiment_prediction(np.array(self.vector))
self.topic = ... | [
"def",
"predict_profile",
"(",
"self",
",",
"topics_classifier",
",",
"prediction_profile",
")",
":",
"self",
".",
"localisation",
"=",
"prediction_profile",
".",
"country_prediction",
"(",
"np",
".",
"array",
"(",
"self",
".",
"vector",
")",
")",
"self",
".",... | Call all the predictions models to fill the localisation, gender, etc | [
"Call",
"all",
"the",
"predictions",
"models",
"to",
"fill",
"the",
"localisation",
"gender",
"etc"
] | [
"\"\"\"\n\t\tCall all the predictions models to fill the localisation, gender, etc\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "topics_classifier",
"type": null
},
{
"param": "prediction_profile",
"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
... |
329be49e263bc2f0e216b64aadd28e8e385ae99f | clementbosc/iot-tweet-search-engine | models/author.py | [
"Apache-2.0"
] | Python | update_profile | null | def update_profile(self, vec):
"""
Update the profile of the user with the new vec param
:param vec: (np.array) vector of the tweet to add
:return:
"""
self.nb_click += 1
for i in range(len(self.vector)):
self.vector[i] = (self.vector[i] * (self.nb_click - 1)) / self.nb_click + (vec[i] / self.nb_click) |
Update the profile of the user with the new vec param
:param vec: (np.array) vector of the tweet to add
:return:
| Update the profile of the user with the new vec param | [
"Update",
"the",
"profile",
"of",
"the",
"user",
"with",
"the",
"new",
"vec",
"param"
] | def update_profile(self, vec):
self.nb_click += 1
for i in range(len(self.vector)):
self.vector[i] = (self.vector[i] * (self.nb_click - 1)) / self.nb_click + (vec[i] / self.nb_click) | [
"def",
"update_profile",
"(",
"self",
",",
"vec",
")",
":",
"self",
".",
"nb_click",
"+=",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"vector",
")",
")",
":",
"self",
".",
"vector",
"[",
"i",
"]",
"=",
"(",
"self",
".",
"vect... | Update the profile of the user with the new vec param | [
"Update",
"the",
"profile",
"of",
"the",
"user",
"with",
"the",
"new",
"vec",
"param"
] | [
"\"\"\"\n\t\tUpdate the profile of the user with the new vec param\n\t\t:param vec: (np.array) vector of the tweet to add\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "vec",
"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
... |
41c3d2af5becb3f02b286c8d7443fa8e6c15263e | clementbosc/iot-tweet-search-engine | models/user.py | [
"Apache-2.0"
] | Python | predict_profile | null | def predict_profile(self, topics_classifier, prediction_profile):
"""
Call all the predictions models to fill the localisation, gender, etc
:return:
"""
self.localisation = prediction_profile.country_prediction(self.vector)
self.gender = prediction_profile.gender_prediction(self.vector)
self.emotion = pr... |
Call all the predictions models to fill the localisation, gender, etc
:return:
| Call all the predictions models to fill the localisation, gender, etc | [
"Call",
"all",
"the",
"predictions",
"models",
"to",
"fill",
"the",
"localisation",
"gender",
"etc"
] | def predict_profile(self, topics_classifier, prediction_profile):
self.localisation = prediction_profile.country_prediction(self.vector)
self.gender = prediction_profile.gender_prediction(self.vector)
self.emotion = prediction_profile.sentiment_prediction(self.vector)
self.topic = topics_classifier.predict(self... | [
"def",
"predict_profile",
"(",
"self",
",",
"topics_classifier",
",",
"prediction_profile",
")",
":",
"self",
".",
"localisation",
"=",
"prediction_profile",
".",
"country_prediction",
"(",
"self",
".",
"vector",
")",
"self",
".",
"gender",
"=",
"prediction_profil... | Call all the predictions models to fill the localisation, gender, etc | [
"Call",
"all",
"the",
"predictions",
"models",
"to",
"fill",
"the",
"localisation",
"gender",
"etc"
] | [
"\"\"\"\n\t\tCall all the predictions models to fill the localisation, gender, etc\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "topics_classifier",
"type": null
},
{
"param": "prediction_profile",
"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
... |
41c3d2af5becb3f02b286c8d7443fa8e6c15263e | clementbosc/iot-tweet-search-engine | models/user.py | [
"Apache-2.0"
] | Python | update_profile | null | def update_profile(self, vec):
"""
Update the profile of the user with the new vec param
:param vec: (np.array) vector of the tweet to add
:return:
"""
assert type(vec) == np.array
self.nb_click += 1
for i in range(len(self.vector)):
self.vector[i] = (self.vector[i] * (self.nb_click - 1)) / self.nb... |
Update the profile of the user with the new vec param
:param vec: (np.array) vector of the tweet to add
:return:
| Update the profile of the user with the new vec param | [
"Update",
"the",
"profile",
"of",
"the",
"user",
"with",
"the",
"new",
"vec",
"param"
] | def update_profile(self, vec):
assert type(vec) == np.array
self.nb_click += 1
for i in range(len(self.vector)):
self.vector[i] = (self.vector[i] * (self.nb_click - 1)) / self.nb_click + (vec[i] / self.nb_click)
tpc = TopicsClassifier()
pp = PredictionProfile()
self.predict_profile(tpc, pp)
DB.get_inst... | [
"def",
"update_profile",
"(",
"self",
",",
"vec",
")",
":",
"assert",
"type",
"(",
"vec",
")",
"==",
"np",
".",
"array",
"self",
".",
"nb_click",
"+=",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"vector",
")",
")",
":",
"self",... | Update the profile of the user with the new vec param | [
"Update",
"the",
"profile",
"of",
"the",
"user",
"with",
"the",
"new",
"vec",
"param"
] | [
"\"\"\"\n\t\tUpdate the profile of the user with the new vec param\n\t\t:param vec: (np.array) vector of the tweet to add\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "vec",
"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
... |
036665c6928163f88f13086028f180965ee9c2e8 | clementbosc/iot-tweet-search-engine | user.py | [
"Apache-2.0"
] | Python | predict_profile | null | def predict_profile(self):
"""
Call all the predictions models to fill the localisation, gender, etc
:return:
"""
self.localisation = self.get_prediction_profile().country_prediction(self.vec)
self.gender = self.get_prediction_profile().gender_prediction(self.vec)
self.emotion = self.get_prediction_profi... |
Call all the predictions models to fill the localisation, gender, etc
:return:
| Call all the predictions models to fill the localisation, gender, etc | [
"Call",
"all",
"the",
"predictions",
"models",
"to",
"fill",
"the",
"localisation",
"gender",
"etc"
] | def predict_profile(self):
self.localisation = self.get_prediction_profile().country_prediction(self.vec)
self.gender = self.get_prediction_profile().gender_prediction(self.vec)
self.emotion = self.get_prediction_profile().sentiment_prediction(self.vec)
self.topic_vector = self.get_topic_classifier().predict(se... | [
"def",
"predict_profile",
"(",
"self",
")",
":",
"self",
".",
"localisation",
"=",
"self",
".",
"get_prediction_profile",
"(",
")",
".",
"country_prediction",
"(",
"self",
".",
"vec",
")",
"self",
".",
"gender",
"=",
"self",
".",
"get_prediction_profile",
"(... | Call all the predictions models to fill the localisation, gender, etc | [
"Call",
"all",
"the",
"predictions",
"models",
"to",
"fill",
"the",
"localisation",
"gender",
"etc"
] | [
"\"\"\"\n\t\tCall all the predictions models to fill the localisation, gender, etc\n\t\t:return:\n\t\t\"\"\""
] | [
{
"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
... |
036665c6928163f88f13086028f180965ee9c2e8 | clementbosc/iot-tweet-search-engine | user.py | [
"Apache-2.0"
] | Python | update_profile | null | def update_profile(self, vec, predict=True):
"""
Update the profile of the user with the new vec param
:param vec: (np.array) vector of the tweet to add
:param predict: (boolean) whether to predict localisation, gender, etc or not
:return:
"""
self.nb_click += 1
for i in range(len(self.vec)):
self.ve... |
Update the profile of the user with the new vec param
:param vec: (np.array) vector of the tweet to add
:param predict: (boolean) whether to predict localisation, gender, etc or not
:return:
| Update the profile of the user with the new vec param | [
"Update",
"the",
"profile",
"of",
"the",
"user",
"with",
"the",
"new",
"vec",
"param"
] | def update_profile(self, vec, predict=True):
self.nb_click += 1
for i in range(len(self.vec)):
self.vec[i] = (self.vec[i] * (self.nb_click - 1)) / self.nb_click + (vec[i] / self.nb_click)
if predict:
self.predict_profile() | [
"def",
"update_profile",
"(",
"self",
",",
"vec",
",",
"predict",
"=",
"True",
")",
":",
"self",
".",
"nb_click",
"+=",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"vec",
")",
")",
":",
"self",
".",
"vec",
"[",
"i",
"]",
"=",
... | Update the profile of the user with the new vec param | [
"Update",
"the",
"profile",
"of",
"the",
"user",
"with",
"the",
"new",
"vec",
"param"
] | [
"\"\"\"\n\t\tUpdate the profile of the user with the new vec param\n\t\t:param vec: (np.array) vector of the tweet to add\n\t\t:param predict: (boolean) whether to predict localisation, gender, etc or not\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "vec",
"type": null
},
{
"param": "predict",
"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
... |
036665c6928163f88f13086028f180965ee9c2e8 | clementbosc/iot-tweet-search-engine | user.py | [
"Apache-2.0"
] | Python | save | null | def save(self):
"""
Save the user in the corresponding file
:return:
"""
users_data = {} # user_id => line
self.create_files()
f = open(User.user_fname if type(self.id) is int else User.author_fname, "r")
contents = f.readlines()
for j in range(1, len(contents)):
items = contents[j].split('\t')
... |
Save the user in the corresponding file
:return:
| Save the user in the corresponding file | [
"Save",
"the",
"user",
"in",
"the",
"corresponding",
"file"
] | def save(self):
users_data = {}
self.create_files()
f = open(User.user_fname if type(self.id) is int else User.author_fname, "r")
contents = f.readlines()
for j in range(1, len(contents)):
items = contents[j].split('\t')
id = int(items[0]) if type(self.id) is int else items[0]
users_data[id] = j
... | [
"def",
"save",
"(",
"self",
")",
":",
"users_data",
"=",
"{",
"}",
"self",
".",
"create_files",
"(",
")",
"f",
"=",
"open",
"(",
"User",
".",
"user_fname",
"if",
"type",
"(",
"self",
".",
"id",
")",
"is",
"int",
"else",
"User",
".",
"author_fname",... | Save the user in the corresponding file | [
"Save",
"the",
"user",
"in",
"the",
"corresponding",
"file"
] | [
"\"\"\"\n\t\tSave the user in the corresponding file\n\t\t:return:\n\t\t\"\"\"",
"# user_id => line",
"# if the id is not in the file"
] | [
{
"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
... |
036665c6928163f88f13086028f180965ee9c2e8 | clementbosc/iot-tweet-search-engine | user.py | [
"Apache-2.0"
] | Python | load | <not_specific> | def load(self):
"""Load the user from the corresponding file of do nothing"""
assert self.id is not None
self.create_files()
f = open(User.user_fname if type(self.id) is int else User.author_fname, "r")
lines = f.readlines()
for i in range(1, len(lines)):
l = lines[i][:-1]
items = l.split('\t')
if... | Load the user from the corresponding file of do nothing | Load the user from the corresponding file of do nothing | [
"Load",
"the",
"user",
"from",
"the",
"corresponding",
"file",
"of",
"do",
"nothing"
] | def load(self):
assert self.id is not None
self.create_files()
f = open(User.user_fname if type(self.id) is int else User.author_fname, "r")
lines = f.readlines()
for i in range(1, len(lines)):
l = lines[i][:-1]
items = l.split('\t')
if items[0] == str(self.id):
self.nb_click = int(items[1])
... | [
"def",
"load",
"(",
"self",
")",
":",
"assert",
"self",
".",
"id",
"is",
"not",
"None",
"self",
".",
"create_files",
"(",
")",
"f",
"=",
"open",
"(",
"User",
".",
"user_fname",
"if",
"type",
"(",
"self",
".",
"id",
")",
"is",
"int",
"else",
"User... | Load the user from the corresponding file of do nothing | [
"Load",
"the",
"user",
"from",
"the",
"corresponding",
"file",
"of",
"do",
"nothing"
] | [
"\"\"\"Load the user from the corresponding file of do nothing\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
036665c6928163f88f13086028f180965ee9c2e8 | clementbosc/iot-tweet-search-engine | user.py | [
"Apache-2.0"
] | Python | next_id | <not_specific> | def next_id(self):
"""Get the max +1 id in the file"""
self.create_files()
f = open(User.user_fname, "r")
contents = f.readlines()
if len(contents) == 1:
return 1
return int(contents[-1].split('\t')[0]) + 1 | Get the max +1 id in the file | Get the max +1 id in the file | [
"Get",
"the",
"max",
"+",
"1",
"id",
"in",
"the",
"file"
] | def next_id(self):
self.create_files()
f = open(User.user_fname, "r")
contents = f.readlines()
if len(contents) == 1:
return 1
return int(contents[-1].split('\t')[0]) + 1 | [
"def",
"next_id",
"(",
"self",
")",
":",
"self",
".",
"create_files",
"(",
")",
"f",
"=",
"open",
"(",
"User",
".",
"user_fname",
",",
"\"r\"",
")",
"contents",
"=",
"f",
".",
"readlines",
"(",
")",
"if",
"len",
"(",
"contents",
")",
"==",
"1",
"... | Get the max +1 id in the file | [
"Get",
"the",
"max",
"+",
"1",
"id",
"in",
"the",
"file"
] | [
"\"\"\"Get the max +1 id in the file\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
036665c6928163f88f13086028f180965ee9c2e8 | clementbosc/iot-tweet-search-engine | user.py | [
"Apache-2.0"
] | Python | create_files | null | def create_files(self):
"""
Create the users and authors files if they don't exists
:return:
"""
if (type(self.id) is int or self.id is None) and not os.path.exists(User.user_fname):
f = open(User.user_fname, 'w+')
f.write('User_Name\tNbClick\tVector\tLocalisation\tGender\tEmotion\tTopicVector\tCentrali... |
Create the users and authors files if they don't exists
:return:
| Create the users and authors files if they don't exists | [
"Create",
"the",
"users",
"and",
"authors",
"files",
"if",
"they",
"don",
"'",
"t",
"exists"
] | def create_files(self):
if (type(self.id) is int or self.id is None) and not os.path.exists(User.user_fname):
f = open(User.user_fname, 'w+')
f.write('User_Name\tNbClick\tVector\tLocalisation\tGender\tEmotion\tTopicVector\tCentrality\n')
f.close()
if type(self.id) is str and not os.path.exists(User.author_... | [
"def",
"create_files",
"(",
"self",
")",
":",
"if",
"(",
"type",
"(",
"self",
".",
"id",
")",
"is",
"int",
"or",
"self",
".",
"id",
"is",
"None",
")",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"User",
".",
"user_fname",
")",
":",
"f"... | Create the users and authors files if they don't exists | [
"Create",
"the",
"users",
"and",
"authors",
"files",
"if",
"they",
"don",
"'",
"t",
"exists"
] | [
"\"\"\"\n\t\tCreate the users and authors files if they don't exists\n\t\t:return:\n\t\t\"\"\""
] | [
{
"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
... |
036665c6928163f88f13086028f180965ee9c2e8 | clementbosc/iot-tweet-search-engine | user.py | [
"Apache-2.0"
] | Python | create_authors | <not_specific> | def create_authors(corpus):
"""
Generate the authors_profile.tsv file
To perform just ONE time
:type corpus: pandas.DataFrame
:return:
"""
tpc = TopicsClassifier(pd_corpus=corpus)
pp = PredictionProfile(pd_corpus=corpus)
for index, tweet in corpus.iterrows():
u = User(tweet.User_Name)
u.load()... |
Generate the authors_profile.tsv file
To perform just ONE time
:type corpus: pandas.DataFrame
:return:
| Generate the authors_profile.tsv file
To perform just ONE time | [
"Generate",
"the",
"authors_profile",
".",
"tsv",
"file",
"To",
"perform",
"just",
"ONE",
"time"
] | def create_authors(corpus):
tpc = TopicsClassifier(pd_corpus=corpus)
pp = PredictionProfile(pd_corpus=corpus)
for index, tweet in corpus.iterrows():
u = User(tweet.User_Name)
u.load()
u.update_profile(tweet.Vector, predict=False)
u.save()
graph = User.load_graph()
centralities = nx.eigenvector_cen... | [
"def",
"create_authors",
"(",
"corpus",
")",
":",
"tpc",
"=",
"TopicsClassifier",
"(",
"pd_corpus",
"=",
"corpus",
")",
"pp",
"=",
"PredictionProfile",
"(",
"pd_corpus",
"=",
"corpus",
")",
"for",
"index",
",",
"tweet",
"in",
"corpus",
".",
"iterrows",
"("... | Generate the authors_profile.tsv file
To perform just ONE time | [
"Generate",
"the",
"authors_profile",
".",
"tsv",
"file",
"To",
"perform",
"just",
"ONE",
"time"
] | [
"\"\"\"\n\t\tGenerate the authors_profile.tsv file\n\t\tTo perform just ONE time\n\t\t:type corpus: pandas.DataFrame\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "corpus",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "corpus",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
cf3e5adf532f7647cd8e73638143878355f9f5b7 | clementbosc/iot-tweet-search-engine | recommendation/basic_reco.py | [
"Apache-2.0"
] | Python | recommended_tweets | <not_specific> | def recommended_tweets(self, main_user, k_best=5):
"""
Use the cosine similarity between the main user thematic vector and all the tweets vectors
:param main_user: str, name of the user
:param k_best: number of results to return
:return: list of recommended tweets
"""
# Add cosine similarity between main... |
Use the cosine similarity between the main user thematic vector and all the tweets vectors
:param main_user: str, name of the user
:param k_best: number of results to return
:return: list of recommended tweets
| Use the cosine similarity between the main user thematic vector and all the tweets vectors | [
"Use",
"the",
"cosine",
"similarity",
"between",
"the",
"main",
"user",
"thematic",
"vector",
"and",
"all",
"the",
"tweets",
"vectors"
] | def recommended_tweets(self, main_user, k_best=5):
cosine_sim = cosine_similarity(np.matrix([np.array(t.vector) for t in self.tweets]),
np.array(main_user.vector).reshape(1, -1))
results = []
for i in range(len(cosine_sim)):
results.append({'cosine_sim': cosine_sim[i], 'tweet': self.tweets[i]})
r... | [
"def",
"recommended_tweets",
"(",
"self",
",",
"main_user",
",",
"k_best",
"=",
"5",
")",
":",
"cosine_sim",
"=",
"cosine_similarity",
"(",
"np",
".",
"matrix",
"(",
"[",
"np",
".",
"array",
"(",
"t",
".",
"vector",
")",
"for",
"t",
"in",
"self",
"."... | Use the cosine similarity between the main user thematic vector and all the tweets vectors | [
"Use",
"the",
"cosine",
"similarity",
"between",
"the",
"main",
"user",
"thematic",
"vector",
"and",
"all",
"the",
"tweets",
"vectors"
] | [
"\"\"\"\n\t\tUse the cosine similarity between the main user thematic vector and all the tweets vectors\n\t\t:param main_user: str, name of the user\n\t\t:param k_best: number of results to return\n\t\t:return: list of recommended tweets\n\t\t\"\"\"",
"# Add cosine similarity between main_user and all others twee... | [
{
"param": "self",
"type": null
},
{
"param": "main_user",
"type": null
},
{
"param": "k_best",
"type": null
}
] | {
"returns": [
{
"docstring": "list of recommended tweets",
"docstring_tokens": [
"list",
"of",
"recommended",
"tweets"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
... |
603ed0f6d919442962e595f2d2b5bbdb2a4f916a | cdusold/PySpeedup | pyspeedup/algorithms/_gcd.py | [
"MIT"
] | Python | gcd | <not_specific> | def gcd(a,b):
'''Using the extended Euclidean algorithm, finds the gcd between a and b.
For example::
>>> gcd(5,10)
5
>>> gcd(1024,768)
256
>>> gcd(1474038573,183508437983)
1
'''
r=a%b
if r==0:
return b
else:
return gcd(b,r) | Using the extended Euclidean algorithm, finds the gcd between a and b.
For example::
>>> gcd(5,10)
5
>>> gcd(1024,768)
256
>>> gcd(1474038573,183508437983)
1
| Using the extended Euclidean algorithm, finds the gcd between a and b.
For example:.
| [
"Using",
"the",
"extended",
"Euclidean",
"algorithm",
"finds",
"the",
"gcd",
"between",
"a",
"and",
"b",
".",
"For",
"example",
":",
"."
] | def gcd(a,b):
r=a%b
if r==0:
return b
else:
return gcd(b,r) | [
"def",
"gcd",
"(",
"a",
",",
"b",
")",
":",
"r",
"=",
"a",
"%",
"b",
"if",
"r",
"==",
"0",
":",
"return",
"b",
"else",
":",
"return",
"gcd",
"(",
"b",
",",
"r",
")"
] | Using the extended Euclidean algorithm, finds the gcd between a and b. | [
"Using",
"the",
"extended",
"Euclidean",
"algorithm",
"finds",
"the",
"gcd",
"between",
"a",
"and",
"b",
"."
] | [
"'''Using the extended Euclidean algorithm, finds the gcd between a and b.\n\n For example::\n\n >>> gcd(5,10)\n 5\n >>> gcd(1024,768)\n 256\n >>> gcd(1474038573,183508437983)\n 1\n\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": [],
... |
a2f41997d0295594c9f9eb2465a982b186d22cc7 | cdusold/PySpeedup | pyspeedup/algorithms/_invMod.py | [
"MIT"
] | Python | invMod | <not_specific> | def invMod(number,modulo):
'''Uses the extended Euclidean algorithm to deduce the inverse of 'number' mod 'modulo'.'''
#Since the quotient values are used in reverse order, postfix recursion makes sense for this equation.
# The following recursively uses Euclidean divison, then applies the tabular algorithm... | Uses the extended Euclidean algorithm to deduce the inverse of 'number' mod 'modulo'. | Uses the extended Euclidean algorithm to deduce the inverse of 'number' mod 'modulo'. | [
"Uses",
"the",
"extended",
"Euclidean",
"algorithm",
"to",
"deduce",
"the",
"inverse",
"of",
"'",
"number",
"'",
"mod",
"'",
"modulo",
"'",
"."
] | def invMod(number,modulo):
_,solution=_iM(modulo,number)
return solution%modulo | [
"def",
"invMod",
"(",
"number",
",",
"modulo",
")",
":",
"_",
",",
"solution",
"=",
"_iM",
"(",
"modulo",
",",
"number",
")",
"return",
"solution",
"%",
"modulo"
] | Uses the extended Euclidean algorithm to deduce the inverse of 'number' mod 'modulo'. | [
"Uses",
"the",
"extended",
"Euclidean",
"algorithm",
"to",
"deduce",
"the",
"inverse",
"of",
"'",
"number",
"'",
"mod",
"'",
"modulo",
"'",
"."
] | [
"'''Uses the extended Euclidean algorithm to deduce the inverse of 'number' mod 'modulo'.'''",
"#Since the quotient values are used in reverse order, postfix recursion makes sense for this equation.",
"# The following recursively uses Euclidean divison, then applies the tabular algorithm upon returning."
] | [
{
"param": "number",
"type": null
},
{
"param": "modulo",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "number",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "modulo",
"type": null,
"docstring": null,
"docstring_tokens... |
a2f41997d0295594c9f9eb2465a982b186d22cc7 | cdusold/PySpeedup | pyspeedup/algorithms/_invMod.py | [
"MIT"
] | Python | _iM | <not_specific> | def _iM(dividend,divisor):
'''A recursive helper function for use in inverting.'''
(q,r)=divmod(dividend,divisor) #Python native function that performs Euclidean division.
if r==0:
if divisor!=1:
raise Exception("Number not invertible in given set of integers.")
return (0,1)
... | A recursive helper function for use in inverting. | A recursive helper function for use in inverting. | [
"A",
"recursive",
"helper",
"function",
"for",
"use",
"in",
"inverting",
"."
] | def _iM(dividend,divisor):
(q,r)=divmod(dividend,divisor)
if r==0:
if divisor!=1:
raise Exception("Number not invertible in given set of integers.")
return (0,1)
prev,solution=_iM(divisor,r)
prev,solution=-solution,-(prev+q*solution)
return prev,solution | [
"def",
"_iM",
"(",
"dividend",
",",
"divisor",
")",
":",
"(",
"q",
",",
"r",
")",
"=",
"divmod",
"(",
"dividend",
",",
"divisor",
")",
"if",
"r",
"==",
"0",
":",
"if",
"divisor",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"Number not invertible in ... | A recursive helper function for use in inverting. | [
"A",
"recursive",
"helper",
"function",
"for",
"use",
"in",
"inverting",
"."
] | [
"'''A recursive helper function for use in inverting.'''",
"#Python native function that performs Euclidean division.",
"#Python syntax for quick value reassignment, which allows for swapping without a temporary variable.",
"#Negatives account for sign change in algorithm lazily."
] | [
{
"param": "dividend",
"type": null
},
{
"param": "divisor",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dividend",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "divisor",
"type": null,
"docstring": null,
"docstring_tok... |
9e163ab17e991d468465c4df3086935eb8074611 | cdusold/PySpeedup | pyspeedup/algorithms/_primes.py | [
"MIT"
] | Python | BrutePrimitivityTest | <not_specific> | def BrutePrimitivityTest(n):
'''Uses simple brute force calculation to determine primitivity.'''
for i in range(2,int(math.sqrt(n)+1)):
if n%i==0:
return False
return True | Uses simple brute force calculation to determine primitivity. | Uses simple brute force calculation to determine primitivity. | [
"Uses",
"simple",
"brute",
"force",
"calculation",
"to",
"determine",
"primitivity",
"."
] | def BrutePrimitivityTest(n):
for i in range(2,int(math.sqrt(n)+1)):
if n%i==0:
return False
return True | [
"def",
"BrutePrimitivityTest",
"(",
"n",
")",
":",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"int",
"(",
"math",
".",
"sqrt",
"(",
"n",
")",
"+",
"1",
")",
")",
":",
"if",
"n",
"%",
"i",
"==",
"0",
":",
"return",
"False",
"return",
"True"
] | Uses simple brute force calculation to determine primitivity. | [
"Uses",
"simple",
"brute",
"force",
"calculation",
"to",
"determine",
"primitivity",
"."
] | [
"'''Uses simple brute force calculation to determine primitivity.'''"
] | [
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
9e163ab17e991d468465c4df3086935eb8074611 | cdusold/PySpeedup | pyspeedup/algorithms/_primes.py | [
"MIT"
] | Python | StrongPrimeTest | <not_specific> | def StrongPrimeTest(n,t=2):
'''Tests for primitivity using a strong primitivity test. Does not guarantee primitivity.'''
if n==2:
return True
if n%2==0:
return False
m=n-1
k=0
while m%2==0:
m//=2
k+=1
b=pow(t,m,n)
if b==1:
return True
for i in ... | Tests for primitivity using a strong primitivity test. Does not guarantee primitivity. | Tests for primitivity using a strong primitivity test. Does not guarantee primitivity. | [
"Tests",
"for",
"primitivity",
"using",
"a",
"strong",
"primitivity",
"test",
".",
"Does",
"not",
"guarantee",
"primitivity",
"."
] | def StrongPrimeTest(n,t=2):
if n==2:
return True
if n%2==0:
return False
m=n-1
k=0
while m%2==0:
m//=2
k+=1
b=pow(t,m,n)
if b==1:
return True
for i in range(0,k):
if b==n-1:
return True
b=(b*b)%n
return False | [
"def",
"StrongPrimeTest",
"(",
"n",
",",
"t",
"=",
"2",
")",
":",
"if",
"n",
"==",
"2",
":",
"return",
"True",
"if",
"n",
"%",
"2",
"==",
"0",
":",
"return",
"False",
"m",
"=",
"n",
"-",
"1",
"k",
"=",
"0",
"while",
"m",
"%",
"2",
"==",
"... | Tests for primitivity using a strong primitivity test. | [
"Tests",
"for",
"primitivity",
"using",
"a",
"strong",
"primitivity",
"test",
"."
] | [
"'''Tests for primitivity using a strong primitivity test. Does not guarantee primitivity.'''"
] | [
{
"param": "n",
"type": null
},
{
"param": "t",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "t",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
9e163ab17e991d468465c4df3086935eb8074611 | cdusold/PySpeedup | pyspeedup/algorithms/_primes.py | [
"MIT"
] | Python | certificateOfPrimitivity | <not_specific> | def certificateOfPrimitivity(number,modulo):
'''Generates a set of the distinct prime factors, and their least nonnegative residues of the given number in the given modulo.'''
DIV=set(factor(modulo-1))
RES=[]
for i in DIV:
RES.append(int(number**((modulo-1)/i)%modulo))
return DIV,RES | Generates a set of the distinct prime factors, and their least nonnegative residues of the given number in the given modulo. | Generates a set of the distinct prime factors, and their least nonnegative residues of the given number in the given modulo. | [
"Generates",
"a",
"set",
"of",
"the",
"distinct",
"prime",
"factors",
"and",
"their",
"least",
"nonnegative",
"residues",
"of",
"the",
"given",
"number",
"in",
"the",
"given",
"modulo",
"."
] | def certificateOfPrimitivity(number,modulo):
DIV=set(factor(modulo-1))
RES=[]
for i in DIV:
RES.append(int(number**((modulo-1)/i)%modulo))
return DIV,RES | [
"def",
"certificateOfPrimitivity",
"(",
"number",
",",
"modulo",
")",
":",
"DIV",
"=",
"set",
"(",
"factor",
"(",
"modulo",
"-",
"1",
")",
")",
"RES",
"=",
"[",
"]",
"for",
"i",
"in",
"DIV",
":",
"RES",
".",
"append",
"(",
"int",
"(",
"number",
"... | Generates a set of the distinct prime factors, and their least nonnegative residues of the given number in the given modulo. | [
"Generates",
"a",
"set",
"of",
"the",
"distinct",
"prime",
"factors",
"and",
"their",
"least",
"nonnegative",
"residues",
"of",
"the",
"given",
"number",
"in",
"the",
"given",
"modulo",
"."
] | [
"'''Generates a set of the distinct prime factors, and their least nonnegative residues of the given number in the given modulo.'''"
] | [
{
"param": "number",
"type": null
},
{
"param": "modulo",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "number",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "modulo",
"type": null,
"docstring": null,
"docstring_tokens... |
9a185ef43e06f8d34659718b71529954a5717289 | cdusold/PySpeedup | pyspeedup/algorithms/_pollard-rho.py | [
"MIT"
] | Python | DiscreteLog | <not_specific> | def DiscreteLog(p,n,alpha,beta):
'''Solves the discrete log problem using the Pollard Rho algorithm.'''
def f(x,a,b):
temp=x%3
#Using sets directly from Example 6.3,
#S1={x in integers mod p: x equivalent to 1 mod 3}
#S2={x in integers mod p: x equivalent to 0 mod 3}
#S3=... | Solves the discrete log problem using the Pollard Rho algorithm. | Solves the discrete log problem using the Pollard Rho algorithm. | [
"Solves",
"the",
"discrete",
"log",
"problem",
"using",
"the",
"Pollard",
"Rho",
"algorithm",
"."
] | def DiscreteLog(p,n,alpha,beta):
def f(x,a,b):
temp=x%3
if temp==1:
return (beta*x)%p,a,(b+1)%n
if temp==0:
return (x*x)%p,(2*a)%n,(2*b)%n
return (alpha*x)%p,(a+1)%n,b
x,a,b=f(1,0,0)
xp,ap,bp=f(x,a,b)
while x!=xp:
x,a,b=f(x,a,b)
xp,... | [
"def",
"DiscreteLog",
"(",
"p",
",",
"n",
",",
"alpha",
",",
"beta",
")",
":",
"def",
"f",
"(",
"x",
",",
"a",
",",
"b",
")",
":",
"temp",
"=",
"x",
"%",
"3",
"if",
"temp",
"==",
"1",
":",
"return",
"(",
"beta",
"*",
"x",
")",
"%",
"p",
... | Solves the discrete log problem using the Pollard Rho algorithm. | [
"Solves",
"the",
"discrete",
"log",
"problem",
"using",
"the",
"Pollard",
"Rho",
"algorithm",
"."
] | [
"'''Solves the discrete log problem using the Pollard Rho algorithm.'''",
"#Using sets directly from Example 6.3,",
"#S1={x in integers mod p: x equivalent to 1 mod 3}",
"#S2={x in integers mod p: x equivalent to 0 mod 3}",
"#S3={x in integers mod p: x equivalent to 2 mod 3}"
] | [
{
"param": "p",
"type": null
},
{
"param": "n",
"type": null
},
{
"param": "alpha",
"type": null
},
{
"param": "beta",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "p",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
6718de38c99e44c0d39b89fd762cb4ccab770c16 | cdusold/PySpeedup | pyspeedup/algorithms/_divideMod.py | [
"MIT"
] | Python | divideMod | <not_specific> | def divideMod(numerator,denominator,modulo):
'''Uses the extended Euclidean algorithm to find a modular quotient.'''
#Since the quotient values are used in reverse order, postfix recursion makes sense for this equation.
# The following recursively uses Euclidean divison, then applies the tabular algorithm u... | Uses the extended Euclidean algorithm to find a modular quotient. | Uses the extended Euclidean algorithm to find a modular quotient. | [
"Uses",
"the",
"extended",
"Euclidean",
"algorithm",
"to",
"find",
"a",
"modular",
"quotient",
"."
] | def divideMod(numerator,denominator,modulo):
_,solution=_dM(numerator,denominator,modulo)
return solution%modulo | [
"def",
"divideMod",
"(",
"numerator",
",",
"denominator",
",",
"modulo",
")",
":",
"_",
",",
"solution",
"=",
"_dM",
"(",
"numerator",
",",
"denominator",
",",
"modulo",
")",
"return",
"solution",
"%",
"modulo"
] | Uses the extended Euclidean algorithm to find a modular quotient. | [
"Uses",
"the",
"extended",
"Euclidean",
"algorithm",
"to",
"find",
"a",
"modular",
"quotient",
"."
] | [
"'''Uses the extended Euclidean algorithm to find a modular quotient.'''",
"#Since the quotient values are used in reverse order, postfix recursion makes sense for this equation.",
"# The following recursively uses Euclidean divison, then applies the tabular algorithm upon returning."
] | [
{
"param": "numerator",
"type": null
},
{
"param": "denominator",
"type": null
},
{
"param": "modulo",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "numerator",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "denominator",
"type": null,
"docstring": null,
"docstrin... |
6718de38c99e44c0d39b89fd762cb4ccab770c16 | cdusold/PySpeedup | pyspeedup/algorithms/_divideMod.py | [
"MIT"
] | Python | _dM | <not_specific> | def _dM(numerator,denominator,modulo):
'''A recursive helper function for use in dividing.'''
(q,r)=divmod(modulo,denominator) #Python native function that performs Euclidean division.
if r==0:
if numerator%denominator!=0: #Then the does not divide the numerator, and thus...
raise Except... | A recursive helper function for use in dividing. | A recursive helper function for use in dividing. | [
"A",
"recursive",
"helper",
"function",
"for",
"use",
"in",
"dividing",
"."
] | def _dM(numerator,denominator,modulo):
(q,r)=divmod(modulo,denominator)
if r==0:
if numerator%denominator!=0:
raise Exception("There is no solution in the given set of integers.")
return (0,numerator//denominator)
prev,solution=_dM(numerator,r,denominator)
prev,solution=-so... | [
"def",
"_dM",
"(",
"numerator",
",",
"denominator",
",",
"modulo",
")",
":",
"(",
"q",
",",
"r",
")",
"=",
"divmod",
"(",
"modulo",
",",
"denominator",
")",
"if",
"r",
"==",
"0",
":",
"if",
"numerator",
"%",
"denominator",
"!=",
"0",
":",
"raise",
... | A recursive helper function for use in dividing. | [
"A",
"recursive",
"helper",
"function",
"for",
"use",
"in",
"dividing",
"."
] | [
"'''A recursive helper function for use in dividing.'''",
"#Python native function that performs Euclidean division.",
"#Then the does not divide the numerator, and thus...",
"#Python syntax for quick value reassignment, which allows for swapping without a temporary variable.",
"#Negatives account for sign ... | [
{
"param": "numerator",
"type": null
},
{
"param": "denominator",
"type": null
},
{
"param": "modulo",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "numerator",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "denominator",
"type": null,
"docstring": null,
"docstrin... |
d0b2493da6880df0352f215e3017e44150ef773c | cdusold/PySpeedup | pyspeedup/concurrent/_buffer.py | [
"MIT"
] | Python | uniformlyNonDecreasing | <not_specific> | def uniformlyNonDecreasing(buffer,item,attempts):
"""
Stops after the buffer has seen a value larger than the one being searched for.
The default halting condition for the Buffer class.
"""
if buffer._cache[-1]>item:
return True
return False |
Stops after the buffer has seen a value larger than the one being searched for.
The default halting condition for the Buffer class.
| Stops after the buffer has seen a value larger than the one being searched for.
The default halting condition for the Buffer class. | [
"Stops",
"after",
"the",
"buffer",
"has",
"seen",
"a",
"value",
"larger",
"than",
"the",
"one",
"being",
"searched",
"for",
".",
"The",
"default",
"halting",
"condition",
"for",
"the",
"Buffer",
"class",
"."
] | def uniformlyNonDecreasing(buffer,item,attempts):
if buffer._cache[-1]>item:
return True
return False | [
"def",
"uniformlyNonDecreasing",
"(",
"buffer",
",",
"item",
",",
"attempts",
")",
":",
"if",
"buffer",
".",
"_cache",
"[",
"-",
"1",
"]",
">",
"item",
":",
"return",
"True",
"return",
"False"
] | Stops after the buffer has seen a value larger than the one being searched for. | [
"Stops",
"after",
"the",
"buffer",
"has",
"seen",
"a",
"value",
"larger",
"than",
"the",
"one",
"being",
"searched",
"for",
"."
] | [
"\"\"\"\n Stops after the buffer has seen a value larger than the one being searched for.\n The default halting condition for the Buffer class.\n \"\"\""
] | [
{
"param": "buffer",
"type": null
},
{
"param": "item",
"type": null
},
{
"param": "attempts",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "buffer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "item",
"type": null,
"docstring": null,
"docstring_tokens":... |
d0b2493da6880df0352f215e3017e44150ef773c | cdusold/PySpeedup | pyspeedup/concurrent/_buffer.py | [
"MIT"
] | Python | absolutelyNonDecreasing | <not_specific> | def absolutelyNonDecreasing(buffer,item,attempts):
"""
Stops after the buffer has seen an absolute value larger than the one being searched for.
The example halting condition given in the documentation.
"""
if abs(buffer._cache[-1])>abs(item):
return True
return False |
Stops after the buffer has seen an absolute value larger than the one being searched for.
The example halting condition given in the documentation.
| Stops after the buffer has seen an absolute value larger than the one being searched for.
The example halting condition given in the documentation. | [
"Stops",
"after",
"the",
"buffer",
"has",
"seen",
"an",
"absolute",
"value",
"larger",
"than",
"the",
"one",
"being",
"searched",
"for",
".",
"The",
"example",
"halting",
"condition",
"given",
"in",
"the",
"documentation",
"."
] | def absolutelyNonDecreasing(buffer,item,attempts):
if abs(buffer._cache[-1])>abs(item):
return True
return False | [
"def",
"absolutelyNonDecreasing",
"(",
"buffer",
",",
"item",
",",
"attempts",
")",
":",
"if",
"abs",
"(",
"buffer",
".",
"_cache",
"[",
"-",
"1",
"]",
")",
">",
"abs",
"(",
"item",
")",
":",
"return",
"True",
"return",
"False"
] | Stops after the buffer has seen an absolute value larger than the one being searched for. | [
"Stops",
"after",
"the",
"buffer",
"has",
"seen",
"an",
"absolute",
"value",
"larger",
"than",
"the",
"one",
"being",
"searched",
"for",
"."
] | [
"\"\"\"\n Stops after the buffer has seen an absolute value larger than the one being searched for.\n The example halting condition given in the documentation.\n \"\"\""
] | [
{
"param": "buffer",
"type": null
},
{
"param": "item",
"type": null
},
{
"param": "attempts",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "buffer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "item",
"type": null,
"docstring": null,
"docstring_tokens":... |
d0b2493da6880df0352f215e3017e44150ef773c | cdusold/PySpeedup | pyspeedup/concurrent/_buffer.py | [
"MIT"
] | Python | pull_values | null | def pull_values(self):
""" A utility method used to pull and cache values from the
concurrently run generator.
"""
try:
for i in range(self._buffersize):
self._cache.append(self._q.get(False))
except Exception as e:
pass | A utility method used to pull and cache values from the
concurrently run generator.
| A utility method used to pull and cache values from the
concurrently run generator. | [
"A",
"utility",
"method",
"used",
"to",
"pull",
"and",
"cache",
"values",
"from",
"the",
"concurrently",
"run",
"generator",
"."
] | def pull_values(self):
try:
for i in range(self._buffersize):
self._cache.append(self._q.get(False))
except Exception as e:
pass | [
"def",
"pull_values",
"(",
"self",
")",
":",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_buffersize",
")",
":",
"self",
".",
"_cache",
".",
"append",
"(",
"self",
".",
"_q",
".",
"get",
"(",
"False",
")",
")",
"except",
"Exception",
... | A utility method used to pull and cache values from the
concurrently run generator. | [
"A",
"utility",
"method",
"used",
"to",
"pull",
"and",
"cache",
"values",
"from",
"the",
"concurrently",
"run",
"generator",
"."
] | [
"\"\"\" A utility method used to pull and cache values from the\n concurrently run generator.\n\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d0b2493da6880df0352f215e3017e44150ef773c | cdusold/PySpeedup | pyspeedup/concurrent/_buffer.py | [
"MIT"
] | Python | buffer | <not_specific> | def buffer(buffersize=16,haltCondition=uniformlyNonDecreasing):
'''A decorator to create a concurrently buffered generator.
Used with ``@buffer([buffersize,[haltCondition]])`` as described in :class:`~pyspeedup.concurrent.Buffer`'s documentation.
'''
def decorator(f):
return Buffer(f,buffersize... | A decorator to create a concurrently buffered generator.
Used with ``@buffer([buffersize,[haltCondition]])`` as described in :class:`~pyspeedup.concurrent.Buffer`'s documentation.
| A decorator to create a concurrently buffered generator. | [
"A",
"decorator",
"to",
"create",
"a",
"concurrently",
"buffered",
"generator",
"."
] | def buffer(buffersize=16,haltCondition=uniformlyNonDecreasing):
def decorator(f):
return Buffer(f,buffersize,haltCondition)
return decorator | [
"def",
"buffer",
"(",
"buffersize",
"=",
"16",
",",
"haltCondition",
"=",
"uniformlyNonDecreasing",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"return",
"Buffer",
"(",
"f",
",",
"buffersize",
",",
"haltCondition",
")",
"return",
"decorator"
] | A decorator to create a concurrently buffered generator. | [
"A",
"decorator",
"to",
"create",
"a",
"concurrently",
"buffered",
"generator",
"."
] | [
"'''A decorator to create a concurrently buffered generator.\n\n Used with ``@buffer([buffersize,[haltCondition]])`` as described in :class:`~pyspeedup.concurrent.Buffer`'s documentation.\n '''"
] | [
{
"param": "buffersize",
"type": null
},
{
"param": "haltCondition",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "buffersize",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "haltCondition",
"type": null,
"docstring": null,
"docst... |
1dce3f99eeb27d135b5fc773787b95e50cab8474 | cdusold/PySpeedup | pyspeedup/concurrent/_cache.py | [
"MIT"
] | Python | _parallelRun | null | def _parallelRun(a_queue,a_dict,a_func_marshal,a_func_name,a_task, an_event):
'''This runs a function, piping recursive calls to the _taskManager through a provided Queue.'''
try:
a_func=FunctionType(loads(a_func_marshal),globals(),"a_func")
globals()[a_func_name]=partial(_getValue,a_dict,a_queu... | This runs a function, piping recursive calls to the _taskManager through a provided Queue. | This runs a function, piping recursive calls to the _taskManager through a provided Queue. | [
"This",
"runs",
"a",
"function",
"piping",
"recursive",
"calls",
"to",
"the",
"_taskManager",
"through",
"a",
"provided",
"Queue",
"."
] | def _parallelRun(a_queue,a_dict,a_func_marshal,a_func_name,a_task, an_event):
try:
a_func=FunctionType(loads(a_func_marshal),globals(),"a_func")
globals()[a_func_name]=partial(_getValue,a_dict,a_queue,an_event,True,a_func)
globals()[a_func_name].apply_async=partial(_getValue,a_dict,a_queue,a... | [
"def",
"_parallelRun",
"(",
"a_queue",
",",
"a_dict",
",",
"a_func_marshal",
",",
"a_func_name",
",",
"a_task",
",",
"an_event",
")",
":",
"try",
":",
"a_func",
"=",
"FunctionType",
"(",
"loads",
"(",
"a_func_marshal",
")",
",",
"globals",
"(",
")",
",",
... | This runs a function, piping recursive calls to the _taskManager through a provided Queue. | [
"This",
"runs",
"a",
"function",
"piping",
"recursive",
"calls",
"to",
"the",
"_taskManager",
"through",
"a",
"provided",
"Queue",
"."
] | [
"'''This runs a function, piping recursive calls to the _taskManager through a provided Queue.'''",
"#setattr(globals()[a_func_name],\"__contains__\",a_dict.__contains__)"
] | [
{
"param": "a_queue",
"type": null
},
{
"param": "a_dict",
"type": null
},
{
"param": "a_func_marshal",
"type": null
},
{
"param": "a_func_name",
"type": null
},
{
"param": "a_task",
"type": null
},
{
"param": "an_event",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "a_queue",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "a_dict",
"type": null,
"docstring": null,
"docstring_token... |
1dce3f99eeb27d135b5fc773787b95e50cab8474 | cdusold/PySpeedup | pyspeedup/concurrent/_cache.py | [
"MIT"
] | Python | _getValue | <not_specific> | def _getValue(a_dict,a_queue,an_event,wait,func,*item):
'''This gets the cached value for a task, or submits a new job and waits on it to complete.'''
try:
if not wait:
return a_dict[item]
temp=a_dict[item]
while temp is _StillWaiting:
an_event.wait(.1)
... | This gets the cached value for a task, or submits a new job and waits on it to complete. | This gets the cached value for a task, or submits a new job and waits on it to complete. | [
"This",
"gets",
"the",
"cached",
"value",
"for",
"a",
"task",
"or",
"submits",
"a",
"new",
"job",
"and",
"waits",
"on",
"it",
"to",
"complete",
"."
] | def _getValue(a_dict,a_queue,an_event,wait,func,*item):
try:
if not wait:
return a_dict[item]
temp=a_dict[item]
while temp is _StillWaiting:
an_event.wait(.1)
temp=a_dict[item]
return temp
except:
a_dict[item]=_StillWaiting
if w... | [
"def",
"_getValue",
"(",
"a_dict",
",",
"a_queue",
",",
"an_event",
",",
"wait",
",",
"func",
",",
"*",
"item",
")",
":",
"try",
":",
"if",
"not",
"wait",
":",
"return",
"a_dict",
"[",
"item",
"]",
"temp",
"=",
"a_dict",
"[",
"item",
"]",
"while",
... | This gets the cached value for a task, or submits a new job and waits on it to complete. | [
"This",
"gets",
"the",
"cached",
"value",
"for",
"a",
"task",
"or",
"submits",
"a",
"new",
"job",
"and",
"waits",
"on",
"it",
"to",
"complete",
"."
] | [
"'''This gets the cached value for a task, or submits a new job and waits on it to complete.'''"
] | [
{
"param": "a_dict",
"type": null
},
{
"param": "a_queue",
"type": null
},
{
"param": "an_event",
"type": null
},
{
"param": "wait",
"type": null
},
{
"param": "func",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "a_dict",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "a_queue",
"type": null,
"docstring": null,
"docstring_token... |
1dce3f99eeb27d135b5fc773787b95e50cab8474 | cdusold/PySpeedup | pyspeedup/concurrent/_cache.py | [
"MIT"
] | Python | _batchAsync | null | def _batchAsync(a_dict,a_queue,func,*items):
'''This smartly decides how to branch asynchronously and does so synchronously if only one item is missing.'''
items = [item for item in items if item not in a_dict]
if len(items)>1:
for item in items:
a_dict[item]=_StillWaiting
a_... | This smartly decides how to branch asynchronously and does so synchronously if only one item is missing. | This smartly decides how to branch asynchronously and does so synchronously if only one item is missing. | [
"This",
"smartly",
"decides",
"how",
"to",
"branch",
"asynchronously",
"and",
"does",
"so",
"synchronously",
"if",
"only",
"one",
"item",
"is",
"missing",
"."
] | def _batchAsync(a_dict,a_queue,func,*items):
items = [item for item in items if item not in a_dict]
if len(items)>1:
for item in items:
a_dict[item]=_StillWaiting
a_queue.put(item) | [
"def",
"_batchAsync",
"(",
"a_dict",
",",
"a_queue",
",",
"func",
",",
"*",
"items",
")",
":",
"items",
"=",
"[",
"item",
"for",
"item",
"in",
"items",
"if",
"item",
"not",
"in",
"a_dict",
"]",
"if",
"len",
"(",
"items",
")",
">",
"1",
":",
"for"... | This smartly decides how to branch asynchronously and does so synchronously if only one item is missing. | [
"This",
"smartly",
"decides",
"how",
"to",
"branch",
"asynchronously",
"and",
"does",
"so",
"synchronously",
"if",
"only",
"one",
"item",
"is",
"missing",
"."
] | [
"'''This smartly decides how to branch asynchronously and does so synchronously if only one item is missing.'''"
] | [
{
"param": "a_dict",
"type": null
},
{
"param": "a_queue",
"type": null
},
{
"param": "func",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "a_dict",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "a_queue",
"type": null,
"docstring": null,
"docstring_token... |
1dce3f99eeb27d135b5fc773787b95e50cab8474 | cdusold/PySpeedup | pyspeedup/concurrent/_cache.py | [
"MIT"
] | Python | apply_async | <not_specific> | def apply_async(self,*item):
"""
Calling this method starts up a new process of the function call in question.
This does not retrieve an answer.
"""
return _getValue(self._d,self._q,self._e,False,self.func,*item) |
Calling this method starts up a new process of the function call in question.
This does not retrieve an answer.
| Calling this method starts up a new process of the function call in question.
This does not retrieve an answer. | [
"Calling",
"this",
"method",
"starts",
"up",
"a",
"new",
"process",
"of",
"the",
"function",
"call",
"in",
"question",
".",
"This",
"does",
"not",
"retrieve",
"an",
"answer",
"."
] | def apply_async(self,*item):
return _getValue(self._d,self._q,self._e,False,self.func,*item) | [
"def",
"apply_async",
"(",
"self",
",",
"*",
"item",
")",
":",
"return",
"_getValue",
"(",
"self",
".",
"_d",
",",
"self",
".",
"_q",
",",
"self",
".",
"_e",
",",
"False",
",",
"self",
".",
"func",
",",
"*",
"item",
")"
] | Calling this method starts up a new process of the function call in question. | [
"Calling",
"this",
"method",
"starts",
"up",
"a",
"new",
"process",
"of",
"the",
"function",
"call",
"in",
"question",
"."
] | [
"\"\"\"\n Calling this method starts up a new process of the function call in question.\n This does not retrieve an answer.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
af21efd8ad9462551890a6eb748c9a8e376128fe | cdusold/PySpeedup | pyspeedup/concurrent/_primer.py | [
"MIT"
] | Python | BrutePrimitivityTest | <not_specific> | def BrutePrimitivityTest(n):
'''Uses simple brute force calculation to determine primitivity.'''
for i in range(2,int(math.sqrt(n)+1)):
if n%i==0:
return [i,n//i]
return True | Uses simple brute force calculation to determine primitivity. | Uses simple brute force calculation to determine primitivity. | [
"Uses",
"simple",
"brute",
"force",
"calculation",
"to",
"determine",
"primitivity",
"."
] | def BrutePrimitivityTest(n):
for i in range(2,int(math.sqrt(n)+1)):
if n%i==0:
return [i,n//i]
return True | [
"def",
"BrutePrimitivityTest",
"(",
"n",
")",
":",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"int",
"(",
"math",
".",
"sqrt",
"(",
"n",
")",
"+",
"1",
")",
")",
":",
"if",
"n",
"%",
"i",
"==",
"0",
":",
"return",
"[",
"i",
",",
"n",
"//",
... | Uses simple brute force calculation to determine primitivity. | [
"Uses",
"simple",
"brute",
"force",
"calculation",
"to",
"determine",
"primitivity",
"."
] | [
"'''Uses simple brute force calculation to determine primitivity.'''"
] | [
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
af21efd8ad9462551890a6eb748c9a8e376128fe | cdusold/PySpeedup | pyspeedup/concurrent/_primer.py | [
"MIT"
] | Python | _parallelRun | null | def _parallelRun(a_queue,a_dict,a_func_marshal,a_func_name,a_task, an_event):
'''This runs a function, piping recursive calls to the _taskManager through a provided Queue.'''
try:
a_func=FunctionType(loads(a_func_marshal),globals(),"a_func")
globals()[a_func_name]=partial(_getValue,a_dict,a_queu... | This runs a function, piping recursive calls to the _taskManager through a provided Queue. | This runs a function, piping recursive calls to the _taskManager through a provided Queue. | [
"This",
"runs",
"a",
"function",
"piping",
"recursive",
"calls",
"to",
"the",
"_taskManager",
"through",
"a",
"provided",
"Queue",
"."
] | def _parallelRun(a_queue,a_dict,a_func_marshal,a_func_name,a_task, an_event):
try:
a_func=FunctionType(loads(a_func_marshal),globals(),"a_func")
globals()[a_func_name]=partial(_getValue,a_dict,a_queue,an_event,True,a_func)
globals()[a_func_name].apply_async=partial(_getValue,a_dict,a_queue,a... | [
"def",
"_parallelRun",
"(",
"a_queue",
",",
"a_dict",
",",
"a_func_marshal",
",",
"a_func_name",
",",
"a_task",
",",
"an_event",
")",
":",
"try",
":",
"a_func",
"=",
"FunctionType",
"(",
"loads",
"(",
"a_func_marshal",
")",
",",
"globals",
"(",
")",
",",
... | This runs a function, piping recursive calls to the _taskManager through a provided Queue. | [
"This",
"runs",
"a",
"function",
"piping",
"recursive",
"calls",
"to",
"the",
"_taskManager",
"through",
"a",
"provided",
"Queue",
"."
] | [
"'''This runs a function, piping recursive calls to the _taskManager through a provided Queue.'''"
] | [
{
"param": "a_queue",
"type": null
},
{
"param": "a_dict",
"type": null
},
{
"param": "a_func_marshal",
"type": null
},
{
"param": "a_func_name",
"type": null
},
{
"param": "a_task",
"type": null
},
{
"param": "an_event",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "a_queue",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "a_dict",
"type": null,
"docstring": null,
"docstring_token... |
8df2ee54ba18f0e59e92a144dbd733afc1ba1f6c | cdusold/PySpeedup | pyspeedup/algorithms/_Shanks.py | [
"MIT"
] | Python | Shanks | <not_specific> | def Shanks(n,alpha,beta):
'''Uses the Shanks algorithm to solve the discrete log problem for log_alpha(beta) in mod n.'''
m=int(math.ceil(math.sqrt(n)))
#The multiplicative difference between elements in list 1 is alpha to the mth power.
alphaM=pow(alpha,m,n)
#The multiplicative difference between e... | Uses the Shanks algorithm to solve the discrete log problem for log_alpha(beta) in mod n. | Uses the Shanks algorithm to solve the discrete log problem for log_alpha(beta) in mod n. | [
"Uses",
"the",
"Shanks",
"algorithm",
"to",
"solve",
"the",
"discrete",
"log",
"problem",
"for",
"log_alpha",
"(",
"beta",
")",
"in",
"mod",
"n",
"."
] | def Shanks(n,alpha,beta):
m=int(math.ceil(math.sqrt(n)))
alphaM=pow(alpha,m,n)
invAlpha=invMod(alpha,n)
L1=[(0,1)]
L2=[(0,beta)]
for j in range(1,m-1):
L1.append((j,(L1[j-1][1]*alphaM)%n))
L2.append((j,(L2[j-1][1]*invAlpha)%n))
L1.sort(key=operator.itemgetter(1))
L2.sort(... | [
"def",
"Shanks",
"(",
"n",
",",
"alpha",
",",
"beta",
")",
":",
"m",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"math",
".",
"sqrt",
"(",
"n",
")",
")",
")",
"alphaM",
"=",
"pow",
"(",
"alpha",
",",
"m",
",",
"n",
")",
"invAlpha",
"=",
"inv... | Uses the Shanks algorithm to solve the discrete log problem for log_alpha(beta) in mod n. | [
"Uses",
"the",
"Shanks",
"algorithm",
"to",
"solve",
"the",
"discrete",
"log",
"problem",
"for",
"log_alpha",
"(",
"beta",
")",
"in",
"mod",
"n",
"."
] | [
"'''Uses the Shanks algorithm to solve the discrete log problem for log_alpha(beta) in mod n.'''",
"#The multiplicative difference between elements in list 1 is alpha to the mth power.",
"#The multiplicative difference between elements in list 2 is the inverse of alpha.",
"#(j,alpha**(m*j)%n)",
"#(i,beta*al... | [
{
"param": "n",
"type": null
},
{
"param": "alpha",
"type": null
},
{
"param": "beta",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "alpha",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
84bd9fe4e2dc227c5441e8b6b11558c77e112ad5 | cdusold/PySpeedup | pyspeedup/algorithms/_factor.py | [
"MIT"
] | Python | factor | <not_specific> | def factor(N):
'''Utilizes Fermat's sieve and recursive caching to reduce factorization time, mostly in repeated factorization.'''
if N<0:
t=factor(-N)
t.insert(0,-1)
return t #Works on positive and negative integers
if N<4:
return [N] #Positive integers under 4 are factored ... | Utilizes Fermat's sieve and recursive caching to reduce factorization time, mostly in repeated factorization. | Utilizes Fermat's sieve and recursive caching to reduce factorization time, mostly in repeated factorization. | [
"Utilizes",
"Fermat",
"'",
"s",
"sieve",
"and",
"recursive",
"caching",
"to",
"reduce",
"factorization",
"time",
"mostly",
"in",
"repeated",
"factorization",
"."
] | def factor(N):
if N<0:
t=factor(-N)
t.insert(0,-1)
return t
if N<4:
return [N]
if N%2==0:
t=factor(N//2)
t.insert(0,2)
return t
a = int(math.ceil(math.sqrt(N)))
b2 = a*a - N
while not isSquare(b2):
b2+=a+a+1
a += 1
... | [
"def",
"factor",
"(",
"N",
")",
":",
"if",
"N",
"<",
"0",
":",
"t",
"=",
"factor",
"(",
"-",
"N",
")",
"t",
".",
"insert",
"(",
"0",
",",
"-",
"1",
")",
"return",
"t",
"if",
"N",
"<",
"4",
":",
"return",
"[",
"N",
"]",
"if",
"N",
"%",
... | Utilizes Fermat's sieve and recursive caching to reduce factorization time, mostly in repeated factorization. | [
"Utilizes",
"Fermat",
"'",
"s",
"sieve",
"and",
"recursive",
"caching",
"to",
"reduce",
"factorization",
"time",
"mostly",
"in",
"repeated",
"factorization",
"."
] | [
"'''Utilizes Fermat's sieve and recursive caching to reduce factorization time, mostly in repeated factorization.'''",
"#Works on positive and negative integers",
"#Positive integers under 4 are factored already (ignoring 1)",
"# equivalently: a+=1; b2 = a*a - N"
] | [
{
"param": "N",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "N",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
46a33f3a84770760ddfc0d908316293d4c4aa19c | cdusold/PySpeedup | pyspeedup/algorithms/_indexCalculus.py | [
"MIT"
] | Python | discreteLog | <not_specific> | def discreteLog(n,a,p,primes):
'''Uses index calculus to find n=a^m mod p using the list of primes provided.'''
#break up n using primes provided.
nList=[]
temp=n
for prime in primes:
while temp%prime==0:
temp//=prime
nList.append(prime)
if temp!=1:
nList.... | Uses index calculus to find n=a^m mod p using the list of primes provided. | Uses index calculus to find n=a^m mod p using the list of primes provided. | [
"Uses",
"index",
"calculus",
"to",
"find",
"n",
"=",
"a^m",
"mod",
"p",
"using",
"the",
"list",
"of",
"primes",
"provided",
"."
] | def discreteLog(n,a,p,primes):
nList=[]
temp=n
for prime in primes:
while temp%prime==0:
temp//=prime
nList.append(prime)
if temp!=1:
nList.append(temp)
primes.append(temp)
primeEquations=[]
aPowM,m=1,0
while not (len(primeEquations)==len(prime... | [
"def",
"discreteLog",
"(",
"n",
",",
"a",
",",
"p",
",",
"primes",
")",
":",
"nList",
"=",
"[",
"]",
"temp",
"=",
"n",
"for",
"prime",
"in",
"primes",
":",
"while",
"temp",
"%",
"prime",
"==",
"0",
":",
"temp",
"//=",
"prime",
"nList",
".",
"ap... | Uses index calculus to find n=a^m mod p using the list of primes provided. | [
"Uses",
"index",
"calculus",
"to",
"find",
"n",
"=",
"a^m",
"mod",
"p",
"using",
"the",
"list",
"of",
"primes",
"provided",
"."
] | [
"'''Uses index calculus to find n=a^m mod p using the list of primes provided.'''",
"#break up n using primes provided.",
"#We don't know that the value left is prime,",
"#but we can't break it up anymore with the values given.",
"#While we can't solve for one of the primes."
] | [
{
"param": "n",
"type": null
},
{
"param": "a",
"type": null
},
{
"param": "p",
"type": null
},
{
"param": "primes",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "a",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
46a33f3a84770760ddfc0d908316293d4c4aa19c | cdusold/PySpeedup | pyspeedup/algorithms/_indexCalculus.py | [
"MIT"
] | Python | rowReduce | <not_specific> | def rowReduce(lstList,p):
'''Takes a list of lists as a representation of rows of a matrix mod p, and reduces it.'''
#Partial Gaussian Elimination, pivoting on invertible elements.
length=min(len(lstList),len(lstList[0])-1)
for i in range(0,length):
if lstList[i][i]%p==0 or gcd(lstList[i][i],p)!... | Takes a list of lists as a representation of rows of a matrix mod p, and reduces it. | Takes a list of lists as a representation of rows of a matrix mod p, and reduces it. | [
"Takes",
"a",
"list",
"of",
"lists",
"as",
"a",
"representation",
"of",
"rows",
"of",
"a",
"matrix",
"mod",
"p",
"and",
"reduces",
"it",
"."
] | def rowReduce(lstList,p):
length=min(len(lstList),len(lstList[0])-1)
for i in range(0,length):
if lstList[i][i]%p==0 or gcd(lstList[i][i],p)!=1:
for j in range(i,len(lstList)):
if lstList[j][i]%p!=0 and gcd(lstList[j][i],p)==1:
lstList.insert(i,lstList.pop... | [
"def",
"rowReduce",
"(",
"lstList",
",",
"p",
")",
":",
"length",
"=",
"min",
"(",
"len",
"(",
"lstList",
")",
",",
"len",
"(",
"lstList",
"[",
"0",
"]",
")",
"-",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"length",
")",
":",
"if",
... | Takes a list of lists as a representation of rows of a matrix mod p, and reduces it. | [
"Takes",
"a",
"list",
"of",
"lists",
"as",
"a",
"representation",
"of",
"rows",
"of",
"a",
"matrix",
"mod",
"p",
"and",
"reduces",
"it",
"."
] | [
"'''Takes a list of lists as a representation of rows of a matrix mod p, and reduces it.'''",
"#Partial Gaussian Elimination, pivoting on invertible elements.",
"#Tries division, and has a default alternative.",
"#This won't change the results, but may reduce the magnitude.",
"#Won't change anything but wil... | [
{
"param": "lstList",
"type": null
},
{
"param": "p",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "lstList",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "p",
"type": null,
"docstring": null,
"docstring_tokens": [... |
23cdd866ad0418c3f8aedb76414c4fa4a97a152d | cdusold/PySpeedup | pyspeedup/algorithms/_cached.py | [
"MIT"
] | Python | cached | <not_specific> | def cached(numberOfCachedValues, popType='random'):
'''A decorator that creates a simplistic cached function with minimal overhead.
This provides very simplistic and quick cache.
'''
def decorator(f):
return _Cached(f,numberOfCachedValues,popType)
return decorator | A decorator that creates a simplistic cached function with minimal overhead.
This provides very simplistic and quick cache.
| A decorator that creates a simplistic cached function with minimal overhead.
This provides very simplistic and quick cache. | [
"A",
"decorator",
"that",
"creates",
"a",
"simplistic",
"cached",
"function",
"with",
"minimal",
"overhead",
".",
"This",
"provides",
"very",
"simplistic",
"and",
"quick",
"cache",
"."
] | def cached(numberOfCachedValues, popType='random'):
def decorator(f):
return _Cached(f,numberOfCachedValues,popType)
return decorator | [
"def",
"cached",
"(",
"numberOfCachedValues",
",",
"popType",
"=",
"'random'",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"return",
"_Cached",
"(",
"f",
",",
"numberOfCachedValues",
",",
"popType",
")",
"return",
"decorator"
] | A decorator that creates a simplistic cached function with minimal overhead. | [
"A",
"decorator",
"that",
"creates",
"a",
"simplistic",
"cached",
"function",
"with",
"minimal",
"overhead",
"."
] | [
"'''A decorator that creates a simplistic cached function with minimal overhead.\n\n This provides very simplistic and quick cache.\n '''"
] | [
{
"param": "numberOfCachedValues",
"type": null
},
{
"param": "popType",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "numberOfCachedValues",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "popType",
"type": null,
"docstring": null,
"d... |
f4dcb707c023445fecc7786ea94076870e3b8988 | cdusold/PySpeedup | pyspeedup/algorithms/_squares.py | [
"MIT"
] | Python | isSquare | <not_specific> | def isSquare(n):
'''
Checks for perfect squares by checking mod 64 to rule out 52/64 cases immediately.
It does so by checking various smaller mods, such as mod 4, where 2 and 3 aren't possible.
'''
# non-neg and mod 4 and mod 8 and mod 16 and mod 32 and mod 64 #mod isSquare.mod
... |
Checks for perfect squares by checking mod 64 to rule out 52/64 cases immediately.
It does so by checking various smaller mods, such as mod 4, where 2 and 3 aren't possible.
| Checks for perfect squares by checking mod 64 to rule out 52/64 cases immediately.
It does so by checking various smaller mods, such as mod 4, where 2 and 3 aren't possible. | [
"Checks",
"for",
"perfect",
"squares",
"by",
"checking",
"mod",
"64",
"to",
"rule",
"out",
"52",
"/",
"64",
"cases",
"immediately",
".",
"It",
"does",
"so",
"by",
"checking",
"various",
"smaller",
"mods",
"such",
"as",
"mod",
"4",
"where",
"2",
"and",
... | def isSquare(n):
m=math.floor(math.sqrt(n)+.5)
return m*m==n and m
if n>=0 and (n&2==0) and (n&7!=5) and (n&11!=8):
m=math.floor(math.sqrt(n)+.5)
return m*m==n and m
return False | [
"def",
"isSquare",
"(",
"n",
")",
":",
"m",
"=",
"math",
".",
"floor",
"(",
"math",
".",
"sqrt",
"(",
"n",
")",
"+",
".5",
")",
"return",
"m",
"*",
"m",
"==",
"n",
"and",
"m",
"if",
"n",
">=",
"0",
"and",
"(",
"n",
"&",
"2",
"==",
"0",
... | Checks for perfect squares by checking mod 64 to rule out 52/64 cases immediately. | [
"Checks",
"for",
"perfect",
"squares",
"by",
"checking",
"mod",
"64",
"to",
"rule",
"out",
"52",
"/",
"64",
"cases",
"immediately",
"."
] | [
"'''\n Checks for perfect squares by checking mod 64 to rule out 52/64 cases immediately.\n\n It does so by checking various smaller mods, such as mod 4, where 2 and 3 aren't possible.\n '''",
"# non-neg and mod 4 and mod 8 and mod 16 and mod 32 and mod 64 #mod isSquare.mod",
"# and ... | [
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f4dcb707c023445fecc7786ea94076870e3b8988 | cdusold/PySpeedup | pyspeedup/algorithms/_squares.py | [
"MIT"
] | Python | tsSquareRoot | <not_specific> | def tsSquareRoot(a,p): #Currently requires p to be prime.
'''Calculates the square root mod p of a.'''
jacobi=jacobi_symbol(a,p)
if jacobi==-1:
raise ValueError("No square root mod {0} exists.".format(p))
s=p-1
e=0
while s%2==0: #Find p-1=s*2^e with odd s.
e+=1
s//=2
... | Calculates the square root mod p of a. | Calculates the square root mod p of a. | [
"Calculates",
"the",
"square",
"root",
"mod",
"p",
"of",
"a",
"."
] | def tsSquareRoot(a,p):
jacobi=jacobi_symbol(a,p)
if jacobi==-1:
raise ValueError("No square root mod {0} exists.".format(p))
s=p-1
e=0
while s%2==0:
e+=1
s//=2
n=findQuadraticNonresidue(p)
x=pow(a,((s+1)/2),p)
b=pow(a,s,p) correction
g=pow(n,s,p)
r=e
... | [
"def",
"tsSquareRoot",
"(",
"a",
",",
"p",
")",
":",
"jacobi",
"=",
"jacobi_symbol",
"(",
"a",
",",
"p",
")",
"if",
"jacobi",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"No square root mod {0} exists.\"",
".",
"format",
"(",
"p",
")",
")",
"s",... | Calculates the square root mod p of a. | [
"Calculates",
"the",
"square",
"root",
"mod",
"p",
"of",
"a",
"."
] | [
"#Currently requires p to be prime.",
"'''Calculates the square root mod p of a.'''",
"#Find p-1=s*2^e with odd s.",
"#first guess",
"#first guess correction",
"#quantity to modify x and b",
"#ord_p(g)=ord_p(pow(n,s,p))",
"#Note (n^s)^2^e=n^(2^e*s)=n^(p-1)=1 mod p",
"#claim ord_p(g)=2^e, because",
... | [
{
"param": "a",
"type": null
},
{
"param": "p",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "a",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "p",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
2056e62171bf380b21c941f5588700a8a060760b | cdusold/PySpeedup | pyspeedup/algorithms/_fibonacci.py | [
"MIT"
] | Python | fibonacci | <not_specific> | def fibonacci(n):
"""Computes the nth Fibonacci number. For example::
>>> map(fibonacci,range(10))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Utilizes modified code from `this answer on Stack Overflow
<http://stackoverflow.com/a/14782458/786020>`_ based upon the concept
explained `here on Wikip... | Computes the nth Fibonacci number. For example::
>>> map(fibonacci,range(10))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Utilizes modified code from `this answer on Stack Overflow
<http://stackoverflow.com/a/14782458/786020>`_ based upon the concept
explained `here on Wikipedia <http://en.wikipedia... | Computes the nth Fibonacci number.
This function is mostly intended to demonstrate the uses of apply_async, and could
easily be improved. | [
"Computes",
"the",
"nth",
"Fibonacci",
"number",
".",
"This",
"function",
"is",
"mostly",
"intended",
"to",
"demonstrate",
"the",
"uses",
"of",
"apply_async",
"and",
"could",
"easily",
"be",
"improved",
"."
] | def fibonacci(n):
if n<0:
raise Exception("Reverse fibonacci sequence not implemented.")
if n <= 3:
return (0, 1, 1, 2)[n]
half,odd=divmod(n,2)
if odd:
fibonacci.apply_async(half)
fibonacci.apply_async(half + 1)
a = fibonacci(half)
b = fibonacci(half + 1)... | [
"def",
"fibonacci",
"(",
"n",
")",
":",
"if",
"n",
"<",
"0",
":",
"raise",
"Exception",
"(",
"\"Reverse fibonacci sequence not implemented.\"",
")",
"if",
"n",
"<=",
"3",
":",
"return",
"(",
"0",
",",
"1",
",",
"1",
",",
"2",
")",
"[",
"n",
"]",
"h... | Computes the nth Fibonacci number. | [
"Computes",
"the",
"nth",
"Fibonacci",
"number",
"."
] | [
"\"\"\"Computes the nth Fibonacci number. For example::\n\n >>> map(fibonacci,range(10))\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n\n Utilizes modified code from `this answer on Stack Overflow\n <http://stackoverflow.com/a/14782458/786020>`_ based upon the concept\n explained `here on Wikipedia <h... | [
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
da20577f4ecaf5a1f05d41072021430d52392cdc | MUONetwork/muon.github.io | bibtex2html/bibtex2html.py | [
"CC-BY-3.0"
] | Python | cleanup_author | <not_specific> | def cleanup_author(s):
"""Clean up and format author names.
cleanup_author(str) -> str
"""
dictionary = {'\\"a': 'ä', '\\"A': 'Ä', '\\"e': 'ë',
'\\"E': 'Ë', '\\"i': 'ï', '\\"I': 'Ï', '\\"o': 'ö',
'\\"O': 'Ö', '\\"u': 'ü', '\\"U': 'Ü', "\\'a":... | Clean up and format author names.
cleanup_author(str) -> str
| Clean up and format author names. | [
"Clean",
"up",
"and",
"format",
"author",
"names",
"."
] | def cleanup_author(s):
dictionary = {'\\"a': 'ä', '\\"A': 'Ä', '\\"e': 'ë',
'\\"E': 'Ë', '\\"i': 'ï', '\\"I': 'Ï', '\\"o': 'ö',
'\\"O': 'Ö', '\\"u': 'ü', '\\"U': 'Ü', "\\'a": 'á',
"\\'A": 'Á', "\\'e": 'é', "\\'i": 'í',
... | [
"def",
"cleanup_author",
"(",
"s",
")",
":",
"dictionary",
"=",
"{",
"'\\\\\"a'",
":",
"'ä'",
",",
"'\\\\\"A'",
":",
"'Ä'",
",",
"'\\\\\"e'",
":",
"'ë'",
",",
"'\\\\\"E'",
":",
"'Ë'",
",",
"'\\\\\"i'",
":",
"'ï'",
",",
"'\\\\\"I'",
... | Clean up and format author names. | [
"Clean",
"up",
"and",
"format",
"author",
"names",
"."
] | [
"\"\"\"Clean up and format author names.\n\n cleanup_author(str) -> str\n \"\"\""
] | [
{
"param": "s",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "s",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
da20577f4ecaf5a1f05d41072021430d52392cdc | MUONetwork/muon.github.io | bibtex2html/bibtex2html.py | [
"CC-BY-3.0"
] | Python | cleanup_title | <not_specific> | def cleanup_title(s):
"""Clean up and format article titles.
cleanup_title(str) -> str
"""
s = s.lower()
s = s.capitalize()
return s | Clean up and format article titles.
cleanup_title(str) -> str
| Clean up and format article titles. | [
"Clean",
"up",
"and",
"format",
"article",
"titles",
"."
] | def cleanup_title(s):
s = s.lower()
s = s.capitalize()
return s | [
"def",
"cleanup_title",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"lower",
"(",
")",
"s",
"=",
"s",
".",
"capitalize",
"(",
")",
"return",
"s"
] | Clean up and format article titles. | [
"Clean",
"up",
"and",
"format",
"article",
"titles",
"."
] | [
"\"\"\"Clean up and format article titles.\n\n cleanup_title(str) -> str\n \"\"\""
] | [
{
"param": "s",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "s",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
da20577f4ecaf5a1f05d41072021430d52392cdc | MUONetwork/muon.github.io | bibtex2html/bibtex2html.py | [
"CC-BY-3.0"
] | Python | cleanup_page | <not_specific> | def cleanup_page(s):
"""Clean up the article page string.
cleanup_pages(str) -> str
"""
s = s.replace('--', '-')
return s | Clean up the article page string.
cleanup_pages(str) -> str
| Clean up the article page string. | [
"Clean",
"up",
"the",
"article",
"page",
"string",
"."
] | def cleanup_page(s):
s = s.replace('--', '-')
return s | [
"def",
"cleanup_page",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'--'",
",",
"'-'",
")",
"return",
"s"
] | Clean up the article page string. | [
"Clean",
"up",
"the",
"article",
"page",
"string",
"."
] | [
"\"\"\"Clean up the article page string.\n\n cleanup_pages(str) -> str\n \"\"\""
] | [
{
"param": "s",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "s",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
83afce6279e0b52a01e849e933a4e987a9f01c21 | VChristlein/textsegment | dataset/pascal_voc.py | [
"MIT"
] | Python | prepare_pascal_voc | null | def prepare_pascal_voc(data_dir=DEFAULT_DATA_DIR,
out_dir=DEFAULT_RECORD_DIR,
force=False):
""" Downloads and extracts pascal voc and its annotation data. """
print("Warning: This dataset was for testing only. It probably won't work anymore.")
if not os.path.exists(d... | Downloads and extracts pascal voc and its annotation data. | Downloads and extracts pascal voc and its annotation data. | [
"Downloads",
"and",
"extracts",
"pascal",
"voc",
"and",
"its",
"annotation",
"data",
"."
] | def prepare_pascal_voc(data_dir=DEFAULT_DATA_DIR,
out_dir=DEFAULT_RECORD_DIR,
force=False):
print("Warning: This dataset was for testing only. It probably won't work anymore.")
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if not os.path.exists(out_dir):
... | [
"def",
"prepare_pascal_voc",
"(",
"data_dir",
"=",
"DEFAULT_DATA_DIR",
",",
"out_dir",
"=",
"DEFAULT_RECORD_DIR",
",",
"force",
"=",
"False",
")",
":",
"print",
"(",
"\"Warning: This dataset was for testing only. It probably won't work anymore.\"",
")",
"if",
"not",
"os",... | Downloads and extracts pascal voc and its annotation data. | [
"Downloads",
"and",
"extracts",
"pascal",
"voc",
"and",
"its",
"annotation",
"data",
"."
] | [
"\"\"\" Downloads and extracts pascal voc and its annotation data. \"\"\""
] | [
{
"param": "data_dir",
"type": null
},
{
"param": "out_dir",
"type": null
},
{
"param": "force",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data_dir",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "out_dir",
"type": null,
"docstring": null,
"docstring_tok... |
0bd2a242f640778b2b39898282904c2794d9a1a0 | VChristlein/textsegment | dataset/dibco.py | [
"MIT"
] | Python | prepare_dibco | <not_specific> | def prepare_dibco(data_dir=DEFAULT_DATA_DIR,
out_dir=None,
force=False):
""" Downloads and extracts dibco dataset and its annotation data. """
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if out_dir is None:
out_dir = data_dir
if not os.path.exists(out_dir):... | Downloads and extracts dibco dataset and its annotation data. | Downloads and extracts dibco dataset and its annotation data. | [
"Downloads",
"and",
"extracts",
"dibco",
"dataset",
"and",
"its",
"annotation",
"data",
"."
] | def prepare_dibco(data_dir=DEFAULT_DATA_DIR,
out_dir=None,
force=False):
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if out_dir is None:
out_dir = data_dir
if not os.path.exists(out_dir):
os.makedirs(out_dir)
train_record = 'train.record'
test_record ... | [
"def",
"prepare_dibco",
"(",
"data_dir",
"=",
"DEFAULT_DATA_DIR",
",",
"out_dir",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"data_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"data_dir",
")",
... | Downloads and extracts dibco dataset and its annotation data. | [
"Downloads",
"and",
"extracts",
"dibco",
"dataset",
"and",
"its",
"annotation",
"data",
"."
] | [
"\"\"\" Downloads and extracts dibco dataset and its annotation data. \"\"\""
] | [
{
"param": "data_dir",
"type": null
},
{
"param": "out_dir",
"type": null
},
{
"param": "force",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data_dir",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "out_dir",
"type": null,
"docstring": null,
"docstring_tok... |
dd6b69387bc7bdac6c95fd67623da00cb72d393b | VChristlein/textsegment | dataset/hisdb.py | [
"MIT"
] | Python | prepare_hisdb | <not_specific> | def prepare_hisdb(data_dir=DEFAULT_DATA_DIR,
out_dir=None,
force=False):
""" Downloads and extracts dibco dataset and its annotation data. """
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if out_dir is None:
out_dir = data_dir
if not os.path.exists(out_dir):... | Downloads and extracts dibco dataset and its annotation data. | Downloads and extracts dibco dataset and its annotation data. | [
"Downloads",
"and",
"extracts",
"dibco",
"dataset",
"and",
"its",
"annotation",
"data",
"."
] | def prepare_hisdb(data_dir=DEFAULT_DATA_DIR,
out_dir=None,
force=False):
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if out_dir is None:
out_dir = data_dir
if not os.path.exists(out_dir):
os.makedirs(out_dir)
train_record = 'train.record'
test_record ... | [
"def",
"prepare_hisdb",
"(",
"data_dir",
"=",
"DEFAULT_DATA_DIR",
",",
"out_dir",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"data_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"data_dir",
")",
... | Downloads and extracts dibco dataset and its annotation data. | [
"Downloads",
"and",
"extracts",
"dibco",
"dataset",
"and",
"its",
"annotation",
"data",
"."
] | [
"\"\"\" Downloads and extracts dibco dataset and its annotation data. \"\"\""
] | [
{
"param": "data_dir",
"type": null
},
{
"param": "out_dir",
"type": null
},
{
"param": "force",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data_dir",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "out_dir",
"type": null,
"docstring": null,
"docstring_tok... |
bbe39435992fa8ae10d5e37b8a3eadde825e4e9f | VChristlein/textsegment | utils/layers.py | [
"MIT"
] | Python | batch_norm_relu | <not_specific> | def batch_norm_relu(inputs, is_training, data_format):
"""Performs a batch normalization followed by a ReLU."""
# We set fused=True for a significant performance boost. See
# https://www.tensorflow.org/performance/performance_guide#common_fused_ops
inputs = tf.layers.batch_normalization(
inputs=inputs, ax... | Performs a batch normalization followed by a ReLU. | Performs a batch normalization followed by a ReLU. | [
"Performs",
"a",
"batch",
"normalization",
"followed",
"by",
"a",
"ReLU",
"."
] | def batch_norm_relu(inputs, is_training, data_format):
inputs = tf.layers.batch_normalization(
inputs=inputs, axis=1 if data_format == 'channels_first' else 3,
momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True,
scale=True, training=is_training, fused=True)
return tf.nn.relu(inpu... | [
"def",
"batch_norm_relu",
"(",
"inputs",
",",
"is_training",
",",
"data_format",
")",
":",
"inputs",
"=",
"tf",
".",
"layers",
".",
"batch_normalization",
"(",
"inputs",
"=",
"inputs",
",",
"axis",
"=",
"1",
"if",
"data_format",
"==",
"'channels_first'",
"el... | Performs a batch normalization followed by a ReLU. | [
"Performs",
"a",
"batch",
"normalization",
"followed",
"by",
"a",
"ReLU",
"."
] | [
"\"\"\"Performs a batch normalization followed by a ReLU.\"\"\"",
"# We set fused=True for a significant performance boost. See",
"# https://www.tensorflow.org/performance/performance_guide#common_fused_ops"
] | [
{
"param": "inputs",
"type": null
},
{
"param": "is_training",
"type": null
},
{
"param": "data_format",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "inputs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "is_training",
"type": null,
"docstring": null,
"docstring_t... |
bbe39435992fa8ae10d5e37b8a3eadde825e4e9f | VChristlein/textsegment | utils/layers.py | [
"MIT"
] | Python | conv2d_fixed_padding | <not_specific> | def conv2d_fixed_padding(inputs, filters, kernel_size, strides, use_bias,
data_format):
"""Strided 2-D convolution with explicit padding."""
# The padding is consistent and is based only on `kernel_size`, not on the
# dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).
... | Strided 2-D convolution with explicit padding. | Strided 2-D convolution with explicit padding. | [
"Strided",
"2",
"-",
"D",
"convolution",
"with",
"explicit",
"padding",
"."
] | def conv2d_fixed_padding(inputs, filters, kernel_size, strides, use_bias,
data_format):
if strides > 1:
inputs = fixed_padding(inputs, kernel_size, data_format)
return tf.layers.conv2d(
inputs=inputs,
filters=filters,
kernel_size=kernel_size,
strides=strides,
... | [
"def",
"conv2d_fixed_padding",
"(",
"inputs",
",",
"filters",
",",
"kernel_size",
",",
"strides",
",",
"use_bias",
",",
"data_format",
")",
":",
"if",
"strides",
">",
"1",
":",
"inputs",
"=",
"fixed_padding",
"(",
"inputs",
",",
"kernel_size",
",",
"data_for... | Strided 2-D convolution with explicit padding. | [
"Strided",
"2",
"-",
"D",
"convolution",
"with",
"explicit",
"padding",
"."
] | [
"\"\"\"Strided 2-D convolution with explicit padding.\"\"\"",
"# The padding is consistent and is based only on `kernel_size`, not on the",
"# dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone)."
] | [
{
"param": "inputs",
"type": null
},
{
"param": "filters",
"type": null
},
{
"param": "kernel_size",
"type": null
},
{
"param": "strides",
"type": null
},
{
"param": "use_bias",
"type": null
},
{
"param": "data_format",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "inputs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "filters",
"type": null,
"docstring": null,
"docstring_token... |
51096caa6e1480e7e520349f8c43977b51a5c290 | VChristlein/textsegment | utils/tf_image_processing.py | [
"MIT"
] | Python | rgb_to_bgr | <not_specific> | def rgb_to_bgr(images, name=None):
""" Transforms a image tensor from RGB to BGR data format.
Args:
images: A tensor of shape (num_images, num_rows, num_columns, num_channels)
(NHWC), (num_rows, num_columns, num_channels) (HWC), where num_channels
must be 3.
name: A name for the operation (op... | Transforms a image tensor from RGB to BGR data format.
Args:
images: A tensor of shape (num_images, num_rows, num_columns, num_channels)
(NHWC), (num_rows, num_columns, num_channels) (HWC), where num_channels
must be 3.
name: A name for the operation (optional).
Returns:
A Tensor of the... | Transforms a image tensor from RGB to BGR data format. | [
"Transforms",
"a",
"image",
"tensor",
"from",
"RGB",
"to",
"BGR",
"data",
"format",
"."
] | def rgb_to_bgr(images, name=None):
with tf.name_scope(name, 'RgbToBgr', [images]):
axis = 2 if images.get_shape().ndims == 3 else 3
r, g, b = tf.split(images, axis=axis, num_or_size_splits=3)
images = tf.concat(axis=axis, values=[b, g, r])
return images | [
"def",
"rgb_to_bgr",
"(",
"images",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'RgbToBgr'",
",",
"[",
"images",
"]",
")",
":",
"axis",
"=",
"2",
"if",
"images",
".",
"get_shape",
"(",
")",
".",
"ndims",
... | Transforms a image tensor from RGB to BGR data format. | [
"Transforms",
"a",
"image",
"tensor",
"from",
"RGB",
"to",
"BGR",
"data",
"format",
"."
] | [
"\"\"\" Transforms a image tensor from RGB to BGR data format.\n\n Args:\n images: A tensor of shape (num_images, num_rows, num_columns, num_channels)\n (NHWC), (num_rows, num_columns, num_channels) (HWC), where num_channels\n must be 3.\n name: A name for the operation (optional).\n\n Returns:\... | [
{
"param": "images",
"type": null
},
{
"param": "name",
"type": null
}
] | {
"returns": [
{
"docstring": "A Tensor of the same shape like `images`.",
"docstring_tokens": [
"A",
"Tensor",
"of",
"the",
"same",
"shape",
"like",
"`",
"images",
"`",
"."
],
"type": null
}
],
... |
51096caa6e1480e7e520349f8c43977b51a5c290 | VChristlein/textsegment | utils/tf_image_processing.py | [
"MIT"
] | Python | bgr_to_rgb | <not_specific> | def bgr_to_rgb(images, name=None):
""" Transforms a image tensor from BGR to RGB data format.
Args:
images: A tensor of shape (num_images, num_rows, num_columns, num_channels)
(NHWC), (num_rows, num_columns, num_channels) (HWC), where num_channels
must be 3.
name: A name for the operation (op... | Transforms a image tensor from BGR to RGB data format.
Args:
images: A tensor of shape (num_images, num_rows, num_columns, num_channels)
(NHWC), (num_rows, num_columns, num_channels) (HWC), where num_channels
must be 3.
name: A name for the operation (optional).
Returns:
A Tensor of the... | Transforms a image tensor from BGR to RGB data format. | [
"Transforms",
"a",
"image",
"tensor",
"from",
"BGR",
"to",
"RGB",
"data",
"format",
"."
] | def bgr_to_rgb(images, name=None):
with tf.name_scope(name, 'RgbToBgr', [images]):
axis = 2 if images.get_shape().ndims == 3 else 3
b, g, r = tf.split(images, axis=axis, num_or_size_splits=3)
images = tf.concat(axis=axis, values=[r, g, b])
return images | [
"def",
"bgr_to_rgb",
"(",
"images",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'RgbToBgr'",
",",
"[",
"images",
"]",
")",
":",
"axis",
"=",
"2",
"if",
"images",
".",
"get_shape",
"(",
")",
".",
"ndims",
... | Transforms a image tensor from BGR to RGB data format. | [
"Transforms",
"a",
"image",
"tensor",
"from",
"BGR",
"to",
"RGB",
"data",
"format",
"."
] | [
"\"\"\" Transforms a image tensor from BGR to RGB data format.\n\n Args:\n images: A tensor of shape (num_images, num_rows, num_columns, num_channels)\n (NHWC), (num_rows, num_columns, num_channels) (HWC), where num_channels\n must be 3.\n name: A name for the operation (optional).\n\n Returns:\... | [
{
"param": "images",
"type": null
},
{
"param": "name",
"type": null
}
] | {
"returns": [
{
"docstring": "A Tensor of the same shape like `images`.",
"docstring_tokens": [
"A",
"Tensor",
"of",
"the",
"same",
"shape",
"like",
"`",
"images",
"`",
"."
],
"type": null
}
],
... |
51096caa6e1480e7e520349f8c43977b51a5c290 | VChristlein/textsegment | utils/tf_image_processing.py | [
"MIT"
] | Python | preprocess | <not_specific> | def preprocess(image, ground_truth, out_size, mean, is_training):
""" Preprocess image and ground truth annotation.
Args:
image: 3-D Tensor of shape (num_rows, num_columns, num_channels) (HWC).
ground_truth: 3-D Tensor of shape (num_rows, num_columns, num_channels)
(HWC).
out_size: Tuple of Int... | Preprocess image and ground truth annotation.
Args:
image: 3-D Tensor of shape (num_rows, num_columns, num_channels) (HWC).
ground_truth: 3-D Tensor of shape (num_rows, num_columns, num_channels)
(HWC).
out_size: Tuple of Int. Output height and width of the preprocessed image.
mean: Python a... | Preprocess image and ground truth annotation. | [
"Preprocess",
"image",
"and",
"ground",
"truth",
"annotation",
"."
] | def preprocess(image, ground_truth, out_size, mean, is_training):
mean = tf.convert_to_tensor(mean, dtype=tf.float32)
image = tf.convert_to_tensor(image)
depth_i = image.shape.as_list()[2]
if ground_truth is not None:
ground_truth = tf.convert_to_tensor(ground_truth)
depth_ground_truth = ground_truth.sh... | [
"def",
"preprocess",
"(",
"image",
",",
"ground_truth",
",",
"out_size",
",",
"mean",
",",
"is_training",
")",
":",
"mean",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"mean",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"image",
"=",
"tf",
".",
"conver... | Preprocess image and ground truth annotation. | [
"Preprocess",
"image",
"and",
"ground",
"truth",
"annotation",
"."
] | [
"\"\"\" Preprocess image and ground truth annotation.\n\n Args:\n image: 3-D Tensor of shape (num_rows, num_columns, num_channels) (HWC).\n ground_truth: 3-D Tensor of shape (num_rows, num_columns, num_channels)\n (HWC).\n out_size: Tuple of Int. Output height and width of the preprocessed image.\n... | [
{
"param": "image",
"type": null
},
{
"param": "ground_truth",
"type": null
},
{
"param": "out_size",
"type": null
},
{
"param": "mean",
"type": null
},
{
"param": "is_training",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "image",
"type": null,
"docstring": "3-D Tensor of shape (num_rows, num_columns, num_channels) (HWC).",
"docstring_tokens": [
"3",
"-",
"D",
"Tensor",
"of",
"shape",
"(",
... |
51096caa6e1480e7e520349f8c43977b51a5c290 | VChristlein/textsegment | utils/tf_image_processing.py | [
"MIT"
] | Python | inv_preprocess | <not_specific> | def inv_preprocess(images, mean, name=None):
""" Transforms the tensor from BGR to RGB and adds the mean. """
with tf.name_scope(name, "InvProprocessImages", [images, mean]):
mean = tf.convert_to_tensor(mean, dtype=tf.float32)
images = bgr_to_rgb(images)
images = images + mean
return images | Transforms the tensor from BGR to RGB and adds the mean. | Transforms the tensor from BGR to RGB and adds the mean. | [
"Transforms",
"the",
"tensor",
"from",
"BGR",
"to",
"RGB",
"and",
"adds",
"the",
"mean",
"."
] | def inv_preprocess(images, mean, name=None):
with tf.name_scope(name, "InvProprocessImages", [images, mean]):
mean = tf.convert_to_tensor(mean, dtype=tf.float32)
images = bgr_to_rgb(images)
images = images + mean
return images | [
"def",
"inv_preprocess",
"(",
"images",
",",
"mean",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"\"InvProprocessImages\"",
",",
"[",
"images",
",",
"mean",
"]",
")",
":",
"mean",
"=",
"tf",
".",
"convert_to_t... | Transforms the tensor from BGR to RGB and adds the mean. | [
"Transforms",
"the",
"tensor",
"from",
"BGR",
"to",
"RGB",
"and",
"adds",
"the",
"mean",
"."
] | [
"\"\"\" Transforms the tensor from BGR to RGB and adds the mean. \"\"\""
] | [
{
"param": "images",
"type": null
},
{
"param": "mean",
"type": null
},
{
"param": "name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "images",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "mean",
"type": null,
"docstring": null,
"docstring_tokens":... |
51096caa6e1480e7e520349f8c43977b51a5c290 | VChristlein/textsegment | utils/tf_image_processing.py | [
"MIT"
] | Python | scale | <not_specific> | def scale(images, out_size=None, scale_factor=1.0, method='NEAREST',
name=None):
""" Scale images to a given size.
`method` can be one of:
* `NEAREST`: Nearest neighbor interpolation
* `BILINEAR`: Bilinear interpolation
Args:
images: 4-D Tensor of shape [batch, height, width, channels] o... | Scale images to a given size.
`method` can be one of:
* `NEAREST`: Nearest neighbor interpolation
* `BILINEAR`: Bilinear interpolation
Args:
images: 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor
of shape [height, width, channels].
out_size: A 1-D int32 Tensor of 2 e... | Scale images to a given size. | [
"Scale",
"images",
"to",
"a",
"given",
"size",
"."
] | def scale(images, out_size=None, scale_factor=1.0, method='NEAREST',
name=None):
with tf.name_scope(name, 'ScaleInput', [images]):
if out_size is None:
shape = images.get_shape().as_list()
if images.get_shape().ndims == 3:
out_size = [int(s * scale_factor) for s in shape[:2]]
e... | [
"def",
"scale",
"(",
"images",
",",
"out_size",
"=",
"None",
",",
"scale_factor",
"=",
"1.0",
",",
"method",
"=",
"'NEAREST'",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'ScaleInput'",
",",
"[",
"images",
... | Scale images to a given size. | [
"Scale",
"images",
"to",
"a",
"given",
"size",
"."
] | [
"\"\"\" Scale images to a given size.\n\n `method` can be one of:\n * `NEAREST`: Nearest neighbor interpolation\n * `BILINEAR`: Bilinear interpolation\n \n Args:\n images: 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor\n of shape [height, width, channels].\n out_size: A 1-D... | [
{
"param": "images",
"type": null
},
{
"param": "out_size",
"type": null
},
{
"param": "scale_factor",
"type": null
},
{
"param": "method",
"type": null
},
{
"param": "name",
"type": null
}
] | {
"returns": [
{
"docstring": "If `image` was 4-D, a 4-D float Tensor of shape\n`[batch, target_height, target_width, channels]`\nIf `image` was 3-D, a 3-D float Tensor of shape\n`[target_height, target_width, channels]`",
"docstring_tokens": [
"If",
"`",
"image",
"`",
... |
51096caa6e1480e7e520349f8c43977b51a5c290 | VChristlein/textsegment | utils/tf_image_processing.py | [
"MIT"
] | Python | map_ground_truth | <not_specific> | def map_ground_truth(ground_truth, palette, one_hot=True, name=None):
""" Maps a ground truth image tensor to a label tensor.
Args:
ground_truth: Rank 3 or 4 tensor: [(batch_size,) height, width, depth].
palette: Color palette with rank [num_classes, palette_depth].
Returns:
If `one_hot` is `True`, ... | Maps a ground truth image tensor to a label tensor.
Args:
ground_truth: Rank 3 or 4 tensor: [(batch_size,) height, width, depth].
palette: Color palette with rank [num_classes, palette_depth].
Returns:
If `one_hot` is `True`, it returns a one hot label of shape
[(batch_size,) height, width, 1... | Maps a ground truth image tensor to a label tensor. | [
"Maps",
"a",
"ground",
"truth",
"image",
"tensor",
"to",
"a",
"label",
"tensor",
"."
] | def map_ground_truth(ground_truth, palette, one_hot=True, name=None):
palette = tf.convert_to_tensor(palette)
with tf.name_scope(name, 'MapGroundTruth', [ground_truth, palette]):
is_batch = True
if len(ground_truth.shape) == 3:
is_batch = False
ground_truth = tf.expand_dims(ground_truth, axis=0)... | [
"def",
"map_ground_truth",
"(",
"ground_truth",
",",
"palette",
",",
"one_hot",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"palette",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"palette",
")",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'Map... | Maps a ground truth image tensor to a label tensor. | [
"Maps",
"a",
"ground",
"truth",
"image",
"tensor",
"to",
"a",
"label",
"tensor",
"."
] | [
"\"\"\" Maps a ground truth image tensor to a label tensor.\n\n Args:\n ground_truth: Rank 3 or 4 tensor: [(batch_size,) height, width, depth].\n palette: Color palette with rank [num_classes, palette_depth].\n\n Returns:\n If `one_hot` is `True`, it returns a one hot label of shape\n [(batch_size... | [
{
"param": "ground_truth",
"type": null
},
{
"param": "palette",
"type": null
},
{
"param": "one_hot",
"type": null
},
{
"param": "name",
"type": null
}
] | {
"returns": [
{
"docstring": "If `one_hot` is `True`, it returns a one hot label of shape\n[(batch_size,) height, width, 1], otherwise it will return a label of\nshape [(batch_size,) height, width, num_clases].",
"docstring_tokens": [
"If",
"`",
"one_hot",
"`",
... |
7d0fd813c7b8f2c2b7e9853c9a1d4ed938dcebc2 | simonpf/quantnn | quantnn/utils.py | [
"MIT"
] | Python | apply | <not_specific> | def apply(f, *args):
"""
Applies a function to sequence values or dicts of values.
Args:
f: The function to apply to ``x`` or all items in ``x``.
*args: Sequence of arguments to be supplied to ``f``. If all arguments
are dicts, the function ``f`` is applied key-wise to all eleme... |
Applies a function to sequence values or dicts of values.
Args:
f: The function to apply to ``x`` or all items in ``x``.
*args: Sequence of arguments to be supplied to ``f``. If all arguments
are dicts, the function ``f`` is applied key-wise to all elements
in the dict.... | Applies a function to sequence values or dicts of values. | [
"Applies",
"a",
"function",
"to",
"sequence",
"values",
"or",
"dicts",
"of",
"values",
"."
] | def apply(f, *args):
if any(isinstance(x, dict) for x in args):
results = {}
d = [x for x in args if isinstance(x, dict)][0]
for k in d:
args_k = [arg[k] if isinstance(arg, dict) else arg
for arg in args]
results[k] = f(*args_k)
return re... | [
"def",
"apply",
"(",
"f",
",",
"*",
"args",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"x",
",",
"dict",
")",
"for",
"x",
"in",
"args",
")",
":",
"results",
"=",
"{",
"}",
"d",
"=",
"[",
"x",
"for",
"x",
"in",
"args",
"if",
"isinstance",
... | Applies a function to sequence values or dicts of values. | [
"Applies",
"a",
"function",
"to",
"sequence",
"values",
"or",
"dicts",
"of",
"values",
"."
] | [
"\"\"\"\n Applies a function to sequence values or dicts of values.\n\n Args:\n f: The function to apply to ``x`` or all items in ``x``.\n *args: Sequence of arguments to be supplied to ``f``. If all arguments\n are dicts, the function ``f`` is applied key-wise to all elements\n ... | [
{
"param": "f",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "f",
"type": null,
"docstring": "The function to apply to ``x`` or all items in ``x``.",
"docstring_tokens": [
"The",
"function",
"to",
"apply",
"to",
"`",
"`",
"x... |
7d0fd813c7b8f2c2b7e9853c9a1d4ed938dcebc2 | simonpf/quantnn | quantnn/utils.py | [
"MIT"
] | Python | serialize_dataset | <not_specific> | def serialize_dataset(dataset):
"""
Writes xarray dataset to a bytestream.
Args:
dataset: A xarray dataset to seraialize.
Returns:
Bytes object containing the dataset as netcdf file.
"""
_, filename = mkstemp()
try:
dataset.to_netcdf(filename)
with open(fi... |
Writes xarray dataset to a bytestream.
Args:
dataset: A xarray dataset to seraialize.
Returns:
Bytes object containing the dataset as netcdf file.
| Writes xarray dataset to a bytestream. | [
"Writes",
"xarray",
"dataset",
"to",
"a",
"bytestream",
"."
] | def serialize_dataset(dataset):
_, filename = mkstemp()
try:
dataset.to_netcdf(filename)
with open(filename, "rb") as file:
buffer = file.read()
finally:
Path(filename).unlink()
return buffer | [
"def",
"serialize_dataset",
"(",
"dataset",
")",
":",
"_",
",",
"filename",
"=",
"mkstemp",
"(",
")",
"try",
":",
"dataset",
".",
"to_netcdf",
"(",
"filename",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"file",
":",
"buffer",
"=",
... | Writes xarray dataset to a bytestream. | [
"Writes",
"xarray",
"dataset",
"to",
"a",
"bytestream",
"."
] | [
"\"\"\"\n Writes xarray dataset to a bytestream.\n\n Args:\n dataset: A xarray dataset to seraialize.\n\n Returns:\n Bytes object containing the dataset as netcdf file.\n \"\"\""
] | [
{
"param": "dataset",
"type": null
}
] | {
"returns": [
{
"docstring": "Bytes object containing the dataset as netcdf file.",
"docstring_tokens": [
"Bytes",
"object",
"containing",
"the",
"dataset",
"as",
"netcdf",
"file",
"."
],
"type": null
}
],
"ra... |
7d0fd813c7b8f2c2b7e9853c9a1d4ed938dcebc2 | simonpf/quantnn | quantnn/utils.py | [
"MIT"
] | Python | deserialize_dataset | <not_specific> | def deserialize_dataset(data):
"""
Read xarray dataset from byte stream containing the
dataset in NetCDF format.
Args:
data: The bytes object containing the binary data of the
NetCDf file.
Returns:
The deserialized xarray dataset.
"""
_, filename = mkstemp()
... |
Read xarray dataset from byte stream containing the
dataset in NetCDF format.
Args:
data: The bytes object containing the binary data of the
NetCDf file.
Returns:
The deserialized xarray dataset.
| Read xarray dataset from byte stream containing the
dataset in NetCDF format. | [
"Read",
"xarray",
"dataset",
"from",
"byte",
"stream",
"containing",
"the",
"dataset",
"in",
"NetCDF",
"format",
"."
] | def deserialize_dataset(data):
_, filename = mkstemp()
try:
with open(filename, "wb") as file:
buffer = file.write(data)
dataset = xr.load_dataset(filename, engine="netcdf4")
finally:
Path(filename).unlink()
return dataset | [
"def",
"deserialize_dataset",
"(",
"data",
")",
":",
"_",
",",
"filename",
"=",
"mkstemp",
"(",
")",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"file",
":",
"buffer",
"=",
"file",
".",
"write",
"(",
"data",
")",
"dataset",... | Read xarray dataset from byte stream containing the
dataset in NetCDF format. | [
"Read",
"xarray",
"dataset",
"from",
"byte",
"stream",
"containing",
"the",
"dataset",
"in",
"NetCDF",
"format",
"."
] | [
"\"\"\"\n Read xarray dataset from byte stream containing the\n dataset in NetCDF format.\n\n Args:\n data: The bytes object containing the binary data of the\n NetCDf file.\n\n Returns:\n The deserialized xarray dataset.\n \"\"\""
] | [
{
"param": "data",
"type": null
}
] | {
"returns": [
{
"docstring": "The deserialized xarray dataset.",
"docstring_tokens": [
"The",
"deserialized",
"xarray",
"dataset",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
... |
6d107efb43fd16d7747946cefa74b94810ccaf77 | simonpf/quantnn | quantnn/data.py | [
"MIT"
] | Python | run | null | def run(self):
"""
Open dataset and start loading batches.
"""
super().run()
while True:
filename = self.task_queue.get()
if filename is None:
break
try:
dataset = self.factory(filename, *self.args, **self.kwa... |
Open dataset and start loading batches.
| Open dataset and start loading batches. | [
"Open",
"dataset",
"and",
"start",
"loading",
"batches",
"."
] | def run(self):
super().run()
while True:
filename = self.task_queue.get()
if filename is None:
break
try:
dataset = self.factory(filename, *self.args, **self.kwargs)
if isinstance(dataset, Iterable):
... | [
"def",
"run",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"run",
"(",
")",
"while",
"True",
":",
"filename",
"=",
"self",
".",
"task_queue",
".",
"get",
"(",
")",
"if",
"filename",
"is",
"None",
":",
"break",
"try",
":",
"dataset",
"=",
"self"... | Open dataset and start loading batches. | [
"Open",
"dataset",
"and",
"start",
"loading",
"batches",
"."
] | [
"\"\"\"\n Open dataset and start loading batches.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6d107efb43fd16d7747946cefa74b94810ccaf77 | simonpf/quantnn | quantnn/data.py | [
"MIT"
] | Python | epoch_done | <not_specific> | def epoch_done(self):
"""
Boolean indicating whether the manager has finished processing the
current epoch.
"""
return self.done_flag.is_set() |
Boolean indicating whether the manager has finished processing the
current epoch.
| Boolean indicating whether the manager has finished processing the
current epoch. | [
"Boolean",
"indicating",
"whether",
"the",
"manager",
"has",
"finished",
"processing",
"the",
"current",
"epoch",
"."
] | def epoch_done(self):
return self.done_flag.is_set() | [
"def",
"epoch_done",
"(",
"self",
")",
":",
"return",
"self",
".",
"done_flag",
".",
"is_set",
"(",
")"
] | Boolean indicating whether the manager has finished processing the
current epoch. | [
"Boolean",
"indicating",
"whether",
"the",
"manager",
"has",
"finished",
"processing",
"the",
"current",
"epoch",
"."
] | [
"\"\"\"\n Boolean indicating whether the manager has finished processing the\n current epoch.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6d107efb43fd16d7747946cefa74b94810ccaf77 | simonpf/quantnn | quantnn/data.py | [
"MIT"
] | Python | run | null | def run(self):
"""
Collects batches from child process and puts them on the batch
queue.
"""
super().run()
while True:
batches = []
# Collect batches from workers.
while (self.done_queue.qsize() < len(self.files)):
for... |
Collects batches from child process and puts them on the batch
queue.
| Collects batches from child process and puts them on the batch
queue. | [
"Collects",
"batches",
"from",
"child",
"process",
"and",
"puts",
"them",
"on",
"the",
"batch",
"queue",
"."
] | def run(self):
super().run()
while True:
batches = []
while (self.done_queue.qsize() < len(self.files)):
for i in range(2):
batch_queue = self.batch_queues[i]
while batch_queue.qsize():
try:
... | [
"def",
"run",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"run",
"(",
")",
"while",
"True",
":",
"batches",
"=",
"[",
"]",
"while",
"(",
"self",
".",
"done_queue",
".",
"qsize",
"(",
")",
"<",
"len",
"(",
"self",
".",
"files",
")",
")",
":... | Collects batches from child process and puts them on the batch
queue. | [
"Collects",
"batches",
"from",
"child",
"process",
"and",
"puts",
"them",
"on",
"the",
"batch",
"queue",
"."
] | [
"\"\"\"\n Collects batches from child process and puts them on the batch\n queue.\n \"\"\"",
"# Collect batches from workers.",
"# Process remaining batches."
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6d107efb43fd16d7747946cefa74b94810ccaf77 | simonpf/quantnn | quantnn/data.py | [
"MIT"
] | Python | next_epoch | null | def next_epoch(self):
"""
Sends signal to manager to start loading of next epoch.
"""
# Empty done queue.
while not self.done_queue.empty():
self.done_queue.get()
files = []
files = list(self._rng.permutation(self.files))
for f in files:
... |
Sends signal to manager to start loading of next epoch.
| Sends signal to manager to start loading of next epoch. | [
"Sends",
"signal",
"to",
"manager",
"to",
"start",
"loading",
"of",
"next",
"epoch",
"."
] | def next_epoch(self):
while not self.done_queue.empty():
self.done_queue.get()
files = []
files = list(self._rng.permutation(self.files))
for f in files:
self.task_queue.put(f)
self.done_flag.clear() | [
"def",
"next_epoch",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"done_queue",
".",
"empty",
"(",
")",
":",
"self",
".",
"done_queue",
".",
"get",
"(",
")",
"files",
"=",
"[",
"]",
"files",
"=",
"list",
"(",
"self",
".",
"_rng",
".",
"per... | Sends signal to manager to start loading of next epoch. | [
"Sends",
"signal",
"to",
"manager",
"to",
"start",
"loading",
"of",
"next",
"epoch",
"."
] | [
"\"\"\"\n Sends signal to manager to start loading of next epoch.\n \"\"\"",
"# Empty done queue."
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | _get_backend_module | <not_specific> | def _get_backend_module(name):
"""
Return module object corresponding to given backend.
Args:
The name of the backend.
Return:
The corresponding module object.
"""
if name == "numpy":
import numpy as np
return np
if name == "numpy.ma":
import numpy as... |
Return module object corresponding to given backend.
Args:
The name of the backend.
Return:
The corresponding module object.
| Return module object corresponding to given backend.
Args:
The name of the backend.
The corresponding module object. | [
"Return",
"module",
"object",
"corresponding",
"to",
"given",
"backend",
".",
"Args",
":",
"The",
"name",
"of",
"the",
"backend",
".",
"The",
"corresponding",
"module",
"object",
"."
] | def _get_backend_module(name):
if name == "numpy":
import numpy as np
return np
if name == "numpy.ma":
import numpy as np
return np.ma
if name == "torch":
import torch
return torch
if name == "jax":
import jax
import jax.numpy as jnp
... | [
"def",
"_get_backend_module",
"(",
"name",
")",
":",
"if",
"name",
"==",
"\"numpy\"",
":",
"import",
"numpy",
"as",
"np",
"return",
"np",
"if",
"name",
"==",
"\"numpy.ma\"",
":",
"import",
"numpy",
"as",
"np",
"return",
"np",
".",
"ma",
"if",
"name",
"... | Return module object corresponding to given backend. | [
"Return",
"module",
"object",
"corresponding",
"to",
"given",
"backend",
"."
] | [
"\"\"\"\n Return module object corresponding to given backend.\n\n Args:\n The name of the backend.\n\n Return:\n The corresponding module object.\n \"\"\""
] | [
{
"param": "name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | to_array | <not_specific> | def to_array(module, array, like=None):
"""
Turn a list into an array.
Args:
module: Module representing the module which should be used as
backend.
array: Iterable to turn into array.
Returns:
Array-object corresponding to the given backend module containing the... |
Turn a list into an array.
Args:
module: Module representing the module which should be used as
backend.
array: Iterable to turn into array.
Returns:
Array-object corresponding to the given backend module containing the
data in array.
| Turn a list into an array. | [
"Turn",
"a",
"list",
"into",
"an",
"array",
"."
] | def to_array(module, array, like=None):
_import_modules()
if module in [np, ma]:
if like is not None:
return module.asarray(array, dtype=like.dtype)
else:
return module.asarray(array)
elif module == torch:
if isinstance(array, torch.Tensor):
if lik... | [
"def",
"to_array",
"(",
"module",
",",
"array",
",",
"like",
"=",
"None",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
"]",
":",
"if",
"like",
"is",
"not",
"None",
":",
"return",
"module",
".",
"asarray",
"(",
... | Turn a list into an array. | [
"Turn",
"a",
"list",
"into",
"an",
"array",
"."
] | [
"\"\"\"\n Turn a list into an array.\n\n Args:\n module: Module representing the module which should be used as\n backend.\n array: Iterable to turn into array.\n\n Returns:\n Array-object corresponding to the given backend module containing the\n data in array.\n ... | [
{
"param": "module",
"type": null
},
{
"param": "array",
"type": null
},
{
"param": "like",
"type": null
}
] | {
"returns": [
{
"docstring": "Array-object corresponding to the given backend module containing the\ndata in array.",
"docstring_tokens": [
"Array",
"-",
"object",
"corresponding",
"to",
"the",
"given",
"backend",
"module",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | sample_uniform | <not_specific> | def sample_uniform(module, shape, like=None):
"""
Create a tensor with random values sampled from a uniform distribution.
Args:
module: Module representing the module which should be used as
backend.
shape: Iterable describing the shape of tensor.
Returns:
Array... |
Create a tensor with random values sampled from a uniform distribution.
Args:
module: Module representing the module which should be used as
backend.
shape: Iterable describing the shape of tensor.
Returns:
Array object corresponding to the given module object cont... | Create a tensor with random values sampled from a uniform distribution. | [
"Create",
"a",
"tensor",
"with",
"random",
"values",
"sampled",
"from",
"a",
"uniform",
"distribution",
"."
] | def sample_uniform(module, shape, like=None):
_import_modules()
if module in [np, ma]:
return module.random.rand(*shape)
elif module == torch:
return module.rand(shape)
elif module == jnp:
return jax.random.uniform(_JAX_KEY, shape)
elif module == tf:
return tf.random.... | [
"def",
"sample_uniform",
"(",
"module",
",",
"shape",
",",
"like",
"=",
"None",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
"]",
":",
"return",
"module",
".",
"random",
".",
"rand",
"(",
"*",
"shape",
")",
"el... | Create a tensor with random values sampled from a uniform distribution. | [
"Create",
"a",
"tensor",
"with",
"random",
"values",
"sampled",
"from",
"a",
"uniform",
"distribution",
"."
] | [
"\"\"\"\n Create a tensor with random values sampled from a uniform distribution.\n\n Args:\n module: Module representing the module which should be used as\n backend.\n shape: Iterable describing the shape of tensor.\n\n Returns:\n Array object corresponding to the give... | [
{
"param": "module",
"type": null
},
{
"param": "shape",
"type": null
},
{
"param": "like",
"type": null
}
] | {
"returns": [
{
"docstring": "Array object corresponding to the given module object containing\nrandom values.",
"docstring_tokens": [
"Array",
"object",
"corresponding",
"to",
"the",
"given",
"module",
"object",
"containing",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | sample_gaussian | <not_specific> | def sample_gaussian(module, shape):
"""
Create a tensor with random values sampled from a Gaussian distribution.
Args:
module: Module representing the module which should be used as
backend.
shape: Iterable describing the shape of tensor.
Returns:
Array object c... |
Create a tensor with random values sampled from a Gaussian distribution.
Args:
module: Module representing the module which should be used as
backend.
shape: Iterable describing the shape of tensor.
Returns:
Array object corresponding to the given module object con... | Create a tensor with random values sampled from a Gaussian distribution. | [
"Create",
"a",
"tensor",
"with",
"random",
"values",
"sampled",
"from",
"a",
"Gaussian",
"distribution",
"."
] | def sample_gaussian(module, shape):
_import_modules()
if module in [np, ma]:
return module.random.randn(*shape)
elif module == torch:
return module.randn(*shape)
elif module == jnp:
return jax.random.normal(_JAX_KEY, shape)
elif module == tf:
return tf.random.normal(s... | [
"def",
"sample_gaussian",
"(",
"module",
",",
"shape",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
"]",
":",
"return",
"module",
".",
"random",
".",
"randn",
"(",
"*",
"shape",
")",
"elif",
"module",
"==",
"torc... | Create a tensor with random values sampled from a Gaussian distribution. | [
"Create",
"a",
"tensor",
"with",
"random",
"values",
"sampled",
"from",
"a",
"Gaussian",
"distribution",
"."
] | [
"\"\"\"\n Create a tensor with random values sampled from a Gaussian distribution.\n\n Args:\n module: Module representing the module which should be used as\n backend.\n shape: Iterable describing the shape of tensor.\n\n Returns:\n Array object corresponding to the giv... | [
{
"param": "module",
"type": null
},
{
"param": "shape",
"type": null
}
] | {
"returns": [
{
"docstring": "Array object corresponding to the given module object containing\nrandom values.",
"docstring_tokens": [
"Array",
"object",
"corresponding",
"to",
"the",
"given",
"module",
"object",
"containing",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | numel | <not_specific> | def numel(array):
"""
Returns the number of elements in an array.
Args:
module: Module representing the module which should be used as
backend.
shape: Iterable describing the shape of tensor.
Returns:
Array object corresponding to the given module object contain... |
Returns the number of elements in an array.
Args:
module: Module representing the module which should be used as
backend.
shape: Iterable describing the shape of tensor.
Returns:
Array object corresponding to the given module object containing
random value... | Returns the number of elements in an array. | [
"Returns",
"the",
"number",
"of",
"elements",
"in",
"an",
"array",
"."
] | def numel(array):
_import_modules()
module_name = type(array).__module__.split(".")[0]
if module_name in ["numpy", "numpy.ma.core"]:
return array.size
elif module_name == "torch":
return array.numel()
elif module_name.split(".")[0] == "jax":
return array.size
elif module_... | [
"def",
"numel",
"(",
"array",
")",
":",
"_import_modules",
"(",
")",
"module_name",
"=",
"type",
"(",
"array",
")",
".",
"__module__",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"if",
"module_name",
"in",
"[",
"\"numpy\"",
",",
"\"numpy.ma.core\"",
... | Returns the number of elements in an array. | [
"Returns",
"the",
"number",
"of",
"elements",
"in",
"an",
"array",
"."
] | [
"\"\"\"\n Returns the number of elements in an array.\n\n Args:\n module: Module representing the module which should be used as\n backend.\n shape: Iterable describing the shape of tensor.\n\n Returns:\n Array object corresponding to the given module object containing\n... | [
{
"param": "array",
"type": null
}
] | {
"returns": [
{
"docstring": "Array object corresponding to the given module object containing\nrandom values.",
"docstring_tokens": [
"Array",
"object",
"corresponding",
"to",
"the",
"given",
"module",
"object",
"containing",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | concatenate | <not_specific> | def concatenate(module, arrays, dimension):
"""
Concatenate array along given dimension.
Args:
module: Module object corresponding to the arrays.
arrays: List of arrays to concatenate.
dimension: Index of the dimensions along which to concatenate.
Return:
The array resu... |
Concatenate array along given dimension.
Args:
module: Module object corresponding to the arrays.
arrays: List of arrays to concatenate.
dimension: Index of the dimensions along which to concatenate.
Return:
The array resulting from concatenating the given arrays along
... | Concatenate array along given dimension. | [
"Concatenate",
"array",
"along",
"given",
"dimension",
"."
] | def concatenate(module, arrays, dimension):
_import_modules()
if module in [np, ma, jnp]:
return module.concatenate(arrays, dimension)
elif module == torch:
return module.cat(arrays, dimension)
elif module == tf:
return tf.concat(arrays, axis=dimension)
return UnknownModuleEx... | [
"def",
"concatenate",
"(",
"module",
",",
"arrays",
",",
"dimension",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
",",
"jnp",
"]",
":",
"return",
"module",
".",
"concatenate",
"(",
"arrays",
",",
"dimension",
")",... | Concatenate array along given dimension. | [
"Concatenate",
"array",
"along",
"given",
"dimension",
"."
] | [
"\"\"\"\n Concatenate array along given dimension.\n\n Args:\n module: Module object corresponding to the arrays.\n arrays: List of arrays to concatenate.\n dimension: Index of the dimensions along which to concatenate.\n\n Return:\n The array resulting from concatenating the gi... | [
{
"param": "module",
"type": null
},
{
"param": "arrays",
"type": null
},
{
"param": "dimension",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "Module object corresponding to the arrays.",
"docstring_tokens": [
"Module",
"object",
"corresponding",
"to",
"the",
"arrays",
"."
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | expand_dims | <not_specific> | def expand_dims(module, array, dimension):
"""
Expand tensor dimension along given axis.
Inserts a dimension of length one at a given index of the
dimension array.
Args:
module: Module object corresponding to the arrays.
array: The array whose dimension to expand.
dimension... |
Expand tensor dimension along given axis.
Inserts a dimension of length one at a given index of the
dimension array.
Args:
module: Module object corresponding to the arrays.
array: The array whose dimension to expand.
dimension: The index at which to insert the new
... | Expand tensor dimension along given axis.
Inserts a dimension of length one at a given index of the
dimension array. | [
"Expand",
"tensor",
"dimension",
"along",
"given",
"axis",
".",
"Inserts",
"a",
"dimension",
"of",
"length",
"one",
"at",
"a",
"given",
"index",
"of",
"the",
"dimension",
"array",
"."
] | def expand_dims(module, array, dimension):
_import_modules()
if module in [np, ma, jnp, tf]:
return module.expand_dims(array, dimension)
elif module == torch:
return module.unsqueeze(array, dimension)
raise UnknownModuleException(f"Module {module.__name__} not supported.") | [
"def",
"expand_dims",
"(",
"module",
",",
"array",
",",
"dimension",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
",",
"jnp",
",",
"tf",
"]",
":",
"return",
"module",
".",
"expand_dims",
"(",
"array",
",",
"dimen... | Expand tensor dimension along given axis. | [
"Expand",
"tensor",
"dimension",
"along",
"given",
"axis",
"."
] | [
"\"\"\"\n Expand tensor dimension along given axis.\n\n Inserts a dimension of length one at a given index of the\n dimension array.\n\n Args:\n module: Module object corresponding to the arrays.\n array: The array whose dimension to expand.\n dimension: The index at which to insert... | [
{
"param": "module",
"type": null
},
{
"param": "array",
"type": null
},
{
"param": "dimension",
"type": null
}
] | {
"returns": [
{
"docstring": "The reshaped array with a dimension added at the given index.",
"docstring_tokens": [
"The",
"reshaped",
"array",
"with",
"a",
"dimension",
"added",
"at",
"the",
"given",
"index",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | pad_zeros | <not_specific> | def pad_zeros(module, array, n, dimension):
"""
Pads array with 0s along given dimension.
Args:
module: Module object corresponding to the arrays.
array: The array to pad.
n: The number of zeros to add to each edge.
dimension: Along which dimension to add zeros.
Returns... |
Pads array with 0s along given dimension.
Args:
module: Module object corresponding to the arrays.
array: The array to pad.
n: The number of zeros to add to each edge.
dimension: Along which dimension to add zeros.
Returns:
A new array with the given number of 0s a... | Pads array with 0s along given dimension. | [
"Pads",
"array",
"with",
"0s",
"along",
"given",
"dimension",
"."
] | def pad_zeros(module, array, n, dimension):
_import_modules()
if module in [np, ma, jnp, tf]:
n_dims = len(array.shape)
pad = [(0, 0)] * n_dims
pad[dimension] = (n, n)
return module.pad(array, pad, mode="constant", constant_values=0.0)
elif module == torch:
n_dims = l... | [
"def",
"pad_zeros",
"(",
"module",
",",
"array",
",",
"n",
",",
"dimension",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
",",
"jnp",
",",
"tf",
"]",
":",
"n_dims",
"=",
"len",
"(",
"array",
".",
"shape",
")"... | Pads array with 0s along given dimension. | [
"Pads",
"array",
"with",
"0s",
"along",
"given",
"dimension",
"."
] | [
"\"\"\"\n Pads array with 0s along given dimension.\n\n Args:\n module: Module object corresponding to the arrays.\n array: The array to pad.\n n: The number of zeros to add to each edge.\n dimension: Along which dimension to add zeros.\n\n Returns:\n A new array with the... | [
{
"param": "module",
"type": null
},
{
"param": "array",
"type": null
},
{
"param": "n",
"type": null
},
{
"param": "dimension",
"type": null
}
] | {
"returns": [
{
"docstring": "A new array with the given number of 0s added to\neach edge along the given dimension.",
"docstring_tokens": [
"A",
"new",
"array",
"with",
"the",
"given",
"number",
"of",
"0s",
"added",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | pad_zeros_left | <not_specific> | def pad_zeros_left(module, array, n, dimension):
"""
Pads array with 0s along given dimension but only on left side.
Args:
module: Module object corresponding to the arrays.
array: The array to pad.
n: The number of zeros to add to each edge.
dimension: Along which dimension... |
Pads array with 0s along given dimension but only on left side.
Args:
module: Module object corresponding to the arrays.
array: The array to pad.
n: The number of zeros to add to each edge.
dimension: Along which dimension to add zeros.
Returns:
A new array with th... | Pads array with 0s along given dimension but only on left side. | [
"Pads",
"array",
"with",
"0s",
"along",
"given",
"dimension",
"but",
"only",
"on",
"left",
"side",
"."
] | def pad_zeros_left(module, array, n, dimension):
_import_modules()
if module in [np, ma, jnp, tf]:
n_dims = len(array.shape)
pad = [(0, 0)] * n_dims
pad[dimension] = (n, 0)
return module.pad(array, pad, mode="constant", constant_values=0.0)
elif module == torch:
n_dim... | [
"def",
"pad_zeros_left",
"(",
"module",
",",
"array",
",",
"n",
",",
"dimension",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
",",
"jnp",
",",
"tf",
"]",
":",
"n_dims",
"=",
"len",
"(",
"array",
".",
"shape",
... | Pads array with 0s along given dimension but only on left side. | [
"Pads",
"array",
"with",
"0s",
"along",
"given",
"dimension",
"but",
"only",
"on",
"left",
"side",
"."
] | [
"\"\"\"\n Pads array with 0s along given dimension but only on left side.\n\n Args:\n module: Module object corresponding to the arrays.\n array: The array to pad.\n n: The number of zeros to add to each edge.\n dimension: Along which dimension to add zeros.\n\n Returns:\n ... | [
{
"param": "module",
"type": null
},
{
"param": "array",
"type": null
},
{
"param": "n",
"type": null
},
{
"param": "dimension",
"type": null
}
] | {
"returns": [
{
"docstring": "A new array with the given number of 0s added to\nonly the left edge along the given dimension.",
"docstring_tokens": [
"A",
"new",
"array",
"with",
"the",
"given",
"number",
"of",
"0s",
"add... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | arange | <not_specific> | def arange(module, start, end, step):
"""
Crate array with stepped sequence of values.
Arguments:
module: The backend array corresponding to the given array.
start: Start value of the sequence.
end: Maximum value of the sequence.
step: Step size.
Return:
1D arra... |
Crate array with stepped sequence of values.
Arguments:
module: The backend array corresponding to the given array.
start: Start value of the sequence.
end: Maximum value of the sequence.
step: Step size.
Return:
1D array containing the sequence starting with the g... | Crate array with stepped sequence of values. | [
"Crate",
"array",
"with",
"stepped",
"sequence",
"of",
"values",
"."
] | def arange(module, start, end, step):
_import_modules()
if module in [np, ma, jnp]:
return module.arange(start, end, step)
elif module == torch:
return module.arange(start, end, step, dtype=torch.float)
elif module == tf:
return tf.range(start, end, step)
raise UnknownModuleE... | [
"def",
"arange",
"(",
"module",
",",
"start",
",",
"end",
",",
"step",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
",",
"jnp",
"]",
":",
"return",
"module",
".",
"arange",
"(",
"start",
",",
"end",
",",
"ste... | Crate array with stepped sequence of values. | [
"Crate",
"array",
"with",
"stepped",
"sequence",
"of",
"values",
"."
] | [
"\"\"\"\n Crate array with stepped sequence of values.\n\n Arguments:\n module: The backend array corresponding to the given array.\n start: Start value of the sequence.\n end: Maximum value of the sequence.\n step: Step size.\n\n Return:\n 1D array containing the sequenc... | [
{
"param": "module",
"type": null
},
{
"param": "start",
"type": null
},
{
"param": "end",
"type": null
},
{
"param": "step",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | reshape | <not_specific> | def reshape(module, array, shape):
"""
Reshape array into given shape.
Arguments:
module: The backend array corresponding to the given array.
array: The array to reshape
shape: The shape into which to rehshape the array.
Returns:
The array reshaped into the requested sh... |
Reshape array into given shape.
Arguments:
module: The backend array corresponding to the given array.
array: The array to reshape
shape: The shape into which to rehshape the array.
Returns:
The array reshaped into the requested shape.
| Reshape array into given shape. | [
"Reshape",
"array",
"into",
"given",
"shape",
"."
] | def reshape(module, array, shape):
_import_modules()
if module in [np, ma, torch, jnp]:
return array.reshape(shape)
if module == tf:
return tf.reshape(array, shape)
raise UnknownModuleException(f"Module {module.__name__} not supported.") | [
"def",
"reshape",
"(",
"module",
",",
"array",
",",
"shape",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
",",
"torch",
",",
"jnp",
"]",
":",
"return",
"array",
".",
"reshape",
"(",
"shape",
")",
"if",
"module"... | Reshape array into given shape. | [
"Reshape",
"array",
"into",
"given",
"shape",
"."
] | [
"\"\"\"\n Reshape array into given shape.\n\n Arguments:\n module: The backend array corresponding to the given array.\n array: The array to reshape\n shape: The shape into which to rehshape the array.\n\n Returns:\n The array reshaped into the requested shape.\n \"\"\""
] | [
{
"param": "module",
"type": null
},
{
"param": "array",
"type": null
},
{
"param": "shape",
"type": null
}
] | {
"returns": [
{
"docstring": "The array reshaped into the requested shape.",
"docstring_tokens": [
"The",
"array",
"reshaped",
"into",
"the",
"requested",
"shape",
"."
],
"type": null
}
],
"raises": [],
"params": [
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | _trapz | <not_specific> | def _trapz(module, y, x, dimension):
"""
Numeric integration using trapezoidal rule.
Arguments:
module: The backend array corresponding to the given array.
y: Rank k-tensor to integrate over the given dimension.
x: The domain values to integrate over.
dimension: The dimensi... |
Numeric integration using trapezoidal rule.
Arguments:
module: The backend array corresponding to the given array.
y: Rank k-tensor to integrate over the given dimension.
x: The domain values to integrate over.
dimension: The dimension to integrate over.
Return:
Th... | Numeric integration using trapezoidal rule. | [
"Numeric",
"integration",
"using",
"trapezoidal",
"rule",
"."
] | def _trapz(module, y, x, dimension):
n = len(y.shape)
x_shape = [1] * n
x_shape[dimension] = -1
x = reshape(module, x, x_shape)
selection = [slice(0, None)] * n
selection_l = selection[:]
selection_l[dimension] = slice(0, -1)
selection_r = selection[:]
selection_r[dimension] = slice(... | [
"def",
"_trapz",
"(",
"module",
",",
"y",
",",
"x",
",",
"dimension",
")",
":",
"n",
"=",
"len",
"(",
"y",
".",
"shape",
")",
"x_shape",
"=",
"[",
"1",
"]",
"*",
"n",
"x_shape",
"[",
"dimension",
"]",
"=",
"-",
"1",
"x",
"=",
"reshape",
"(",
... | Numeric integration using trapezoidal rule. | [
"Numeric",
"integration",
"using",
"trapezoidal",
"rule",
"."
] | [
"\"\"\"\n Numeric integration using trapezoidal rule.\n\n Arguments:\n module: The backend array corresponding to the given array.\n y: Rank k-tensor to integrate over the given dimension.\n x: The domain values to integrate over.\n dimension: The dimension to integrate over.\n\n ... | [
{
"param": "module",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "dimension",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | trapz | <not_specific> | def trapz(module, y, x, dimension):
"""
Numeric integration using trapezoidal rule.
Arguments:
module: The backend array corresponding to the given array.
y: Rank k-tensor to integrate over the given dimension.
x: The domain values to integrate over.
dimension: The dimensio... |
Numeric integration using trapezoidal rule.
Arguments:
module: The backend array corresponding to the given array.
y: Rank k-tensor to integrate over the given dimension.
x: The domain values to integrate over.
dimension: The dimension to integrate over.
Return:
Th... | Numeric integration using trapezoidal rule. | [
"Numeric",
"integration",
"using",
"trapezoidal",
"rule",
"."
] | def trapz(module, y, x, dimension):
if len(x) == y.shape[dimension] + 1:
dx = x[1:] - x[:-1]
n = len(y.shape)
dx_shape = [1] * n
dx_shape[dimension] = -1
dx = reshape(module, dx, dx_shape)
return module.sum(y * dx, dimension)
if module in [np, ma, torch, jnp]:
... | [
"def",
"trapz",
"(",
"module",
",",
"y",
",",
"x",
",",
"dimension",
")",
":",
"if",
"len",
"(",
"x",
")",
"==",
"y",
".",
"shape",
"[",
"dimension",
"]",
"+",
"1",
":",
"dx",
"=",
"x",
"[",
"1",
":",
"]",
"-",
"x",
"[",
":",
"-",
"1",
... | Numeric integration using trapezoidal rule. | [
"Numeric",
"integration",
"using",
"trapezoidal",
"rule",
"."
] | [
"\"\"\"\n Numeric integration using trapezoidal rule.\n\n Arguments:\n module: The backend array corresponding to the given array.\n y: Rank k-tensor to integrate over the given dimension.\n x: The domain values to integrate over.\n dimension: The dimension to integrate over.\n\n ... | [
{
"param": "module",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "dimension",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | cumsum | <not_specific> | def cumsum(module, y, dimension):
"""
Cumulative sum along given axis.
Arguments:
module: The backend array corresponding to the given array.
y: Rank k-tensor to accumulate along given dimension.
dimension: The dimension to sum over.
Return:
The rank k tensor containing ... |
Cumulative sum along given axis.
Arguments:
module: The backend array corresponding to the given array.
y: Rank k-tensor to accumulate along given dimension.
dimension: The dimension to sum over.
Return:
The rank k tensor containing the cumulative sum along the given dimens... | Cumulative sum along given axis. | [
"Cumulative",
"sum",
"along",
"given",
"axis",
"."
] | def cumsum(module, y, dimension):
_import_modules()
if module in [np, ma, torch, jnp]:
return module.cumsum(y, axis=dimension)
elif module == tf:
return tf.math.cumsum(y, dimension) | [
"def",
"cumsum",
"(",
"module",
",",
"y",
",",
"dimension",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
",",
"torch",
",",
"jnp",
"]",
":",
"return",
"module",
".",
"cumsum",
"(",
"y",
",",
"axis",
"=",
"dim... | Cumulative sum along given axis. | [
"Cumulative",
"sum",
"along",
"given",
"axis",
"."
] | [
"\"\"\"\n Cumulative sum along given axis.\n\n Arguments:\n module: The backend array corresponding to the given array.\n y: Rank k-tensor to accumulate along given dimension.\n dimension: The dimension to sum over.\n\n Return:\n The rank k tensor containing the cumulative sum al... | [
{
"param": "module",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "dimension",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | cumtrapz | <not_specific> | def cumtrapz(module, y, x, dimension):
"""
Cumulative integral along given axis.
The returned tensor has the same shape as the input tensor y and the
values correspond to the numeric integral computed up to the corresponding
value of the provided x vector assuming that the function described by y
... |
Cumulative integral along given axis.
The returned tensor has the same shape as the input tensor y and the
values correspond to the numeric integral computed up to the corresponding
value of the provided x vector assuming that the function described by y
is 0 outside of the domain described by x.
... | Cumulative integral along given axis.
The returned tensor has the same shape as the input tensor y and the
values correspond to the numeric integral computed up to the corresponding
value of the provided x vector assuming that the function described by y
is 0 outside of the domain described by x. | [
"Cumulative",
"integral",
"along",
"given",
"axis",
".",
"The",
"returned",
"tensor",
"has",
"the",
"same",
"shape",
"as",
"the",
"input",
"tensor",
"y",
"and",
"the",
"values",
"correspond",
"to",
"the",
"numeric",
"integral",
"computed",
"up",
"to",
"the",... | def cumtrapz(module, y, x, dimension):
n = len(y.shape)
if len(x.shape) < n:
x_shape = [1] * n
x_shape[dimension] = -1
x = reshape(module, x, x_shape)
selection = [slice(0, None)] * n
selection_l = selection[:]
selection_l[dimension] = slice(0, -1)
selection_l = tuple(sel... | [
"def",
"cumtrapz",
"(",
"module",
",",
"y",
",",
"x",
",",
"dimension",
")",
":",
"n",
"=",
"len",
"(",
"y",
".",
"shape",
")",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"<",
"n",
":",
"x_shape",
"=",
"[",
"1",
"]",
"*",
"n",
"x_shape",
"["... | Cumulative integral along given axis. | [
"Cumulative",
"integral",
"along",
"given",
"axis",
"."
] | [
"\"\"\"\n Cumulative integral along given axis.\n\n The returned tensor has the same shape as the input tensor y and the\n values correspond to the numeric integral computed up to the corresponding\n value of the provided x vector assuming that the function described by y\n is 0 outside of the domain... | [
{
"param": "module",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "dimension",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | zeros | <not_specific> | def zeros(module, shape, like=None):
"""
Zero tensor of given shape.
Arguments:
module: The backend array corresponding to the given array.
shape: Tuple defining the desired shape of the tensor to create.
like: Optional tensor to use to determine additional properties
su... |
Zero tensor of given shape.
Arguments:
module: The backend array corresponding to the given array.
shape: Tuple defining the desired shape of the tensor to create.
like: Optional tensor to use to determine additional properties
such as data type, device, etc ...
Return... | Zero tensor of given shape. | [
"Zero",
"tensor",
"of",
"given",
"shape",
"."
] | def zeros(module, shape, like=None):
_import_modules()
if module in [np, ma]:
if like is not None:
return module.zeros(shape, dtype=like.dtype)
else:
return module.zeros(shape)
elif module == torch:
if like is not None:
return module.zeros(shape, d... | [
"def",
"zeros",
"(",
"module",
",",
"shape",
",",
"like",
"=",
"None",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
"]",
":",
"if",
"like",
"is",
"not",
"None",
":",
"return",
"module",
".",
"zeros",
"(",
"sh... | Zero tensor of given shape. | [
"Zero",
"tensor",
"of",
"given",
"shape",
"."
] | [
"\"\"\"\n Zero tensor of given shape.\n\n Arguments:\n module: The backend array corresponding to the given array.\n shape: Tuple defining the desired shape of the tensor to create.\n like: Optional tensor to use to determine additional properties\n such as data type, device, e... | [
{
"param": "module",
"type": null
},
{
"param": "shape",
"type": null
},
{
"param": "like",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | ones | <not_specific> | def ones(module, shape, like=None):
"""
One tensor of given shape.
Arguments:
module: The backend array corresponding to the given array.
shape: Tuple defining the desired shape of the tensor to create.
like: Optional tensor to use to determine additional properties
such... |
One tensor of given shape.
Arguments:
module: The backend array corresponding to the given array.
shape: Tuple defining the desired shape of the tensor to create.
like: Optional tensor to use to determine additional properties
such as data type, device, etc ...
Return:... | One tensor of given shape. | [
"One",
"tensor",
"of",
"given",
"shape",
"."
] | def ones(module, shape, like=None):
_import_modules()
if module in [np, ma]:
if like is not None:
return module.ones(shape, dtype=like.dtype)
else:
return module.ones(shape)
elif module == torch:
if like is not None:
return module.ones(shape, dtype... | [
"def",
"ones",
"(",
"module",
",",
"shape",
",",
"like",
"=",
"None",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
"]",
":",
"if",
"like",
"is",
"not",
"None",
":",
"return",
"module",
".",
"ones",
"(",
"shap... | One tensor of given shape. | [
"One",
"tensor",
"of",
"given",
"shape",
"."
] | [
"\"\"\"\n One tensor of given shape.\n\n Arguments:\n module: The backend array corresponding to the given array.\n shape: Tuple defining the desired shape of the tensor to create.\n like: Optional tensor to use to determine additional properties\n such as data type, device, et... | [
{
"param": "module",
"type": null
},
{
"param": "shape",
"type": null
},
{
"param": "like",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | tensordot | <not_specific> | def tensordot(module, x, y, axes):
"""
Calculate tensor product of two tensors.
Arguments:
module: The backend array corresponding to the given array.
x: The left-hand-side operand
y: The right-hand-side operand
axes: Integer or pair of integers describing over which axes
... |
Calculate tensor product of two tensors.
Arguments:
module: The backend array corresponding to the given array.
x: The left-hand-side operand
y: The right-hand-side operand
axes: Integer or pair of integers describing over which axes
to calculate the tensor product.... | Calculate tensor product of two tensors. | [
"Calculate",
"tensor",
"product",
"of",
"two",
"tensors",
"."
] | def tensordot(module, x, y, axes):
_import_modules()
if module in [np, ma]:
return np.tensordot(x, y, axes)
elif module == torch:
return torch.tensordot(x, y, axes)
elif module == jnp:
return jnp.tensordot(x, y, axes)
elif module == tf:
return tf.tensordot(x, y, axes)... | [
"def",
"tensordot",
"(",
"module",
",",
"x",
",",
"y",
",",
"axes",
")",
":",
"_import_modules",
"(",
")",
"if",
"module",
"in",
"[",
"np",
",",
"ma",
"]",
":",
"return",
"np",
".",
"tensordot",
"(",
"x",
",",
"y",
",",
"axes",
")",
"elif",
"mo... | Calculate tensor product of two tensors. | [
"Calculate",
"tensor",
"product",
"of",
"two",
"tensors",
"."
] | [
"\"\"\"\n Calculate tensor product of two tensors.\n\n Arguments:\n module: The backend array corresponding to the given array.\n x: The left-hand-side operand\n y: The right-hand-side operand\n axes: Integer or pair of integers describing over which axes\n to calculate ... | [
{
"param": "module",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "axes",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
8dbc9a521c07cab5efce057ddbb80bf30339ced6 | simonpf/quantnn | quantnn/generic/__init__.py | [
"MIT"
] | Python | argmax | <not_specific> | def argmax(module, x, axes=None):
"""
Get indices of maximum in tensor.
Arguments:
module: The backend array corresponding to the given array.
x: The tensor to calculate the exponential of.
axes: Tuple specifying the axes along the which compute the
maximum.
Return:... |
Get indices of maximum in tensor.
Arguments:
module: The backend array corresponding to the given array.
x: The tensor to calculate the exponential of.
axes: Tuple specifying the axes along the which compute the
maximum.
Return:
Tensor containing indices of the... | Get indices of maximum in tensor. | [
"Get",
"indices",
"of",
"maximum",
"in",
"tensor",
"."
] | def argmax(module, x, axes=None):
return module.argmax(x, axes) | [
"def",
"argmax",
"(",
"module",
",",
"x",
",",
"axes",
"=",
"None",
")",
":",
"return",
"module",
".",
"argmax",
"(",
"x",
",",
"axes",
")"
] | Get indices of maximum in tensor. | [
"Get",
"indices",
"of",
"maximum",
"in",
"tensor",
"."
] | [
"\"\"\"\n Get indices of maximum in tensor.\n\n Arguments:\n module: The backend array corresponding to the given array.\n x: The tensor to calculate the exponential of.\n axes: Tuple specifying the axes along the which compute the\n maximum.\n\n Return:\n Tensor cont... | [
{
"param": "module",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "axes",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module",
"type": null,
"docstring": "The backend array corresponding to the given array.",
"docstring_tokens": [
"The",
"backend",
"array",
"corresponding",
"to",
"the",
... |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | handle_input | <not_specific> | def handle_input(data, device=None):
"""
Handle input data.
This function handles data supplied
- as tuple of :code:`np.ndarray`
- a single :code:`np.ndarray`
- torch :code:`dataloader`
If a numpy array is provided it is converted to a torch tensor
so that it can be fed into a p... |
Handle input data.
This function handles data supplied
- as tuple of :code:`np.ndarray`
- a single :code:`np.ndarray`
- torch :code:`dataloader`
If a numpy array is provided it is converted to a torch tensor
so that it can be fed into a pytorch model.
| Handle input data.
This function handles data supplied
If a numpy array is provided it is converted to a torch tensor
so that it can be fed into a pytorch model. | [
"Handle",
"input",
"data",
".",
"This",
"function",
"handles",
"data",
"supplied",
"If",
"a",
"numpy",
"array",
"is",
"provided",
"it",
"is",
"converted",
"to",
"a",
"torch",
"tensor",
"so",
"that",
"it",
"can",
"be",
"fed",
"into",
"a",
"pytorch",
"mode... | def handle_input(data, device=None):
if type(data) == tuple:
x, y = data
dtype_y = torch.float
if "int" in str(y.dtype):
dtype_y = torch.long
x = torch.tensor(x, dtype=torch.float)
y = torch.tensor(y, dtype=dtype_y)
if device is not None:
x = x... | [
"def",
"handle_input",
"(",
"data",
",",
"device",
"=",
"None",
")",
":",
"if",
"type",
"(",
"data",
")",
"==",
"tuple",
":",
"x",
",",
"y",
"=",
"data",
"dtype_y",
"=",
"torch",
".",
"float",
"if",
"\"int\"",
"in",
"str",
"(",
"y",
".",
"dtype",... | Handle input data. | [
"Handle",
"input",
"data",
"."
] | [
"\"\"\"\n Handle input data.\n\n This function handles data supplied\n\n - as tuple of :code:`np.ndarray`\n - a single :code:`np.ndarray`\n - torch :code:`dataloader`\n\n If a numpy array is provided it is converted to a torch tensor\n so that it can be fed into a pytorch model.\n \"\"... | [
{
"param": "data",
"type": null
},
{
"param": "device",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "device",
"type": null,
"docstring": null,
"docstring_tokens":... |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | _get_default_optimizer | <not_specific> | def _get_default_optimizer(model):
"""
The default optimizer. Currently set to Adam optimizer.
"""
optimizer = optim.Adam(model.parameters(), lr=0.0005)
return optimizer |
The default optimizer. Currently set to Adam optimizer.
| The default optimizer. Currently set to Adam optimizer. | [
"The",
"default",
"optimizer",
".",
"Currently",
"set",
"to",
"Adam",
"optimizer",
"."
] | def _get_default_optimizer(model):
optimizer = optim.Adam(model.parameters(), lr=0.0005)
return optimizer | [
"def",
"_get_default_optimizer",
"(",
"model",
")",
":",
"optimizer",
"=",
"optim",
".",
"Adam",
"(",
"model",
".",
"parameters",
"(",
")",
",",
"lr",
"=",
"0.0005",
")",
"return",
"optimizer"
] | The default optimizer. | [
"The",
"default",
"optimizer",
"."
] | [
"\"\"\"\n The default optimizer. Currently set to Adam optimizer.\n \"\"\""
] | [
{
"param": "model",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | _get_default_scheduler | <not_specific> | def _get_default_scheduler(optimizer):
"""
The default scheduler which reduces lr when training loss reaches a
plateau.
"""
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.1, patience=5)
return scheduler |
The default scheduler which reduces lr when training loss reaches a
plateau.
| The default scheduler which reduces lr when training loss reaches a
plateau. | [
"The",
"default",
"scheduler",
"which",
"reduces",
"lr",
"when",
"training",
"loss",
"reaches",
"a",
"plateau",
"."
] | def _get_default_scheduler(optimizer):
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.1, patience=5)
return scheduler | [
"def",
"_get_default_scheduler",
"(",
"optimizer",
")",
":",
"scheduler",
"=",
"optim",
".",
"lr_scheduler",
".",
"ReduceLROnPlateau",
"(",
"optimizer",
",",
"factor",
"=",
"0.1",
",",
"patience",
"=",
"5",
")",
"return",
"scheduler"
] | The default scheduler which reduces lr when training loss reaches a
plateau. | [
"The",
"default",
"scheduler",
"which",
"reduces",
"lr",
"when",
"training",
"loss",
"reaches",
"a",
"plateau",
"."
] | [
"\"\"\"\n The default scheduler which reduces lr when training loss reaches a\n plateau.\n \"\"\""
] | [
{
"param": "optimizer",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "optimizer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | _has_channels_last_tensor | <not_specific> | def _has_channels_last_tensor(parameters):
"""
Determine whether any of the tensors in the models parameters is
in channels last format.
"""
for p in parameters:
if isinstance(p.data, torch.Tensor):
t = p.data
if (
t.is_contiguous(memory_format=torch.c... |
Determine whether any of the tensors in the models parameters is
in channels last format.
| Determine whether any of the tensors in the models parameters is
in channels last format. | [
"Determine",
"whether",
"any",
"of",
"the",
"tensors",
"in",
"the",
"models",
"parameters",
"is",
"in",
"channels",
"last",
"format",
"."
] | def _has_channels_last_tensor(parameters):
for p in parameters:
if isinstance(p.data, torch.Tensor):
t = p.data
if (
t.is_contiguous(memory_format=torch.channels_last)
and not t.is_contiguous()
):
return True
eli... | [
"def",
"_has_channels_last_tensor",
"(",
"parameters",
")",
":",
"for",
"p",
"in",
"parameters",
":",
"if",
"isinstance",
"(",
"p",
".",
"data",
",",
"torch",
".",
"Tensor",
")",
":",
"t",
"=",
"p",
".",
"data",
"if",
"(",
"t",
".",
"is_contiguous",
... | Determine whether any of the tensors in the models parameters is
in channels last format. | [
"Determine",
"whether",
"any",
"of",
"the",
"tensors",
"in",
"the",
"models",
"parameters",
"is",
"in",
"channels",
"last",
"format",
"."
] | [
"\"\"\"\n Determine whether any of the tensors in the models parameters is\n in channels last format.\n \"\"\""
] | [
{
"param": "parameters",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "parameters",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | _get_x_y | <not_specific> | def _get_x_y(batch_data, keys):
"""
Retrieve training input from batch data.
This function checks whether the object returned as a batch from
the training loader is an iterable or a mapping. If it is an
iterable it will simply unpack the input- and target-data in the
order ``x, y``. If ``batch_... |
Retrieve training input from batch data.
This function checks whether the object returned as a batch from
the training loader is an iterable or a mapping. If it is an
iterable it will simply unpack the input- and target-data in the
order ``x, y``. If ``batch_data`` is a mapping and keys is not
... | Retrieve training input from batch data.
This function checks whether the object returned as a batch from
the training loader is an iterable or a mapping. If it is an
iterable it will simply unpack the input- and target-data in the
order ``x, y``. | [
"Retrieve",
"training",
"input",
"from",
"batch",
"data",
".",
"This",
"function",
"checks",
"whether",
"the",
"object",
"returned",
"as",
"a",
"batch",
"from",
"the",
"training",
"loader",
"is",
"an",
"iterable",
"or",
"a",
"mapping",
".",
"If",
"it",
"is... | def _get_x_y(batch_data, keys):
if isinstance(batch_data, Mapping):
if keys is not None:
try:
x_key, y_key = keys
except ValueError:
raise DatasetError(
f"Could not unpack provided keys f{keys} into "
"variables ... | [
"def",
"_get_x_y",
"(",
"batch_data",
",",
"keys",
")",
":",
"if",
"isinstance",
"(",
"batch_data",
",",
"Mapping",
")",
":",
"if",
"keys",
"is",
"not",
"None",
":",
"try",
":",
"x_key",
",",
"y_key",
"=",
"keys",
"except",
"ValueError",
":",
"raise",
... | Retrieve training input from batch data. | [
"Retrieve",
"training",
"input",
"from",
"batch",
"data",
"."
] | [
"\"\"\"\n Retrieve training input from batch data.\n\n This function checks whether the object returned as a batch from\n the training loader is an iterable or a mapping. If it is an\n iterable it will simply unpack the input- and target-data in the\n order ``x, y``. If ``batch_data`` is a mapping an... | [
{
"param": "batch_data",
"type": null
},
{
"param": "keys",
"type": null
}
] | {
"returns": [
{
"docstring": "Tuple ``x, y`` of input data ``x`` and corresponding output data\n``y``.",
"docstring_tokens": [
"Tuple",
"`",
"`",
"x",
"y",
"`",
"`",
"of",
"input",
"data",
"`",
"`",
... |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | channel_axis | <not_specific> | def channel_axis(self):
"""
The index of the axis that contains the channel information in a batch
of input data.
"""
if _has_channels_last_tensor(self.parameters()):
return -1
return 1 |
The index of the axis that contains the channel information in a batch
of input data.
| The index of the axis that contains the channel information in a batch
of input data. | [
"The",
"index",
"of",
"the",
"axis",
"that",
"contains",
"the",
"channel",
"information",
"in",
"a",
"batch",
"of",
"input",
"data",
"."
] | def channel_axis(self):
if _has_channels_last_tensor(self.parameters()):
return -1
return 1 | [
"def",
"channel_axis",
"(",
"self",
")",
":",
"if",
"_has_channels_last_tensor",
"(",
"self",
".",
"parameters",
"(",
")",
")",
":",
"return",
"-",
"1",
"return",
"1"
] | The index of the axis that contains the channel information in a batch
of input data. | [
"The",
"index",
"of",
"the",
"axis",
"that",
"contains",
"the",
"channel",
"information",
"in",
"a",
"batch",
"of",
"input",
"data",
"."
] | [
"\"\"\"\n The index of the axis that contains the channel information in a batch\n of input data.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | _make_adversarial_samples | <not_specific> | def _make_adversarial_samples(self, x, eps):
"""
Recycles current gradients to perform an adversarial training
step.
Args:
x: The current input.
eps: Scaling factor for the fast gradient sign method.
Returns:
x_adv: Perturbed input tensor rep... |
Recycles current gradients to perform an adversarial training
step.
Args:
x: The current input.
eps: Scaling factor for the fast gradient sign method.
Returns:
x_adv: Perturbed input tensor representing the adversarial
example.
... | Recycles current gradients to perform an adversarial training
step. | [
"Recycles",
"current",
"gradients",
"to",
"perform",
"an",
"adversarial",
"training",
"step",
"."
] | def _make_adversarial_samples(self, x, eps):
x_adv = x.detach() + eps * torch.sign(x.grad.detach())
return x_adv | [
"def",
"_make_adversarial_samples",
"(",
"self",
",",
"x",
",",
"eps",
")",
":",
"x_adv",
"=",
"x",
".",
"detach",
"(",
")",
"+",
"eps",
"*",
"torch",
".",
"sign",
"(",
"x",
".",
"grad",
".",
"detach",
"(",
")",
")",
"return",
"x_adv"
] | Recycles current gradients to perform an adversarial training
step. | [
"Recycles",
"current",
"gradients",
"to",
"perform",
"an",
"adversarial",
"training",
"step",
"."
] | [
"\"\"\"\n Recycles current gradients to perform an adversarial training\n step.\n\n Args:\n x: The current input.\n eps: Scaling factor for the fast gradient sign method.\n\n Returns:\n x_adv: Perturbed input tensor representing the adversarial\n ... | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "eps",
"type": null
}
] | {
"returns": [
{
"docstring": "Perturbed input tensor representing the adversarial\nexample.",
"docstring_tokens": [
"Perturbed",
"input",
"tensor",
"representing",
"the",
"adversarial",
"example",
"."
],
"type": "x_adv"
}... |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | reset | null | def reset(self):
"""
Reinitializes the weights of a model.
"""
def reset_function(module):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
m.reset_parameters()
self.apply(reset_function) |
Reinitializes the weights of a model.
| Reinitializes the weights of a model. | [
"Reinitializes",
"the",
"weights",
"of",
"a",
"model",
"."
] | def reset(self):
def reset_function(module):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
m.reset_parameters()
self.apply(reset_function) | [
"def",
"reset",
"(",
"self",
")",
":",
"def",
"reset_function",
"(",
"module",
")",
":",
"if",
"isinstance",
"(",
"m",
",",
"nn",
".",
"Conv2d",
")",
"or",
"isinstance",
"(",
"m",
",",
"nn",
".",
"Linear",
")",
":",
"m",
".",
"reset_parameters",
"(... | Reinitializes the weights of a model. | [
"Reinitializes",
"the",
"weights",
"of",
"a",
"model",
"."
] | [
"\"\"\"\n Reinitializes the weights of a model.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | _train_step | <not_specific> | def _train_step(
self, x, y, loss, adversarial_training, metrics=None, transformation=None
):
"""
Performs a single training step and returns a dictionary of
losses for every output.
Args:
x: The input data for the current batch.
y: The output data fo... |
Performs a single training step and returns a dictionary of
losses for every output.
Args:
x: The input data for the current batch.
y: The output data for the current batch.
adversarial_training: Scaling factor for adversarial training or
Non... | Performs a single training step and returns a dictionary of
losses for every output. | [
"Performs",
"a",
"single",
"training",
"step",
"and",
"returns",
"a",
"dictionary",
"of",
"losses",
"for",
"every",
"output",
"."
] | def _train_step(
self, x, y, loss, adversarial_training, metrics=None, transformation=None
):
y_pred = self(x)
if adversarial_training is not None:
x.requires_grad = True
if not isinstance(y_pred, dict):
y_pred = {"__loss__": y_pred}
if not isinstance(... | [
"def",
"_train_step",
"(",
"self",
",",
"x",
",",
"y",
",",
"loss",
",",
"adversarial_training",
",",
"metrics",
"=",
"None",
",",
"transformation",
"=",
"None",
")",
":",
"y_pred",
"=",
"self",
"(",
"x",
")",
"if",
"adversarial_training",
"is",
"not",
... | Performs a single training step and returns a dictionary of
losses for every output. | [
"Performs",
"a",
"single",
"training",
"step",
"and",
"returns",
"a",
"dictionary",
"of",
"losses",
"for",
"every",
"output",
"."
] | [
"\"\"\"\n Performs a single training step and returns a dictionary of\n losses for every output.\n\n Args:\n x: The input data for the current batch.\n y: The output data for the current batch.\n adversarial_training: Scaling factor for adversarial training or\n... | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "loss",
"type": null
},
{
"param": "adversarial_training",
"type": null
},
{
"param": "metrics",
"type": null
},
{
"param": "trans... | {
"returns": [
{
"docstring": "A single loss or a dictionary of losses in the case of a multi-output\nnetwork.",
"docstring_tokens": [
"A",
"single",
"loss",
"or",
"a",
"dictionary",
"of",
"losses",
"in",
"the",
"c... |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | train | <not_specific> | def train(
self,
training_data,
validation_data=None,
loss=None,
optimizer=None,
scheduler="default",
n_epochs=None,
adversarial_training=None,
batch_size=None,
device="cpu",
logger=None,
metrics=None,
keys=None,
... |
Train the network.
This trains the network for the given number of epochs using the
provided training and validation data.
If desired, the training can be augmented using adversarial training.
In this case the network is additionally trained with an adversarial
batch o... | Train the network.
This trains the network for the given number of epochs using the
provided training and validation data.
If desired, the training can be augmented using adversarial training.
In this case the network is additionally trained with an adversarial
batch of examples in each step of the training. | [
"Train",
"the",
"network",
".",
"This",
"trains",
"the",
"network",
"for",
"the",
"given",
"number",
"of",
"epochs",
"using",
"the",
"provided",
"training",
"and",
"validation",
"data",
".",
"If",
"desired",
"the",
"training",
"can",
"be",
"augmented",
"usin... | def train(
self,
training_data,
validation_data=None,
loss=None,
optimizer=None,
scheduler="default",
n_epochs=None,
adversarial_training=None,
batch_size=None,
device="cpu",
logger=None,
metrics=None,
keys=None,
... | [
"def",
"train",
"(",
"self",
",",
"training_data",
",",
"validation_data",
"=",
"None",
",",
"loss",
"=",
"None",
",",
"optimizer",
"=",
"None",
",",
"scheduler",
"=",
"\"default\"",
",",
"n_epochs",
"=",
"None",
",",
"adversarial_training",
"=",
"None",
"... | Train the network. | [
"Train",
"the",
"network",
"."
] | [
"\"\"\"\n Train the network.\n\n This trains the network for the given number of epochs using the\n provided training and validation data.\n\n If desired, the training can be augmented using adversarial training.\n In this case the network is additionally trained with an adversari... | [
{
"param": "self",
"type": null
},
{
"param": "training_data",
"type": null
},
{
"param": "validation_data",
"type": null
},
{
"param": "loss",
"type": null
},
{
"param": "optimizer",
"type": null
},
{
"param": "scheduler",
"type": null
},
{
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "training_data",
"type": null,
"docstring": "pytorch dataloader prov... |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | calibration | <not_specific> | def calibration(self, data, gpu=False):
"""
Computes the calibration of the predictions from the neural network.
Arguments:
data: torch dataloader object providing the data for which to compute
the calibration.
Returns:
(intervals, frequencies): ... |
Computes the calibration of the predictions from the neural network.
Arguments:
data: torch dataloader object providing the data for which to compute
the calibration.
Returns:
(intervals, frequencies): Tuple containing the confidence intervals and
... | Computes the calibration of the predictions from the neural network. | [
"Computes",
"the",
"calibration",
"of",
"the",
"predictions",
"from",
"the",
"neural",
"network",
"."
] | def calibration(self, data, gpu=False):
if gpu and torch.cuda.is_available():
dev = torch.device("cuda")
else:
dev = torch.device("cpu")
self.to(dev)
n_intervals = self.quantiles.size // 2
qs = self.quantiles
intervals = np.array([q_r - q_l for (q_... | [
"def",
"calibration",
"(",
"self",
",",
"data",
",",
"gpu",
"=",
"False",
")",
":",
"if",
"gpu",
"and",
"torch",
".",
"cuda",
".",
"is_available",
"(",
")",
":",
"dev",
"=",
"torch",
".",
"device",
"(",
"\"cuda\"",
")",
"else",
":",
"dev",
"=",
"... | Computes the calibration of the predictions from the neural network. | [
"Computes",
"the",
"calibration",
"of",
"the",
"predictions",
"from",
"the",
"neural",
"network",
"."
] | [
"\"\"\"\n Computes the calibration of the predictions from the neural network.\n\n Arguments:\n data: torch dataloader object providing the data for which to compute\n the calibration.\n\n Returns:\n (intervals, frequencies): Tuple containing the confidence ... | [
{
"param": "self",
"type": null
},
{
"param": "data",
"type": null
},
{
"param": "gpu",
"type": null
}
] | {
"returns": [
{
"docstring": "(intervals, frequencies): Tuple containing the confidence intervals and\ncorresponding observed frequencies.",
"docstring_tokens": [
"(",
"intervals",
"frequencies",
")",
":",
"Tuple",
"containing",
"the",
... |
74041f81a9171dad0d92e2d2c295e708968d9dea | simonpf/quantnn | quantnn/models/pytorch/common.py | [
"MIT"
] | Python | save | null | def save(self, path):
"""
Save QRNN to file.
Arguments:
The path in which to store the QRNN.
"""
torch.save(
{
"width": self.width,
"depth": self.depth,
"activation": self.activation,
"networ... |
Save QRNN to file.
Arguments:
The path in which to store the QRNN.
| Save QRNN to file.
Arguments:
The path in which to store the QRNN. | [
"Save",
"QRNN",
"to",
"file",
".",
"Arguments",
":",
"The",
"path",
"in",
"which",
"to",
"store",
"the",
"QRNN",
"."
] | def save(self, path):
torch.save(
{
"width": self.width,
"depth": self.depth,
"activation": self.activation,
"network_state": self.state_dict(),
"optimizer_state": self.optimizer.state_dict(),
},
... | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"torch",
".",
"save",
"(",
"{",
"\"width\"",
":",
"self",
".",
"width",
",",
"\"depth\"",
":",
"self",
".",
"depth",
",",
"\"activation\"",
":",
"self",
".",
"activation",
",",
"\"network_state\"",
":"... | Save QRNN to file. | [
"Save",
"QRNN",
"to",
"file",
"."
] | [
"\"\"\"\n Save QRNN to file.\n\n Arguments:\n The path in which to store the QRNN.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "path",
"type": null,
"docstring": null,
"docstring_tokens": [... |
02727efe7de83acfc44a3be9e8a014da62830614 | simonpf/quantnn | test/test_data.py | [
"MIT"
] | Python | _shuffle | null | def _shuffle(self):
"""
Shuffles the data order keeping x and y samples consistent.
"""
indices = np.random.permutation(self.x.shape[0])
self.x = self.x[indices]
self.y = self.y[indices] |
Shuffles the data order keeping x and y samples consistent.
| Shuffles the data order keeping x and y samples consistent. | [
"Shuffles",
"the",
"data",
"order",
"keeping",
"x",
"and",
"y",
"samples",
"consistent",
"."
] | def _shuffle(self):
indices = np.random.permutation(self.x.shape[0])
self.x = self.x[indices]
self.y = self.y[indices] | [
"def",
"_shuffle",
"(",
"self",
")",
":",
"indices",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"self",
".",
"x",
".",
"shape",
"[",
"0",
"]",
")",
"self",
".",
"x",
"=",
"self",
".",
"x",
"[",
"indices",
"]",
"self",
".",
"y",
"=",
"... | Shuffles the data order keeping x and y samples consistent. | [
"Shuffles",
"the",
"data",
"order",
"keeping",
"x",
"and",
"y",
"samples",
"consistent",
"."
] | [
"\"\"\"\n Shuffles the data order keeping x and y samples consistent.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
52990d3fcf3a3920824cb5eb29546a792b720461 | TurtleP/luaprettydoc | luaprettydoc/luafile.py | [
"MIT"
] | Python | should_update_markdown | bool | def should_update_markdown(self, filepath: str, output: str) -> bool:
"""Check if Markdown needs to be re-exported.
If it doesn't exist yet, return True"""
lua_file = Path(filepath).resolve()
markdown = Path(output).resolve()
if not markdown.exists():
return True
... | Check if Markdown needs to be re-exported.
If it doesn't exist yet, return True | Check if Markdown needs to be re-exported.
If it doesn't exist yet, return True | [
"Check",
"if",
"Markdown",
"needs",
"to",
"be",
"re",
"-",
"exported",
".",
"If",
"it",
"doesn",
"'",
"t",
"exist",
"yet",
"return",
"True"
] | def should_update_markdown(self, filepath: str, output: str) -> bool:
lua_file = Path(filepath).resolve()
markdown = Path(output).resolve()
if not markdown.exists():
return True
return lua_file.stat().st_mtime > markdown.stat().st_mtime | [
"def",
"should_update_markdown",
"(",
"self",
",",
"filepath",
":",
"str",
",",
"output",
":",
"str",
")",
"->",
"bool",
":",
"lua_file",
"=",
"Path",
"(",
"filepath",
")",
".",
"resolve",
"(",
")",
"markdown",
"=",
"Path",
"(",
"output",
")",
".",
"... | Check if Markdown needs to be re-exported. | [
"Check",
"if",
"Markdown",
"needs",
"to",
"be",
"re",
"-",
"exported",
"."
] | [
"\"\"\"Check if Markdown needs to be re-exported.\n If it doesn't exist yet, return True\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "filepath",
"type": "str"
},
{
"param": "output",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "filepath",
"type": "str",
"docstring": null,
"docstring_token... |
52990d3fcf3a3920824cb5eb29546a792b720461 | TurtleP/luaprettydoc | luaprettydoc/luafile.py | [
"MIT"
] | Python | is_metadata_valid | bool | def is_metadata_valid(self, type: str) -> bool:
"""Check if the Metadata Type is 'Module' or 'Library'"""
for item in MetadataType:
if type == item.value:
return True
return False | Check if the Metadata Type is 'Module' or 'Library | Check if the Metadata Type is 'Module' or 'Library | [
"Check",
"if",
"the",
"Metadata",
"Type",
"is",
"'",
"Module",
"'",
"or",
"'",
"Library"
] | def is_metadata_valid(self, type: str) -> bool:
for item in MetadataType:
if type == item.value:
return True
return False | [
"def",
"is_metadata_valid",
"(",
"self",
",",
"type",
":",
"str",
")",
"->",
"bool",
":",
"for",
"item",
"in",
"MetadataType",
":",
"if",
"type",
"==",
"item",
".",
"value",
":",
"return",
"True",
"return",
"False"
] | Check if the Metadata Type is 'Module' or 'Library | [
"Check",
"if",
"the",
"Metadata",
"Type",
"is",
"'",
"Module",
"'",
"or",
"'",
"Library"
] | [
"\"\"\"Check if the Metadata Type is 'Module' or 'Library'\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "type",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "type",
"type": "str",
"docstring": null,
"docstring_tokens": ... |
52990d3fcf3a3920824cb5eb29546a792b720461 | TurtleP/luaprettydoc | luaprettydoc/luafile.py | [
"MIT"
] | Python | create_metadata | None | def create_metadata(self, meta: list, name: str) -> None:
"""Create the Metadata for Markdown Output"""
module_type, module_name, module_brief = None, None, None
for metadata in meta:
if CommentTag.COMMENT_TAG_HEADER in metadata:
module_type = get_tag_line(metadata,... | Create the Metadata for Markdown Output | Create the Metadata for Markdown Output | [
"Create",
"the",
"Metadata",
"for",
"Markdown",
"Output"
] | def create_metadata(self, meta: list, name: str) -> None:
module_type, module_name, module_brief = None, None, None
for metadata in meta:
if CommentTag.COMMENT_TAG_HEADER in metadata:
module_type = get_tag_line(metadata, 1)
elif CommentTag.COMMENT_TAG_NAME in meta... | [
"def",
"create_metadata",
"(",
"self",
",",
"meta",
":",
"list",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"module_type",
",",
"module_name",
",",
"module_brief",
"=",
"None",
",",
"None",
",",
"None",
"for",
"metadata",
"in",
"meta",
":",
"if",... | Create the Metadata for Markdown Output | [
"Create",
"the",
"Metadata",
"for",
"Markdown",
"Output"
] | [
"\"\"\"Create the Metadata for Markdown Output\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "meta",
"type": "list"
},
{
"param": "name",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "meta",
"type": "list",
"docstring": null,
"docstring_tokens":... |
52990d3fcf3a3920824cb5eb29546a792b720461 | TurtleP/luaprettydoc | luaprettydoc/luafile.py | [
"MIT"
] | Python | handle_parameter_returns | str | def handle_parameter_returns(self, line: str) -> str:
"""Handle when we get a @param or @return tag"""
__param_return = get_tag_line(line, 1)
if __param_return:
return Templates.TEMPLATE_RETURN_PARAM.format(__param_return)
return str() | Handle when we get a @param or @return tag | Handle when we get a @param or @return tag | [
"Handle",
"when",
"we",
"get",
"a",
"@param",
"or",
"@return",
"tag"
] | def handle_parameter_returns(self, line: str) -> str:
__param_return = get_tag_line(line, 1)
if __param_return:
return Templates.TEMPLATE_RETURN_PARAM.format(__param_return)
return str() | [
"def",
"handle_parameter_returns",
"(",
"self",
",",
"line",
":",
"str",
")",
"->",
"str",
":",
"__param_return",
"=",
"get_tag_line",
"(",
"line",
",",
"1",
")",
"if",
"__param_return",
":",
"return",
"Templates",
".",
"TEMPLATE_RETURN_PARAM",
".",
"format",
... | Handle when we get a @param or @return tag | [
"Handle",
"when",
"we",
"get",
"a",
"@param",
"or",
"@return",
"tag"
] | [
"\"\"\"Handle when we get a @param or @return tag\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "line",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "line",
"type": "str",
"docstring": null,
"docstring_tokens": ... |
52990d3fcf3a3920824cb5eb29546a792b720461 | TurtleP/luaprettydoc | luaprettydoc/luafile.py | [
"MIT"
] | Python | handle_note | str | def handle_note(self, line: str) -> str:
"""Handle when we get a @note tag"""
__note = get_tag_line(line, 1)
if __note is not None:
return __note
return str() | Handle when we get a @note tag | Handle when we get a @note tag | [
"Handle",
"when",
"we",
"get",
"a",
"@note",
"tag"
] | def handle_note(self, line: str) -> str:
__note = get_tag_line(line, 1)
if __note is not None:
return __note
return str() | [
"def",
"handle_note",
"(",
"self",
",",
"line",
":",
"str",
")",
"->",
"str",
":",
"__note",
"=",
"get_tag_line",
"(",
"line",
",",
"1",
")",
"if",
"__note",
"is",
"not",
"None",
":",
"return",
"__note",
"return",
"str",
"(",
")"
] | Handle when we get a @note tag | [
"Handle",
"when",
"we",
"get",
"a",
"@note",
"tag"
] | [
"\"\"\"Handle when we get a @note tag\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "line",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "line",
"type": "str",
"docstring": null,
"docstring_tokens": ... |
52990d3fcf3a3920824cb5eb29546a792b720461 | TurtleP/luaprettydoc | luaprettydoc/luafile.py | [
"MIT"
] | Python | create_function | None | def create_function(self, data: dict) -> None:
"""Creates a Function's markdown data"""
__args = ", ".join(data["args"])
__call = None
__brief, __params = None, ""
__notes, __returns = list(), ""
__generate_function = True
for comment in data["comments"]:
... | Creates a Function's markdown data | Creates a Function's markdown data | [
"Creates",
"a",
"Function",
"'",
"s",
"markdown",
"data"
] | def create_function(self, data: dict) -> None:
__args = ", ".join(data["args"])
__call = None
__brief, __params = None, ""
__notes, __returns = list(), ""
__generate_function = True
for comment in data["comments"]:
if CommentTag.COMMENT_TAG_BRIEF in comment:
... | [
"def",
"create_function",
"(",
"self",
",",
"data",
":",
"dict",
")",
"->",
"None",
":",
"__args",
"=",
"\", \"",
".",
"join",
"(",
"data",
"[",
"\"args\"",
"]",
")",
"__call",
"=",
"None",
"__brief",
",",
"__params",
"=",
"None",
",",
"\"\"",
"__not... | Creates a Function's markdown data | [
"Creates",
"a",
"Function",
"'",
"s",
"markdown",
"data"
] | [
"\"\"\"Creates a Function's markdown data\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "data",
"type": "dict"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data",
"type": "dict",
"docstring": null,
"docstring_tokens":... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.