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
7aa54f786e0c99c9aa783fe511960da09d81b047
kienpt/site_discovery_public
discovery/collect_candidates.py
[ "Apache-1.1" ]
Python
extract_keywords
<not_specific>
def extract_keywords(sites, k=10): """ Extract top k most frequent keywords """ stop = stopwords.words('english') counter = Counter() for site in sites: for p in site: text = p.get_text('meta') text = URLUtility.clean_text(text) words = word_tokenize(...
Extract top k most frequent keywords
Extract top k most frequent keywords
[ "Extract", "top", "k", "most", "frequent", "keywords" ]
def extract_keywords(sites, k=10): stop = stopwords.words('english') counter = Counter() for site in sites: for p in site: text = p.get_text('meta') text = URLUtility.clean_text(text) words = word_tokenize(text) words = [word for word in words if word...
[ "def", "extract_keywords", "(", "sites", ",", "k", "=", "10", ")", ":", "stop", "=", "stopwords", ".", "words", "(", "'english'", ")", "counter", "=", "Counter", "(", ")", "for", "site", "in", "sites", ":", "for", "p", "in", "site", ":", "text", "=...
Extract top k most frequent keywords
[ "Extract", "top", "k", "most", "frequent", "keywords" ]
[ "\"\"\"\n Extract top k most frequent keywords\n \"\"\"", "# Get the topk words", "# convert to array" ]
[ { "param": "sites", "type": null }, { "param": "k", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sites", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "k", "type": null, "docstring": null, "docstring_tokens": [],...
195f692dbb2a3d5fffa65035a93f79aa8079006f
kienpt/site_discovery_public
extraction/link_extractor.py
[ "Apache-1.1" ]
Python
extract_links
<not_specific>
def extract_links(self, url, html): ''' Extract links from html source using regular expression. Return list of links Args: - url: url of the html source, used to construct absolute url from relative url - html: html source Returns: - links: extracted...
Extract links from html source using regular expression. Return list of links Args: - url: url of the html source, used to construct absolute url from relative url - html: html source Returns: - links: extracted (normalized and validated) links
Extract links from html source using regular expression. Return list of links
[ "Extract", "links", "from", "html", "source", "using", "regular", "expression", ".", "Return", "list", "of", "links" ]
def extract_links(self, url, html): match = self.LINK_PATTERN.findall(html) links = set([]) for link in match: link = urlparse.urljoin(url, link) link = URLUtility.validate_link(link) if link: link = URLUtility.normalize(link) i...
[ "def", "extract_links", "(", "self", ",", "url", ",", "html", ")", ":", "match", "=", "self", ".", "LINK_PATTERN", ".", "findall", "(", "html", ")", "links", "=", "set", "(", "[", "]", ")", "for", "link", "in", "match", ":", "link", "=", "urlparse"...
Extract links from html source using regular expression.
[ "Extract", "links", "from", "html", "source", "using", "regular", "expression", "." ]
[ "'''\n Extract links from html source using regular expression. Return list of links\n\n Args:\n - url: url of the html source, used to construct absolute url from relative url\n - html: html source\n Returns:\n - links: extracted (normalized and validated) link...
[ { "param": "self", "type": null }, { "param": "url", "type": null }, { "param": "html", "type": null } ]
{ "returns": [ { "docstring": "extracted (normalized and validated) links", "docstring_tokens": [ "extracted", "(", "normalized", "and", "validated", ")", "links" ], "type": null } ], "raises": [], "params": [ { "i...
195f692dbb2a3d5fffa65035a93f79aa8079006f
kienpt/site_discovery_public
extraction/link_extractor.py
[ "Apache-1.1" ]
Python
extract_links_bs
<not_specific>
def extract_links_bs(self, url, html): ''' Extract all outlinks from html using beautiful soup. Return list of links Args: - url: url of the html source, used to construct absolute url from relative url - html: html source Returns: - links: list of ou...
Extract all outlinks from html using beautiful soup. Return list of links Args: - url: url of the html source, used to construct absolute url from relative url - html: html source Returns: - links: list of outlinks
Extract all outlinks from html using beautiful soup. Return list of links
[ "Extract", "all", "outlinks", "from", "html", "using", "beautiful", "soup", ".", "Return", "list", "of", "links" ]
def extract_links_bs(self, url, html): try: soup = BeautifulSoup(html, 'lxml') except: print "Parsing with beautiful soup failed" return [] links = set() for tag in soup.findAll('a', href=True): link = tag['href'] try: ...
[ "def", "extract_links_bs", "(", "self", ",", "url", ",", "html", ")", ":", "try", ":", "soup", "=", "BeautifulSoup", "(", "html", ",", "'lxml'", ")", "except", ":", "print", "\"Parsing with beautiful soup failed\"", "return", "[", "]", "links", "=", "set", ...
Extract all outlinks from html using beautiful soup.
[ "Extract", "all", "outlinks", "from", "html", "using", "beautiful", "soup", "." ]
[ "'''\n Extract all outlinks from html using beautiful soup. Return list of links\n\n Args:\n - url: url of the html source, used to construct absolute url from relative url\n - html: html source\n Returns:\n - links: list of outlinks\n \n '''" ]
[ { "param": "self", "type": null }, { "param": "url", "type": null }, { "param": "html", "type": null } ]
{ "returns": [ { "docstring": "list of outlinks", "docstring_tokens": [ "list", "of", "outlinks" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], ...
195f692dbb2a3d5fffa65035a93f79aa8079006f
kienpt/site_discovery_public
extraction/link_extractor.py
[ "Apache-1.1" ]
Python
extract_external_links
<not_specific>
def extract_external_links(self, url, html): ''' Extract external outlinks, that link to different websites Returns: - list of unique urls ''' try: soup = BeautifulSoup(html, 'lxml') links = set() tld = URLUtility.get_tld(url) ...
Extract external outlinks, that link to different websites Returns: - list of unique urls
Extract external outlinks, that link to different websites
[ "Extract", "external", "outlinks", "that", "link", "to", "different", "websites" ]
def extract_external_links(self, url, html): try: soup = BeautifulSoup(html, 'lxml') links = set() tld = URLUtility.get_tld(url) for tag in soup.findAll('a', href=True): link = tag['href'] values = urlparse.urlparse(link) ...
[ "def", "extract_external_links", "(", "self", ",", "url", ",", "html", ")", ":", "try", ":", "soup", "=", "BeautifulSoup", "(", "html", ",", "'lxml'", ")", "links", "=", "set", "(", ")", "tld", "=", "URLUtility", ".", "get_tld", "(", "url", ")", "for...
Extract external outlinks, that link to different websites
[ "Extract", "external", "outlinks", "that", "link", "to", "different", "websites" ]
[ "'''\n Extract external outlinks, that link to different websites\n Returns: \n - list of unique urls\n '''" ]
[ { "param": "self", "type": null }, { "param": "url", "type": null }, { "param": "html", "type": null } ]
{ "returns": [ { "docstring": "list of unique urls", "docstring_tokens": [ "list", "of", "unique", "urls" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring...
e1d32a94cc893a55931ba1c122871fd6084aca7e
kienpt/site_discovery_public
search_apis/search_site.py
[ "Apache-1.1" ]
Python
search_site
null
def search_site(url_file, out_file, keyword): """ Write results as json line objects into out_file Format of each json object: list<str>: list of urls. First url is the main site """ urls = URLUtility.load_urls(url_file) site2urls = read_json(out_file) k = 10 out = open(out_f...
Write results as json line objects into out_file Format of each json object: list<str>: list of urls. First url is the main site
Write results as json line objects into out_file Format of each json object: list: list of urls. First url is the main site
[ "Write", "results", "as", "json", "line", "objects", "into", "out_file", "Format", "of", "each", "json", "object", ":", "list", ":", "list", "of", "urls", ".", "First", "url", "is", "the", "main", "site" ]
def search_site(url_file, out_file, keyword): urls = URLUtility.load_urls(url_file) site2urls = read_json(out_file) k = 10 out = open(out_file, "a+") for i, url in enumerate(urls): site = URLUtility.get_host(url) if site not in site2urls: results = bing_search.search_site...
[ "def", "search_site", "(", "url_file", ",", "out_file", ",", "keyword", ")", ":", "urls", "=", "URLUtility", ".", "load_urls", "(", "url_file", ")", "site2urls", "=", "read_json", "(", "out_file", ")", "k", "=", "10", "out", "=", "open", "(", "out_file",...
Write results as json line objects into out_file Format of each json object: list<str>: list of urls.
[ "Write", "results", "as", "json", "line", "objects", "into", "out_file", "Format", "of", "each", "json", "object", ":", "list<str", ">", ":", "list", "of", "urls", "." ]
[ "\"\"\"\n Write results as json line objects into out_file\n Format of each json object:\n list<str>: list of urls. First url is the main site\n \"\"\"" ]
[ { "param": "url_file", "type": null }, { "param": "out_file", "type": null }, { "param": "keyword", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "url_file", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "out_file", "type": null, "docstring": null, "docstring_to...
cbb95acd5e243b93dd341b4f369166178e9b783e
kienpt/site_discovery_public
evaluation/classifier.py
[ "Apache-1.1" ]
Python
train
null
def train(data_dir, model_file, vect_file, is_test=False): """ data_dir must contain 2 directories: positive and negative Each directory must contain a json file (i.e., data.json) or list of html files (ache format) """ print "Loading data..." pos_docs = load_data(data_dir + '/positive') neg...
data_dir must contain 2 directories: positive and negative Each directory must contain a json file (i.e., data.json) or list of html files (ache format)
data_dir must contain 2 directories: positive and negative Each directory must contain a json file or list of html files (ache format)
[ "data_dir", "must", "contain", "2", "directories", ":", "positive", "and", "negative", "Each", "directory", "must", "contain", "a", "json", "file", "or", "list", "of", "html", "files", "(", "ache", "format", ")" ]
def train(data_dir, model_file, vect_file, is_test=False): print "Loading data..." pos_docs = load_data(data_dir + '/positive') neg_docs = load_data(data_dir + '/negative') docs = pos_docs + neg_docs print "Vectorizing..." vectorizer = TfidfVectorizer(stop_words='english', ngram_range=(1,2), max...
[ "def", "train", "(", "data_dir", ",", "model_file", ",", "vect_file", ",", "is_test", "=", "False", ")", ":", "print", "\"Loading data...\"", "pos_docs", "=", "load_data", "(", "data_dir", "+", "'/positive'", ")", "neg_docs", "=", "load_data", "(", "data_dir",...
data_dir must contain 2 directories: positive and negative Each directory must contain a json file (i.e., data.json) or list of html files (ache format)
[ "data_dir", "must", "contain", "2", "directories", ":", "positive", "and", "negative", "Each", "directory", "must", "contain", "a", "json", "file", "(", "i", ".", "e", ".", "data", ".", "json", ")", "or", "list", "of", "html", "files", "(", "ache", "fo...
[ "\"\"\"\n data_dir must contain 2 directories: positive and negative\n Each directory must contain a json file (i.e., data.json) or list of html files (ache format)\n \"\"\"", "#vectorizer = TfidfVectorizer(tokenizer=LemmaTokenizer(), stop_words='english', ngram_range=(1,2), max_df=0.95, min_df=0.05, nor...
[ { "param": "data_dir", "type": null }, { "param": "model_file", "type": null }, { "param": "vect_file", "type": null }, { "param": "is_test", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data_dir", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "model_file", "type": null, "docstring": null, "docstring_...
ca28af96b500835576dbf3a2220f4e0e76f7029a
kienpt/site_discovery_public
utils/page.py
[ "Apache-1.1" ]
Python
load_from_json
<not_specific>
def load_from_json(self, json_obj): """ Don't load the json object if it is not valid (e.g., too large or lacking of title) """ """ if json_obj['url'] == "http://www.armslist.com/classifieds/knoxville-tennessee": print json_obj print self.is_valid(json_obj...
Don't load the json object if it is not valid (e.g., too large or lacking of title)
Don't load the json object if it is not valid
[ "Don", "'", "t", "load", "the", "json", "object", "if", "it", "is", "not", "valid" ]
def load_from_json(self, json_obj): if not json_obj: print "Warning: json object is empty" return if 'html' in json_obj: if self.is_valid(json_obj): self.html = json_obj['html'] if 'text' in json_obj: self.body = jso...
[ "def", "load_from_json", "(", "self", ",", "json_obj", ")", ":", "\"\"\"\n if json_obj['url'] == \"http://www.armslist.com/classifieds/knoxville-tennessee\":\n print json_obj\n print self.is_valid(json_obj)\n print json_obj['text']\n \"\"\"", "if", ...
Don't load the json object if it is not valid (e.g., too large or lacking of title)
[ "Don", "'", "t", "load", "the", "json", "object", "if", "it", "is", "not", "valid", "(", "e", ".", "g", ".", "too", "large", "or", "lacking", "of", "title", ")" ]
[ "\"\"\"\n Don't load the json object if it is not valid (e.g., too large or lacking of title)\n \"\"\"", "\"\"\"\n if json_obj['url'] == \"http://www.armslist.com/classifieds/knoxville-tennessee\":\n print json_obj\n print self.is_valid(json_obj)\n print json_...
[ { "param": "self", "type": null }, { "param": "json_obj", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "json_obj", "type": null, "docstring": null, "docstring_tokens...
aefadd5637b13ba5e23298883ab0feb9d53eae0c
kienpt/site_discovery_public
plotting/plot_harvestrate/prepare_data.py
[ "Apache-1.1" ]
Python
prepare_wdt
<not_specific>
def prepare_wdt(result_file, clf_file): """ Prepare data from website discovery tool Args: - result_file: output from wdt - clf_file: classification result """ url2label, site2label = _read_clf_file(clf_file) urls = _read_result_file(result_file) # urls ordered by timestamp relev_pa...
Prepare data from website discovery tool Args: - result_file: output from wdt - clf_file: classification result
Prepare data from website discovery tool Args: result_file: output from wdt clf_file: classification result
[ "Prepare", "data", "from", "website", "discovery", "tool", "Args", ":", "result_file", ":", "output", "from", "wdt", "clf_file", ":", "classification", "result" ]
def prepare_wdt(result_file, clf_file): url2label, site2label = _read_clf_file(clf_file) urls = _read_result_file(result_file) relev_pages, relev_sites = _count_relev(url2label, site2label, urls) return relev_pages, relev_sites
[ "def", "prepare_wdt", "(", "result_file", ",", "clf_file", ")", ":", "url2label", ",", "site2label", "=", "_read_clf_file", "(", "clf_file", ")", "urls", "=", "_read_result_file", "(", "result_file", ")", "relev_pages", ",", "relev_sites", "=", "_count_relev", "...
Prepare data from website discovery tool Args: result_file: output from wdt clf_file: classification result
[ "Prepare", "data", "from", "website", "discovery", "tool", "Args", ":", "result_file", ":", "output", "from", "wdt", "clf_file", ":", "classification", "result" ]
[ "\"\"\"\n Prepare data from website discovery tool\n\n Args:\n - result_file: output from wdt\n - clf_file: classification result\n \"\"\"", "# urls ordered by timestamp" ]
[ { "param": "result_file", "type": null }, { "param": "clf_file", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "result_file", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "clf_file", "type": null, "docstring": null, "docstring...
1bfac1ca4180e2ea1cb5947ac9b24d2447d7018e
kienpt/site_discovery_public
utils/multiproc_fetcher.py
[ "Apache-1.1" ]
Python
_contains
<not_specific>
def _contains(self, url): """ Check the cache if it contains the url. Returns: return a dict object if url exists in the cache, else return None """ for cache in self.caches: if cache.contains(url): return cache.get(url) return N...
Check the cache if it contains the url. Returns: return a dict object if url exists in the cache, else return None
Check the cache if it contains the url.
[ "Check", "the", "cache", "if", "it", "contains", "the", "url", "." ]
def _contains(self, url): for cache in self.caches: if cache.contains(url): return cache.get(url) return None
[ "def", "_contains", "(", "self", ",", "url", ")", ":", "for", "cache", "in", "self", ".", "caches", ":", "if", "cache", ".", "contains", "(", "url", ")", ":", "return", "cache", ".", "get", "(", "url", ")", "return", "None" ]
Check the cache if it contains the url.
[ "Check", "the", "cache", "if", "it", "contains", "the", "url", "." ]
[ "\"\"\" \n Check the cache if it contains the url.\n\n Returns:\n return a dict object if url exists in the cache, else return None\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "url", "type": null } ]
{ "returns": [ { "docstring": "return a dict object if url exists in the cache, else return None", "docstring_tokens": [ "return", "a", "dict", "object", "if", "url", "exists", "in", "the", "cache", "else", ...
1bfac1ca4180e2ea1cb5947ac9b24d2447d7018e
kienpt/site_discovery_public
utils/multiproc_fetcher.py
[ "Apache-1.1" ]
Python
fetch_sites
<not_specific>
def fetch_sites(self, urls, max_pages=1, selection="random", online=True, allow_fetch_later=False): """ Fetch the sites. Step 1: Fetch the home pages Step 2: Select representative pages from the fetched sites Step 3: Fetch the selected representative pages Step 4: Merge t...
Fetch the sites. Step 1: Fetch the home pages Step 2: Select representative pages from the fetched sites Step 3: Fetch the selected representative pages Step 4: Merge the fetched results Parameters: ----------- urls: list of url. Each url represents a w...
Fetch the sites. Step 1: Fetch the home pages Step 2: Select representative pages from the fetched sites Step 3: Fetch the selected representative pages Step 4: Merge the fetched results list of url. Each url represents a website max_pages: maximum number of pages to be selected in each website selection: method to ...
[ "Fetch", "the", "sites", ".", "Step", "1", ":", "Fetch", "the", "home", "pages", "Step", "2", ":", "Select", "representative", "pages", "from", "the", "fetched", "sites", "Step", "3", ":", "Fetch", "the", "selected", "representative", "pages", "Step", "4",...
def fetch_sites(self, urls, max_pages=1, selection="random", online=True, allow_fetch_later=False): pages = self.fetch_pages(urls, online, allow_fetch_later) max_pages -= 1 websites = {} for p in pages: tld = p.get_tld() w = Website(p.get_url()) w....
[ "def", "fetch_sites", "(", "self", ",", "urls", ",", "max_pages", "=", "1", ",", "selection", "=", "\"random\"", ",", "online", "=", "True", ",", "allow_fetch_later", "=", "False", ")", ":", "\"\"\"\n # Hack: used pre-fetched data\n if online==False and ...
Fetch the sites.
[ "Fetch", "the", "sites", "." ]
[ "\"\"\"\n Fetch the sites.\n Step 1: Fetch the home pages\n Step 2: Select representative pages from the fetched sites\n Step 3: Fetch the selected representative pages\n Step 4: Merge the fetched results \n\n Parameters:\n -----------\n urls: list of url. Eac...
[ { "param": "self", "type": null }, { "param": "urls", "type": null }, { "param": "max_pages", "type": null }, { "param": "selection", "type": null }, { "param": "online", "type": null }, { "param": "allow_fetch_later", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "urls", "type": null, "docstring": null, "docstring_tokens": [...
1bfac1ca4180e2ea1cb5947ac9b24d2447d7018e
kienpt/site_discovery_public
utils/multiproc_fetcher.py
[ "Apache-1.1" ]
Python
_select_by_search
<not_specific>
def _select_by_search(self, page, max_pages): """ Select pages inside a given website using site search Args: max_pages: maximum number of pages selected in the site """ "Selecing pages using bing search" host = page.get_host() keyword = "gun" ...
Select pages inside a given website using site search Args: max_pages: maximum number of pages selected in the site
Select pages inside a given website using site search
[ "Select", "pages", "inside", "a", "given", "website", "using", "site", "search" ]
def _select_by_search(self, page, max_pages): host = page.get_host() keyword = "gun" urls = self.bing_search.search_site(keyword, host) ret = [] for url in urls: if len(ret)<max_pages: if url!=page.get_url(): ret.append(url) ...
[ "def", "_select_by_search", "(", "self", ",", "page", ",", "max_pages", ")", ":", "\"Selecing pages using bing search\"", "host", "=", "page", ".", "get_host", "(", ")", "keyword", "=", "\"gun\"", "urls", "=", "self", ".", "bing_search", ".", "search_site", "(...
Select pages inside a given website using site search
[ "Select", "pages", "inside", "a", "given", "website", "using", "site", "search" ]
[ "\"\"\"\n Select pages inside a given website using site search\n\n Args:\n max_pages: maximum number of pages selected in the site\n \"\"\"", "\"Selecing pages using bing search\"", "\"\"\"\n if host==\"http://www.armslist.com/\":\n print urls\n prin...
[ { "param": "self", "type": null }, { "param": "page", "type": null }, { "param": "max_pages", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "page", "type": null, "docstring": null, "docstring_tokens": [...
1bfac1ca4180e2ea1cb5947ac9b24d2447d7018e
kienpt/site_discovery_public
utils/multiproc_fetcher.py
[ "Apache-1.1" ]
Python
fetch_pages
<not_specific>
def fetch_pages(self, urls, online=True, allow_fetch_later=False): """ Fetch the urls that are not in cache Parameters: ----------- urls: list of url. Each url represents a website Returns: -------- list<website>: list of fetched websites """ ...
Fetch the urls that are not in cache Parameters: ----------- urls: list of url. Each url represents a website Returns: -------- list<website>: list of fetched websites
Fetch the urls that are not in cache Parameters. list of url. Each url represents a website list: list of fetched websites
[ "Fetch", "the", "urls", "that", "are", "not", "in", "cache", "Parameters", ".", "list", "of", "url", ".", "Each", "url", "represents", "a", "website", "list", ":", "list", "of", "fetched", "websites" ]
def fetch_pages(self, urls, online=True, allow_fetch_later=False): print "Number of urls considering to fetch: ", len(urls) if allow_fetch_later==False: temp_urls = [] for url in urls: if url not in self.uniq_urls: self.uniq_urls.add(url) ...
[ "def", "fetch_pages", "(", "self", ",", "urls", ",", "online", "=", "True", ",", "allow_fetch_later", "=", "False", ")", ":", "print", "\"Number of urls considering to fetch: \"", ",", "len", "(", "urls", ")", "if", "allow_fetch_later", "==", "False", ":", "te...
Fetch the urls that are not in cache Parameters:
[ "Fetch", "the", "urls", "that", "are", "not", "in", "cache", "Parameters", ":" ]
[ "\"\"\"\n Fetch the urls that are not in cache\n\n Parameters:\n -----------\n urls: list of url. Each url represents a website\n\n Returns:\n --------\n list<website>: list of fetched websites\n \"\"\"", "# Remove urls that were crawled previously", "# Re...
[ { "param": "self", "type": null }, { "param": "urls", "type": null }, { "param": "online", "type": null }, { "param": "allow_fetch_later", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "urls", "type": null, "docstring": null, "docstring_tokens": [...
3c9259e984c78d72cbaf9a6a926b5c476a2e2700
kienpt/site_discovery_public
search_apis/bing_search.py
[ "Apache-1.1" ]
Python
search_site
<not_specific>
def search_site(self, keyword, url, k=10): """ Search inside a given website using the search command: "keyword site:url" Parameters keyword: keyword used to search url: top level domain Returns list of urls """ keyword = keyword + " s...
Search inside a given website using the search command: "keyword site:url" Parameters keyword: keyword used to search url: top level domain Returns list of urls
Search inside a given website using the search command: "keyword site:url" Parameters keyword: keyword used to search url: top level domain Returns list of urls
[ "Search", "inside", "a", "given", "website", "using", "the", "search", "command", ":", "\"", "keyword", "site", ":", "url", "\"", "Parameters", "keyword", ":", "keyword", "used", "to", "search", "url", ":", "top", "level", "domain", "Returns", "list", "of"...
def search_site(self, keyword, url, k=10): keyword = keyword + " site:" + url return self.search(keyword, k)
[ "def", "search_site", "(", "self", ",", "keyword", ",", "url", ",", "k", "=", "10", ")", ":", "keyword", "=", "keyword", "+", "\" site:\"", "+", "url", "return", "self", ".", "search", "(", "keyword", ",", "k", ")" ]
Search inside a given website using the search command: "keyword site:url" Parameters keyword: keyword used to search url: top level domain Returns list of urls
[ "Search", "inside", "a", "given", "website", "using", "the", "search", "command", ":", "\"", "keyword", "site", ":", "url", "\"", "Parameters", "keyword", ":", "keyword", "used", "to", "search", "url", ":", "top", "level", "domain", "Returns", "list", "of"...
[ "\"\"\"\n Search inside a given website using the search command: \"keyword site:url\"\n Parameters\n keyword: keyword used to search\n url: top level domain\n Returns \n list of urls\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "keyword", "type": null }, { "param": "url", "type": null }, { "param": "k", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "keyword", "type": null, "docstring": null, "docstring_tokens"...
8cbcc4b7aaf2a67786c162bf1db92fb5daedc848
kienpt/site_discovery_public
search_apis/search_apis.py
[ "Apache-1.1" ]
Python
_extract_keywords
<not_specific>
def _extract_keywords(self, sites, k=10): """ Extract top k most frequent keywords. Skip ones that were selected. """ stop = stopwords.words('english') counter = Counter() for site in sites: for p in site: text = p.get_text('meta') ...
Extract top k most frequent keywords. Skip ones that were selected.
Extract top k most frequent keywords. Skip ones that were selected.
[ "Extract", "top", "k", "most", "frequent", "keywords", ".", "Skip", "ones", "that", "were", "selected", "." ]
def _extract_keywords(self, sites, k=10): stop = stopwords.words('english') counter = Counter() for site in sites: for p in site: text = p.get_text('meta') text = URLUtility.clean_text(text) words = nltk.word_tokenize(text) ...
[ "def", "_extract_keywords", "(", "self", ",", "sites", ",", "k", "=", "10", ")", ":", "stop", "=", "stopwords", ".", "words", "(", "'english'", ")", "counter", "=", "Counter", "(", ")", "for", "site", "in", "sites", ":", "for", "p", "in", "site", "...
Extract top k most frequent keywords.
[ "Extract", "top", "k", "most", "frequent", "keywords", "." ]
[ "\"\"\"\n Extract top k most frequent keywords. Skip ones that were selected.\n \"\"\"", "# Get the topk words", "\"\"\"\n counter = [(counter[w], w) for w in counter if counter[w]>1] # convert to array\n heapq.heapify(counter)\n topk = heapq.nlargest(k, counter)\n retu...
[ { "param": "self", "type": null }, { "param": "sites", "type": null }, { "param": "k", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sites", "type": null, "docstring": null, "docstring_tokens": ...
8cbcc4b7aaf2a67786c162bf1db92fb5daedc848
kienpt/site_discovery_public
search_apis/search_apis.py
[ "Apache-1.1" ]
Python
search_backward_forward
<not_specific>
def search_backward_forward(self, url): """ Search related pages using backlink search and forward search Returns: - list of urls (potentially duplicated) """ t = time.time() backlinks = self.search_backward(url) print "Backlink search time: ", time.t...
Search related pages using backlink search and forward search Returns: - list of urls (potentially duplicated)
Search related pages using backlink search and forward search
[ "Search", "related", "pages", "using", "backlink", "search", "and", "forward", "search" ]
def search_backward_forward(self, url): t = time.time() backlinks = self.search_backward(url) print "Backlink search time: ", time.time() - t t = time.time() fwlinks = self.search_forward(backlinks) print "Forward search time: ", time.time() - t return backlinks ...
[ "def", "search_backward_forward", "(", "self", ",", "url", ")", ":", "t", "=", "time", ".", "time", "(", ")", "backlinks", "=", "self", ".", "search_backward", "(", "url", ")", "print", "\"Backlink search time: \"", ",", "time", ".", "time", "(", ")", "-...
Search related pages using backlink search and forward search
[ "Search", "related", "pages", "using", "backlink", "search", "and", "forward", "search" ]
[ "\"\"\"\n Search related pages using backlink search and forward search\n\n Returns:\n - list of urls (potentially duplicated)\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "url", "type": null } ]
{ "returns": [ { "docstring": "list of urls (potentially duplicated)", "docstring_tokens": [ "list", "of", "urls", "(", "potentially", "duplicated", ")" ], "type": null } ], "raises": [], "params": [ { "identifier"...
8cbcc4b7aaf2a67786c162bf1db92fb5daedc848
kienpt/site_discovery_public
search_apis/search_apis.py
[ "Apache-1.1" ]
Python
search_backward_forward_batch
<not_specific>
def search_backward_forward_batch(self, sites): """ Search related pages using backlink search and forward search Parameters: - sites: list of Website objects Returns: - list of urls (potentially duplicated) """ t = time.time() backlinks =...
Search related pages using backlink search and forward search Parameters: - sites: list of Website objects Returns: - list of urls (potentially duplicated)
Search related pages using backlink search and forward search
[ "Search", "related", "pages", "using", "backlink", "search", "and", "forward", "search" ]
def search_backward_forward_batch(self, sites): t = time.time() backlinks = set() for site in sites: backlinks.update(self.search_backward(site.get_host())) backlinks = list(backlinks) print "Backlink search time: ", time.time() - t t = time.time() fwl...
[ "def", "search_backward_forward_batch", "(", "self", ",", "sites", ")", ":", "t", "=", "time", ".", "time", "(", ")", "backlinks", "=", "set", "(", ")", "for", "site", "in", "sites", ":", "backlinks", ".", "update", "(", "self", ".", "search_backward", ...
Search related pages using backlink search and forward search
[ "Search", "related", "pages", "using", "backlink", "search", "and", "forward", "search" ]
[ "\"\"\"\n Search related pages using backlink search and forward search\n\n Parameters:\n - sites: list of Website objects\n Returns:\n - list of urls (potentially duplicated)\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "sites", "type": null } ]
{ "returns": [ { "docstring": "list of urls (potentially duplicated)", "docstring_tokens": [ "list", "of", "urls", "(", "potentially", "duplicated", ")" ], "type": null } ], "raises": [], "params": [ { "identifier"...
8cbcc4b7aaf2a67786c162bf1db92fb5daedc848
kienpt/site_discovery_public
search_apis/search_apis.py
[ "Apache-1.1" ]
Python
search_keywords
<not_specific>
def search_keywords(self, keyword, max_results, se='google'): """ Search relevant pages by keyword using Google Args: max_results: maximum number of results to return """ urls = [] if self.keyword_cache.contains(keyword): urls = self.keyword_cache.ge...
Search relevant pages by keyword using Google Args: max_results: maximum number of results to return
Search relevant pages by keyword using Google Args: max_results: maximum number of results to return
[ "Search", "relevant", "pages", "by", "keyword", "using", "Google", "Args", ":", "max_results", ":", "maximum", "number", "of", "results", "to", "return" ]
def search_keywords(self, keyword, max_results, se='google'): urls = [] if self.keyword_cache.contains(keyword): urls = self.keyword_cache.get(keyword) print "hit keyword query: ", keyword else: if se=='google': time.sleep(self.google_delay) ...
[ "def", "search_keywords", "(", "self", ",", "keyword", ",", "max_results", ",", "se", "=", "'google'", ")", ":", "urls", "=", "[", "]", "if", "self", ".", "keyword_cache", ".", "contains", "(", "keyword", ")", ":", "urls", "=", "self", ".", "keyword_ca...
Search relevant pages by keyword using Google Args: max_results: maximum number of results to return
[ "Search", "relevant", "pages", "by", "keyword", "using", "Google", "Args", ":", "max_results", ":", "maximum", "number", "of", "results", "to", "return" ]
[ "\"\"\"\n Search relevant pages by keyword using Google\n\n Args:\n max_results: maximum number of results to return\n\n \"\"\"", "# default: 'bing'", "\"\"\"\n if 'items' in results:\n for item in results['items']:\n urls.append(url_normalize(item['l...
[ { "param": "self", "type": null }, { "param": "keyword", "type": null }, { "param": "max_results", "type": null }, { "param": "se", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "keyword", "type": null, "docstring": null, "docstring_tokens"...
8cbcc4b7aaf2a67786c162bf1db92fb5daedc848
kienpt/site_discovery_public
search_apis/search_apis.py
[ "Apache-1.1" ]
Python
search_forward_sites
<not_specific>
def search_forward_sites(self, sites, insite=False): """ Fetch the pages and extract external links. Args - sites: list of Website objects - insite: False if extracting links outside the host. """ outlinks = set() for site in sites: fo...
Fetch the pages and extract external links. Args - sites: list of Website objects - insite: False if extracting links outside the host.
Fetch the pages and extract external links. Args sites: list of Website objects insite: False if extracting links outside the host.
[ "Fetch", "the", "pages", "and", "extract", "external", "links", ".", "Args", "sites", ":", "list", "of", "Website", "objects", "insite", ":", "False", "if", "extracting", "links", "outside", "the", "host", "." ]
def search_forward_sites(self, sites, insite=False): outlinks = set() for site in sites: for page in site: if insite: links = self.link_extractor.extract_insite_links(page.get_url(), page.get_html()) else: links = self.l...
[ "def", "search_forward_sites", "(", "self", ",", "sites", ",", "insite", "=", "False", ")", ":", "outlinks", "=", "set", "(", ")", "for", "site", "in", "sites", ":", "for", "page", "in", "site", ":", "if", "insite", ":", "links", "=", "self", ".", ...
Fetch the pages and extract external links.
[ "Fetch", "the", "pages", "and", "extract", "external", "links", "." ]
[ "\"\"\"\n Fetch the pages and extract external links. \n Args\n - sites: list of Website objects\n - insite: False if extracting links outside the host.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "sites", "type": null }, { "param": "insite", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sites", "type": null, "docstring": null, "docstring_tokens": ...
8cbcc4b7aaf2a67786c162bf1db92fb5daedc848
kienpt/site_discovery_public
search_apis/search_apis.py
[ "Apache-1.1" ]
Python
search_forward
<not_specific>
def search_forward(self, urls, insite=False): """ Fetch the pages and extract external links Args - urls: list of urls - insite: False if extracting links outside the host. """ sites = self.fetcher.fetch_sites(urls, allow_fetch_later = True) outli...
Fetch the pages and extract external links Args - urls: list of urls - insite: False if extracting links outside the host.
Fetch the pages and extract external links Args urls: list of urls insite: False if extracting links outside the host.
[ "Fetch", "the", "pages", "and", "extract", "external", "links", "Args", "urls", ":", "list", "of", "urls", "insite", ":", "False", "if", "extracting", "links", "outside", "the", "host", "." ]
def search_forward(self, urls, insite=False): sites = self.fetcher.fetch_sites(urls, allow_fetch_later = True) outlinks = set() for site in sites: for page in site: if insite: links = self.link_extractor.extract_insite_links(page.get_url(), page.g...
[ "def", "search_forward", "(", "self", ",", "urls", ",", "insite", "=", "False", ")", ":", "sites", "=", "self", ".", "fetcher", ".", "fetch_sites", "(", "urls", ",", "allow_fetch_later", "=", "True", ")", "outlinks", "=", "set", "(", ")", "for", "site"...
Fetch the pages and extract external links Args urls: list of urls insite: False if extracting links outside the host.
[ "Fetch", "the", "pages", "and", "extract", "external", "links", "Args", "urls", ":", "list", "of", "urls", "insite", ":", "False", "if", "extracting", "links", "outside", "the", "host", "." ]
[ "\"\"\"\n Fetch the pages and extract external links\n Args\n - urls: list of urls\n - insite: False if extracting links outside the host.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "urls", "type": null }, { "param": "insite", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "urls", "type": null, "docstring": null, "docstring_tokens": [...
8cbcc4b7aaf2a67786c162bf1db92fb5daedc848
kienpt/site_discovery_public
search_apis/search_apis.py
[ "Apache-1.1" ]
Python
select_subset
<not_specific>
def select_subset(self, urls): """ Each page might contain thousand of external urls which pollute the results, so we only keep a fixed number of links from each page How this works: - Pick one url in each site - If not yet reaching max, select random urls Retur...
Each page might contain thousand of external urls which pollute the results, so we only keep a fixed number of links from each page How this works: - Pick one url in each site - If not yet reaching max, select random urls Returns: - list of urls
Each page might contain thousand of external urls which pollute the results, so we only keep a fixed number of links from each page How this works: Pick one url in each site If not yet reaching max, select random urls
[ "Each", "page", "might", "contain", "thousand", "of", "external", "urls", "which", "pollute", "the", "results", "so", "we", "only", "keep", "a", "fixed", "number", "of", "links", "from", "each", "page", "How", "this", "works", ":", "Pick", "one", "url", ...
def select_subset(self, urls): if len(urls)<=self.max_urls: return urls results = [] sites = set() for url in urls: site = URLUtility.get_host(url) if site not in sites: sites.add(site) results.append(url) i...
[ "def", "select_subset", "(", "self", ",", "urls", ")", ":", "if", "len", "(", "urls", ")", "<=", "self", ".", "max_urls", ":", "return", "urls", "results", "=", "[", "]", "\"\"\"\n cur = urls\n while len(results)<self.max_urls:\n sites = set()...
Each page might contain thousand of external urls which pollute the results, so we only keep a fixed number of links from each page How this works: Pick one url in each site If not yet reaching max, select random urls
[ "Each", "page", "might", "contain", "thousand", "of", "external", "urls", "which", "pollute", "the", "results", "so", "we", "only", "keep", "a", "fixed", "number", "of", "links", "from", "each", "page", "How", "this", "works", ":", "Pick", "one", "url", ...
[ "\"\"\"\n Each page might contain thousand of external urls which pollute the results, so we only keep a fixed number of links from each page\n How this works:\n - Pick one url in each site \n - If not yet reaching max, select random urls\n Returns:\n - list of...
[ { "param": "self", "type": null }, { "param": "urls", "type": null } ]
{ "returns": [ { "docstring": "list of urls", "docstring_tokens": [ "list", "of", "urls" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "defa...
8cbcc4b7aaf2a67786c162bf1db92fb5daedc848
kienpt/site_discovery_public
search_apis/search_apis.py
[ "Apache-1.1" ]
Python
search_related
<not_specific>
def search_related(self, url, k): """ Return list of related urls using Google related search """ query = "related:" + url urls = [] if self.related_cache.contains(query): urls = self.related_cache.get(query) print "hit related query: ", query ...
Return list of related urls using Google related search
Return list of related urls using Google related search
[ "Return", "list", "of", "related", "urls", "using", "Google", "related", "search" ]
def search_related(self, url, k): query = "related:" + url urls = [] if self.related_cache.contains(query): urls = self.related_cache.get(query) print "hit related query: ", query else: time.sleep(self.google_delay) urls = self.google.searc...
[ "def", "search_related", "(", "self", ",", "url", ",", "k", ")", ":", "query", "=", "\"related:\"", "+", "url", "urls", "=", "[", "]", "if", "self", ".", "related_cache", ".", "contains", "(", "query", ")", ":", "urls", "=", "self", ".", "related_cac...
Return list of related urls using Google related search
[ "Return", "list", "of", "related", "urls", "using", "Google", "related", "search" ]
[ "\"\"\"\n Return list of related urls using Google related search\n \"\"\"", "\"\"\"\n urls = []\n if 'items' in results:\n for item in results['items']:\n urls.append(url_normalize(item['link']))\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "url", "type": null }, { "param": "k", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": []...
3c4323de320f00fe17f55aa8f18bcfdce1643e6d
andrewoconnell89/CS472_Project2
src/main.py
[ "MIT" ]
Python
runFromFile
null
def runFromFile(smm, fileName): '''Takes the SystemMemoryManager object and file name to run a prewritted set of commands Input--- smm : SystemMemoryManager object fileName : Name of file located in root directory ''' #Test the Sample output with open(fileName, 'r') as f: cu...
Takes the SystemMemoryManager object and file name to run a prewritted set of commands Input--- smm : SystemMemoryManager object fileName : Name of file located in root directory
Takes the SystemMemoryManager object and file name to run a prewritted set of commands Input smm : SystemMemoryManager object fileName : Name of file located in root directory
[ "Takes", "the", "SystemMemoryManager", "object", "and", "file", "name", "to", "run", "a", "prewritted", "set", "of", "commands", "Input", "smm", ":", "SystemMemoryManager", "object", "fileName", ":", "Name", "of", "file", "located", "in", "root", "directory" ]
def runFromFile(smm, fileName): with open(fileName, 'r') as f: cursor = str.strip(f.readline()) while cursor != '': if cursor == 'R': cursor = str.strip(f.readline()) tmpAddress = int(cursor, 16) smm.read(tmpAddress) elif cursor...
[ "def", "runFromFile", "(", "smm", ",", "fileName", ")", ":", "with", "open", "(", "fileName", ",", "'r'", ")", "as", "f", ":", "cursor", "=", "str", ".", "strip", "(", "f", ".", "readline", "(", ")", ")", "while", "cursor", "!=", "''", ":", "if",...
Takes the SystemMemoryManager object and file name to run a prewritted set of commands
[ "Takes", "the", "SystemMemoryManager", "object", "and", "file", "name", "to", "run", "a", "prewritted", "set", "of", "commands" ]
[ "'''Takes the SystemMemoryManager object and file name to run\n a prewritted set of commands\n\n Input---\n smm : SystemMemoryManager object\n fileName : Name of file located in root directory '''", "#Test the Sample output", "#Load up the next line from the file" ]
[ { "param": "smm", "type": null }, { "param": "fileName", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "smm", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fileName", "type": null, "docstring": null, "docstring_tokens"...
eb0953712813ba2a1eff1e70c360ae05f26e17c7
andrewoconnell89/CS472_Project2
src/CacheSim/SystemMemoryManager.py
[ "MIT" ]
Python
read
null
def read(self,address): '''Method returns the value in the given address. It will check to see if the address is a hit in the cache and if not load it into the cache. ''' print('\nREAD {0:x}'.format(address)) if self.cache.checkCache(address): print('HIT') ...
Method returns the value in the given address. It will check to see if the address is a hit in the cache and if not load it into the cache.
Method returns the value in the given address. It will check to see if the address is a hit in the cache and if not load it into the cache.
[ "Method", "returns", "the", "value", "in", "the", "given", "address", ".", "It", "will", "check", "to", "see", "if", "the", "address", "is", "a", "hit", "in", "the", "cache", "and", "if", "not", "load", "it", "into", "the", "cache", "." ]
def read(self,address): print('\nREAD {0:x}'.format(address)) if self.cache.checkCache(address): print('HIT') print('Value {0:x}'.format(self.cache.getAddressValue(address))) else: print('MISS') if self.cache.isDirty(address): cache...
[ "def", "read", "(", "self", ",", "address", ")", ":", "print", "(", "'\\nREAD {0:x}'", ".", "format", "(", "address", ")", ")", "if", "self", ".", "cache", ".", "checkCache", "(", "address", ")", ":", "print", "(", "'HIT'", ")", "print", "(", "'Value...
Method returns the value in the given address.
[ "Method", "returns", "the", "value", "in", "the", "given", "address", "." ]
[ "'''Method returns the value in the given address. It will\n check to see if the address is a hit in the cache and if not\n load it into the cache. '''", "#Write Back to main Memory if current row is dirty", "# print(\"CACHE DIRTY Writing back to MM\")" ]
[ { "param": "self", "type": null }, { "param": "address", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "address", "type": null, "docstring": null, "docstring_tokens"...
eb0953712813ba2a1eff1e70c360ae05f26e17c7
andrewoconnell89/CS472_Project2
src/CacheSim/SystemMemoryManager.py
[ "MIT" ]
Python
write
null
def write(self, address, value): '''Writes to memory at the specified address and given value. Will do some level of error checking, address: Must be in the range of the current memeory value: can not be larger than 8 bits''' print('\nWRITE {0:x}'.format(address)) if sel...
Writes to memory at the specified address and given value. Will do some level of error checking, address: Must be in the range of the current memeory value: can not be larger than 8 bits
Writes to memory at the specified address and given value. Will do some level of error checking, address: Must be in the range of the current memeory value: can not be larger than 8 bits
[ "Writes", "to", "memory", "at", "the", "specified", "address", "and", "given", "value", ".", "Will", "do", "some", "level", "of", "error", "checking", "address", ":", "Must", "be", "in", "the", "range", "of", "the", "current", "memeory", "value", ":", "c...
def write(self, address, value): print('\nWRITE {0:x}'.format(address)) if self.cache.checkCache(address): print('HIT') self.cache.updateData(address, value) print('Value {0:x}'.format(self.cache.getAddressValue(address))) else: print('MISS') ...
[ "def", "write", "(", "self", ",", "address", ",", "value", ")", ":", "print", "(", "'\\nWRITE {0:x}'", ".", "format", "(", "address", ")", ")", "if", "self", ".", "cache", ".", "checkCache", "(", "address", ")", ":", "print", "(", "'HIT'", ")", "self...
Writes to memory at the specified address and given value.
[ "Writes", "to", "memory", "at", "the", "specified", "address", "and", "given", "value", "." ]
[ "'''Writes to memory at the specified address and given value. Will do\n some level of error checking,\n address: Must be in the range of the current memeory\n value: can not be larger than 8 bits'''", "#Write Back to main Memory if current row is dirty" ]
[ { "param": "self", "type": null }, { "param": "address", "type": null }, { "param": "value", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "address", "type": null, "docstring": null, "docstring_tokens"...
aa6e6fc63b196f26ff08eb00615783dcdbb87204
andrewoconnell89/CS472_Project2
src/CacheSim/Cache.py
[ "MIT" ]
Python
checkCache
<not_specific>
def checkCache(self,address): '''Check the current Cache to see if there is a cache hit for a given memory address. The method will return back a boolean True or False True: There was a Cache hit False: There was a Cache Miss ''' #Get Slot number slotMASK = 0b0000111100...
Check the current Cache to see if there is a cache hit for a given memory address. The method will return back a boolean True or False True: There was a Cache hit False: There was a Cache Miss
Check the current Cache to see if there is a cache hit for a given memory address. The method will return back a boolean True or False True: There was a Cache hit False: There was a Cache Miss
[ "Check", "the", "current", "Cache", "to", "see", "if", "there", "is", "a", "cache", "hit", "for", "a", "given", "memory", "address", ".", "The", "method", "will", "return", "back", "a", "boolean", "True", "or", "False", "True", ":", "There", "was", "a"...
def checkCache(self,address): slotMASK = 0b000011110000 slot = (slotMASK & address) >> 4 tagMASK = 0b111100000000 tag = (tagMASK & address) >> 8 offsetMASK = 0b000000001111 offset = (offsetMASK & address) if self.slots[slot].valid == 1: if self.slots[s...
[ "def", "checkCache", "(", "self", ",", "address", ")", ":", "slotMASK", "=", "0b000011110000", "slot", "=", "(", "slotMASK", "&", "address", ")", ">>", "4", "tagMASK", "=", "0b111100000000", "tag", "=", "(", "tagMASK", "&", "address", ")", ">>", "8", "...
Check the current Cache to see if there is a cache hit for a given memory address.
[ "Check", "the", "current", "Cache", "to", "see", "if", "there", "is", "a", "cache", "hit", "for", "a", "given", "memory", "address", "." ]
[ "'''Check the current Cache to see if there is a cache hit for a given\n memory address. The method will return back a boolean True or False\n True: There was a Cache hit\n False: There was a Cache Miss '''", "#Get Slot number", "#print('Slot: ' + str(slot))", "#Get Tag", "#print('Tag:...
[ { "param": "self", "type": null }, { "param": "address", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "address", "type": null, "docstring": null, "docstring_tokens"...
aa6e6fc63b196f26ff08eb00615783dcdbb87204
andrewoconnell89/CS472_Project2
src/CacheSim/Cache.py
[ "MIT" ]
Python
isDirty
<not_specific>
def isDirty(self,address): '''checks to see if cacheRow is dirty or not''' #Get Slot number slotMASK = 0b000011110000 slot = (slotMASK & address) >> 4 return self.slots[slot].dirty
checks to see if cacheRow is dirty or not
checks to see if cacheRow is dirty or not
[ "checks", "to", "see", "if", "cacheRow", "is", "dirty", "or", "not" ]
def isDirty(self,address): slotMASK = 0b000011110000 slot = (slotMASK & address) >> 4 return self.slots[slot].dirty
[ "def", "isDirty", "(", "self", ",", "address", ")", ":", "slotMASK", "=", "0b000011110000", "slot", "=", "(", "slotMASK", "&", "address", ")", ">>", "4", "return", "self", ".", "slots", "[", "slot", "]", ".", "dirty" ]
checks to see if cacheRow is dirty or not
[ "checks", "to", "see", "if", "cacheRow", "is", "dirty", "or", "not" ]
[ "'''checks to see if cacheRow is dirty or not'''", "#Get Slot number" ]
[ { "param": "self", "type": null }, { "param": "address", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "address", "type": null, "docstring": null, "docstring_tokens"...
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
evaluate_versions
List[Dict[str, float]]
def evaluate_versions(class_: Any, dataset: Any, ckpt: AnyPath, is_graph: bool = True, logdir: AnyPath = 'Log', log_name: Optional[str] = 'default', deep: bool = True, metric_name: Optional[str] = None, sort_order: str = 'min')\ -> List[Dict[str, float]]: """Evaluate all checkpoints on...
Evaluate all checkpoints on x, y. Args: x: Model input. y: Target output. class_: Model class. logdir: Version directory to look underneath from. log_name: Name of log directory. deep: Search for version directory in depth for non-standard directory hierarchy. ...
Evaluate all checkpoints on x, y.
[ "Evaluate", "all", "checkpoints", "on", "x", "y", "." ]
def evaluate_versions(class_: Any, dataset: Any, ckpt: AnyPath, is_graph: bool = True, logdir: AnyPath = 'Log', log_name: Optional[str] = 'default', deep: bool = True, metric_name: Optional[str] = None, sort_order: str = 'min')\ -> List[Dict[str, float]]: return [evaluate_ckpt(class_=c...
[ "def", "evaluate_versions", "(", "class_", ":", "Any", ",", "dataset", ":", "Any", ",", "ckpt", ":", "AnyPath", ",", "is_graph", ":", "bool", "=", "True", ",", "logdir", ":", "AnyPath", "=", "'Log'", ",", "log_name", ":", "Optional", "[", "str", "]", ...
Evaluate all checkpoints on x, y.
[ "Evaluate", "all", "checkpoints", "on", "x", "y", "." ]
[ "\"\"\"Evaluate all checkpoints on x, y.\n\n Args:\n x: Model input.\n y: Target output.\n class_: Model class.\n\n logdir: Version directory to look underneath from.\n log_name: Name of log directory.\n deep: Search for version directory in depth for non-standard direct...
[ { "param": "class_", "type": "Any" }, { "param": "dataset", "type": "Any" }, { "param": "ckpt", "type": "AnyPath" }, { "param": "is_graph", "type": "bool" }, { "param": "logdir", "type": "AnyPath" }, { "param": "log_name", "type": "Optional[str]" ...
{ "returns": [], "raises": [], "params": [ { "identifier": "class_", "type": "Any", "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "dataset", "type": "Any", "docstring": null...
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
evaluate_ckpt
Dict[str, float]
def evaluate_ckpt(class_: Any, dataset: Any, ckpt: AnyPath, is_graph: bool = True, verbose: bool = False) -> Dict[str, float]: """Evaluate checkpoint on x, y. Args: is_graph: True if dataset is graph dataset: Dataset. class_: Model class. ckpt: Path to checkpoint file. v...
Evaluate checkpoint on x, y. Args: is_graph: True if dataset is graph dataset: Dataset. class_: Model class. ckpt: Path to checkpoint file. verbose: Verbose mode.
Evaluate checkpoint on x, y.
[ "Evaluate", "checkpoint", "on", "x", "y", "." ]
def evaluate_ckpt(class_: Any, dataset: Any, ckpt: AnyPath, is_graph: bool = True, verbose: bool = False) -> Dict[str, float]: model = class_.load_from_checkpoint(ckpt) log_dict = model.hparams.copy() pred = [] y = [] if is_graph: for input in dataset: input = torchg.data.batch.B...
[ "def", "evaluate_ckpt", "(", "class_", ":", "Any", ",", "dataset", ":", "Any", ",", "ckpt", ":", "AnyPath", ",", "is_graph", ":", "bool", "=", "True", ",", "verbose", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "float", "]", ":",...
Evaluate checkpoint on x, y.
[ "Evaluate", "checkpoint", "on", "x", "y", "." ]
[ "\"\"\"Evaluate checkpoint on x, y.\n\n Args:\n is_graph: True if dataset is graph\n dataset: Dataset.\n class_: Model class.\n ckpt: Path to checkpoint file.\n verbose: Verbose mode.\n \"\"\"" ]
[ { "param": "class_", "type": "Any" }, { "param": "dataset", "type": "Any" }, { "param": "ckpt", "type": "AnyPath" }, { "param": "is_graph", "type": "bool" }, { "param": "verbose", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "class_", "type": "Any", "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "dataset", "type": "Any", "docstring": null...
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
graph_saliency_map
torch.Tensor
def graph_saliency_map(model: Any, input: Union[torchg.data.data.Data, torchg.data.batch.Batch], method: str = 'norm')\ -> torch.Tensor: """Calculate saliency map on node features. There is no restriction on the model object but only its forward method, i.e. model.forward(input.x, input.edge_index,...
Calculate saliency map on node features. There is no restriction on the model object but only its forward method, i.e. model.forward(input.x, input.edge_index, input.batch) This function does not support edge features yet. Warning: The saliency map only propagates to the input level. If embedding is ...
Calculate saliency map on node features. There is no restriction on the model object but only its forward method, i.e. This function does not support edge features yet. The saliency map only propagates to the input level. If embedding is used, the graph saliency does not account for the embedding generator.
[ "Calculate", "saliency", "map", "on", "node", "features", ".", "There", "is", "no", "restriction", "on", "the", "model", "object", "but", "only", "its", "forward", "method", "i", ".", "e", ".", "This", "function", "does", "not", "support", "edge", "feature...
def graph_saliency_map(model: Any, input: Union[torchg.data.data.Data, torchg.data.batch.Batch], method: str = 'norm')\ -> torch.Tensor: input = input.clone() if type(input) == torchg.data.data.Data: batch = torch.zeros(input.x.shape[0], dtype=torch.long) else: batch = input.batch ...
[ "def", "graph_saliency_map", "(", "model", ":", "Any", ",", "input", ":", "Union", "[", "torchg", ".", "data", ".", "data", ".", "Data", ",", "torchg", ".", "data", ".", "batch", ".", "Batch", "]", ",", "method", ":", "str", "=", "'norm'", ")", "->...
Calculate saliency map on node features.
[ "Calculate", "saliency", "map", "on", "node", "features", "." ]
[ "\"\"\"Calculate saliency map on node features.\n\n There is no restriction on the model object but only its forward method, i.e.\n model.forward(input.x, input.edge_index, input.batch)\n\n This function does not support edge features yet.\n\n Warning: The saliency map only propagates to the input level...
[ { "param": "model", "type": "Any" }, { "param": "input", "type": "Union[torchg.data.data.Data, torchg.data.batch.Batch]" }, { "param": "method", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "model", "type": "Any", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "input", "type": "Union[torchg.data.data.Data, torchg.data.batch.Batch]"...
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
confusion_matrix_plot
Union[Figure, Axes]
def confusion_matrix_plot(cm: np.array, return_fig: bool = True) -> Union[Figure, Axes]: """Utility function get plot confusion matrix ax or figure. Args: cm: Confusion matrix in numpy.Array. return_fig: If true, return matplotlib.Figure. Otherwise, matplotlib.Axes """ display = Confusi...
Utility function get plot confusion matrix ax or figure. Args: cm: Confusion matrix in numpy.Array. return_fig: If true, return matplotlib.Figure. Otherwise, matplotlib.Axes
Utility function get plot confusion matrix ax or figure.
[ "Utility", "function", "get", "plot", "confusion", "matrix", "ax", "or", "figure", "." ]
def confusion_matrix_plot(cm: np.array, return_fig: bool = True) -> Union[Figure, Axes]: display = ConfusionMatrixDisplay(cm) _ = display.plot() plt.close() display.ax_.grid(False) if return_fig: return display.figure_ else: return display.ax_
[ "def", "confusion_matrix_plot", "(", "cm", ":", "np", ".", "array", ",", "return_fig", ":", "bool", "=", "True", ")", "->", "Union", "[", "Figure", ",", "Axes", "]", ":", "display", "=", "ConfusionMatrixDisplay", "(", "cm", ")", "_", "=", "display", "....
Utility function get plot confusion matrix ax or figure.
[ "Utility", "function", "get", "plot", "confusion", "matrix", "ax", "or", "figure", "." ]
[ "\"\"\"Utility function get plot confusion matrix ax or figure.\n\n Args:\n cm: Confusion matrix in numpy.Array.\n return_fig: If true, return matplotlib.Figure. Otherwise, matplotlib.Axes\n \"\"\"" ]
[ { "param": "cm", "type": "np.array" }, { "param": "return_fig", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cm", "type": "np.array", "docstring": "Confusion matrix in numpy.Array.", "docstring_tokens": [ "Confusion", "matrix", "in", "numpy", ".", "Array", "." ], "de...
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
dual_confusion_matrix_plot
Figure
def dual_confusion_matrix_plot(cms: List[np.array]) -> Figure: """Utility function to plot two confusion matrix in parallel. Suggest to use in train-val logging visualization. Args: cms: List of confusion matrix in numpy.Array """ fig, ax = plt.subplots(figsize=(12 * len(cms) * 12)) f...
Utility function to plot two confusion matrix in parallel. Suggest to use in train-val logging visualization. Args: cms: List of confusion matrix in numpy.Array
Utility function to plot two confusion matrix in parallel. Suggest to use in train-val logging visualization.
[ "Utility", "function", "to", "plot", "two", "confusion", "matrix", "in", "parallel", ".", "Suggest", "to", "use", "in", "train", "-", "val", "logging", "visualization", "." ]
def dual_confusion_matrix_plot(cms: List[np.array]) -> Figure: fig, ax = plt.subplots(figsize=(12 * len(cms) * 12)) for i, cm in enumerate(cms): ax = confusion_matrix_plot(cm, return_fig=False) if i == 0: fig.axes = [ax] else: fig.axes.append(ax) return fig
[ "def", "dual_confusion_matrix_plot", "(", "cms", ":", "List", "[", "np", ".", "array", "]", ")", "->", "Figure", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "(", "12", "*", "len", "(", "cms", ")", "*", "12", ")", ")",...
Utility function to plot two confusion matrix in parallel.
[ "Utility", "function", "to", "plot", "two", "confusion", "matrix", "in", "parallel", "." ]
[ "\"\"\"Utility function to plot two confusion matrix in parallel.\n\n Suggest to use in train-val logging visualization.\n\n Args:\n cms: List of confusion matrix in numpy.Array\n \"\"\"" ]
[ { "param": "cms", "type": "List[np.array]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cms", "type": "List[np.array]", "docstring": "List of confusion matrix in numpy.Array", "docstring_tokens": [ "List", "of", "confusion", "matrix", "in", "numpy", ".", ...
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
reg_corr_plot
plt.Figure
def reg_corr_plot(pred: Iterable, y: Iterable, full_range: bool = False) -> plt.Figure: """Utility function get seaborn jointplot between prediction and target values. Args: pred: Predicted values from model. y: Target values. full_range: If false, restrict plotted data points to true v...
Utility function get seaborn jointplot between prediction and target values. Args: pred: Predicted values from model. y: Target values. full_range: If false, restrict plotted data points to true value range.
Utility function get seaborn jointplot between prediction and target values.
[ "Utility", "function", "get", "seaborn", "jointplot", "between", "prediction", "and", "target", "values", "." ]
def reg_corr_plot(pred: Iterable, y: Iterable, full_range: bool = False) -> plt.Figure: df = pd.DataFrame(zip(pred, y), columns=['predicted value', 'true value']) if full_range: lim = (df.values.min(), df.values.max()) else: lim = (df['true value'].min(), df['true value'].max()) jg = sns...
[ "def", "reg_corr_plot", "(", "pred", ":", "Iterable", ",", "y", ":", "Iterable", ",", "full_range", ":", "bool", "=", "False", ")", "->", "plt", ".", "Figure", ":", "df", "=", "pd", ".", "DataFrame", "(", "zip", "(", "pred", ",", "y", ")", ",", "...
Utility function get seaborn jointplot between prediction and target values.
[ "Utility", "function", "get", "seaborn", "jointplot", "between", "prediction", "and", "target", "values", "." ]
[ "\"\"\"Utility function get seaborn jointplot between prediction and target values.\n\n Args:\n pred: Predicted values from model.\n y: Target values.\n full_range: If false, restrict plotted data points to true value range.\n \"\"\"", "# noinspection PyArgumentList" ]
[ { "param": "pred", "type": "Iterable" }, { "param": "y", "type": "Iterable" }, { "param": "full_range", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pred", "type": "Iterable", "docstring": "Predicted values from model.", "docstring_tokens": [ "Predicted", "values", "from", "model", "." ], "default": null, "is_option...
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
dual_reg_corr_plot
plt.Figure
def dual_reg_corr_plot(dual_data: Dict[str, Dict[str, torch.Tensor]], full_range: bool = False, margin_ratio: float = 1.1, **kwargs) -> plt.Figure: """Utility function to overlay seaborn jointplots of train and validation set. Args: dual_data: Dictionary of train and val set data...
Utility function to overlay seaborn jointplots of train and validation set. Args: dual_data: Dictionary of train and val set data in the format of {'train': {'pred': predictions, 'true': target values}, 'val': ...} full_range: If false, restrict plotted data points to true value range. ...
Utility function to overlay seaborn jointplots of train and validation set.
[ "Utility", "function", "to", "overlay", "seaborn", "jointplots", "of", "train", "and", "validation", "set", "." ]
def dual_reg_corr_plot(dual_data: Dict[str, Dict[str, torch.Tensor]], full_range: bool = False, margin_ratio: float = 1.1, **kwargs) -> plt.Figure: y_cat = torch.cat((dual_data['train']['y'], dual_data['val']['y']), axis=0) pred_cat = torch.cat((dual_data['train']['pred'], dual_data['val'...
[ "def", "dual_reg_corr_plot", "(", "dual_data", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", "]", ",", "full_range", ":", "bool", "=", "False", ",", "margin_ratio", ":", "float", "=", "1.1", ",", "**", "kwargs", ...
Utility function to overlay seaborn jointplots of train and validation set.
[ "Utility", "function", "to", "overlay", "seaborn", "jointplots", "of", "train", "and", "validation", "set", "." ]
[ "\"\"\"Utility function to overlay seaborn jointplots of train and validation set.\n\n Args:\n dual_data: Dictionary of train and val set data in the format of\n {'train': {'pred': predictions, 'true': target values}, 'val': ...}\n full_range: If false, restrict plotted data points to tr...
[ { "param": "dual_data", "type": "Dict[str, Dict[str, torch.Tensor]]" }, { "param": "full_range", "type": "bool" }, { "param": "margin_ratio", "type": "float" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dual_data", "type": "Dict[str, Dict[str, torch.Tensor]]", "docstring": "Dictionary of train and val set data in the format of\n{'train': {'pred': predictions, 'true': target values}, 'val': ...}", "docstring_tokens": [ ...
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
pdb2distance_map
torch.Tensor
def pdb2distance_map(pdb: AnyPath) -> torch.Tensor: """Get the distance map between CA atoms from pdb.""" pdb = Path(pdb) parser = PDB.PDBParser(PERMISSIVE=True, QUIET=True) structure = parser.get_structure(pdb.stem, pdb) chain = structure[0]['A'] coors = [] for resid in range(1, len(chain)...
Get the distance map between CA atoms from pdb.
Get the distance map between CA atoms from pdb.
[ "Get", "the", "distance", "map", "between", "CA", "atoms", "from", "pdb", "." ]
def pdb2distance_map(pdb: AnyPath) -> torch.Tensor: pdb = Path(pdb) parser = PDB.PDBParser(PERMISSIVE=True, QUIET=True) structure = parser.get_structure(pdb.stem, pdb) chain = structure[0]['A'] coors = [] for resid in range(1, len(chain)+1): residue = chain[resid] ca = [atom for ...
[ "def", "pdb2distance_map", "(", "pdb", ":", "AnyPath", ")", "->", "torch", ".", "Tensor", ":", "pdb", "=", "Path", "(", "pdb", ")", "parser", "=", "PDB", ".", "PDBParser", "(", "PERMISSIVE", "=", "True", ",", "QUIET", "=", "True", ")", "structure", "...
Get the distance map between CA atoms from pdb.
[ "Get", "the", "distance", "map", "between", "CA", "atoms", "from", "pdb", "." ]
[ "\"\"\"Get the distance map between CA atoms from pdb.\"\"\"" ]
[ { "param": "pdb", "type": "AnyPath" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pdb", "type": "AnyPath", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7295ff6d628e2ba1ed6fe0f05075773edb22f850
SimonKitSangChu/ProteinGNN
src/proteingnn/util.py
[ "MIT" ]
Python
plot_corr
None
def plot_corr(x: OrderedIterableType, y: OrderedIterableType, x_name: str, y_name: str, png: Optional[AnyPath] = None, rootdir: Optional[AnyPath] = None, **kwargs) -> None: """Plot x, y in seaborn jointplot Args: x: x-axis samples y: y-axis samples x_name: Name of x variab...
Plot x, y in seaborn jointplot Args: x: x-axis samples y: y-axis samples x_name: Name of x variable for plotting y_name: Name of y variable for plotting png: png filename. Default: {x_name}_{y_name}.png rootdir: Destination directory for png. kwargs: Keyword ...
Plot x, y in seaborn jointplot
[ "Plot", "x", "y", "in", "seaborn", "jointplot" ]
def plot_corr(x: OrderedIterableType, y: OrderedIterableType, x_name: str, y_name: str, png: Optional[AnyPath] = None, rootdir: Optional[AnyPath] = None, **kwargs) -> None: if type(x) is collections.OrderedDict: x = list(x.values()) if type(y) is collections.OrderedDict: y = list(y...
[ "def", "plot_corr", "(", "x", ":", "OrderedIterableType", ",", "y", ":", "OrderedIterableType", ",", "x_name", ":", "str", ",", "y_name", ":", "str", ",", "png", ":", "Optional", "[", "AnyPath", "]", "=", "None", ",", "rootdir", ":", "Optional", "[", "...
Plot x, y in seaborn jointplot
[ "Plot", "x", "y", "in", "seaborn", "jointplot" ]
[ "\"\"\"Plot x, y in seaborn jointplot\n\n Args:\n x: x-axis samples\n y: y-axis samples\n x_name: Name of x variable for plotting\n y_name: Name of y variable for plotting\n png: png filename. Default: {x_name}_{y_name}.png\n rootdir: Destination directory for png.\n ...
[ { "param": "x", "type": "OrderedIterableType" }, { "param": "y", "type": "OrderedIterableType" }, { "param": "x_name", "type": "str" }, { "param": "y_name", "type": "str" }, { "param": "png", "type": "Optional[AnyPath]" }, { "param": "rootdir", "ty...
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": "OrderedIterableType", "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "y", "type": "OrderedIterableType", ...
6ae2514ceb29af39aa19410451ee3792b4c54e32
SimonKitSangChu/ProteinGNN
src/proteingnn/example/data.py
[ "MIT" ]
Python
_log2en_rcsb_mismatch
List[int]
def _log2en_rcsb_mismatch(log2en: pd.DataFrame, seqrec_wt: Iterable) -> List[int]: """Find resid mismatch between log2en csv and rcsb fasta.""" mismatch_resid = [] for resid, (aa1, aa2) in enumerate(zip(seqrec_wt, log2en.wtAA), 1): if aa1 != aa2: mismatch_resid.append(resid) return ...
Find resid mismatch between log2en csv and rcsb fasta.
Find resid mismatch between log2en csv and rcsb fasta.
[ "Find", "resid", "mismatch", "between", "log2en", "csv", "and", "rcsb", "fasta", "." ]
def _log2en_rcsb_mismatch(log2en: pd.DataFrame, seqrec_wt: Iterable) -> List[int]: mismatch_resid = [] for resid, (aa1, aa2) in enumerate(zip(seqrec_wt, log2en.wtAA), 1): if aa1 != aa2: mismatch_resid.append(resid) return mismatch_resid
[ "def", "_log2en_rcsb_mismatch", "(", "log2en", ":", "pd", ".", "DataFrame", ",", "seqrec_wt", ":", "Iterable", ")", "->", "List", "[", "int", "]", ":", "mismatch_resid", "=", "[", "]", "for", "resid", ",", "(", "aa1", ",", "aa2", ")", "in", "enumerate"...
Find resid mismatch between log2en csv and rcsb fasta.
[ "Find", "resid", "mismatch", "between", "log2en", "csv", "and", "rcsb", "fasta", "." ]
[ "\"\"\"Find resid mismatch between log2en csv and rcsb fasta.\"\"\"" ]
[ { "param": "log2en", "type": "pd.DataFrame" }, { "param": "seqrec_wt", "type": "Iterable" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "log2en", "type": "pd.DataFrame", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "seqrec_wt", "type": "Iterable", "docstring": null, ...
6ae2514ceb29af39aa19410451ee3792b4c54e32
SimonKitSangChu/ProteinGNN
src/proteingnn/example/data.py
[ "MIT" ]
Python
bglb_Tm_pose2pdb
Dict
def bglb_Tm_pose2pdb(pdb : Optional[AnyPath] = None) -> Dict: """pose2pdb from Rosetta to rcsb resid mapping for 2jie""" if not globals()['PYROSETTA_INIT']: pyrosetta.init('-out::level 0') globals()['PYROSETTA_INIT'] = True if pdb is None: pdb = 'data/2jie.pdb' pose = pyrosetta...
pose2pdb from Rosetta to rcsb resid mapping for 2jie
pose2pdb from Rosetta to rcsb resid mapping for 2jie
[ "pose2pdb", "from", "Rosetta", "to", "rcsb", "resid", "mapping", "for", "2jie" ]
def bglb_Tm_pose2pdb(pdb : Optional[AnyPath] = None) -> Dict: if not globals()['PYROSETTA_INIT']: pyrosetta.init('-out::level 0') globals()['PYROSETTA_INIT'] = True if pdb is None: pdb = 'data/2jie.pdb' pose = pyrosetta.pose_from_pdb(str(pdb)) pose2pdb = {} for rosid in range...
[ "def", "bglb_Tm_pose2pdb", "(", "pdb", ":", "Optional", "[", "AnyPath", "]", "=", "None", ")", "->", "Dict", ":", "if", "not", "globals", "(", ")", "[", "'PYROSETTA_INIT'", "]", ":", "pyrosetta", ".", "init", "(", "'-out::level 0'", ")", "globals", "(", ...
pose2pdb from Rosetta to rcsb resid mapping for 2jie
[ "pose2pdb", "from", "Rosetta", "to", "rcsb", "resid", "mapping", "for", "2jie" ]
[ "\"\"\"pose2pdb from Rosetta to rcsb resid mapping for 2jie\"\"\"" ]
[ { "param": "pdb", "type": "Optional[AnyPath]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pdb", "type": "Optional[AnyPath]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4da4aa1f291c761f2d0efd793b8c27d33aba9a1c
SimonKitSangChu/ProteinGNN
src/proteingnn/example/model.py
[ "MIT" ]
Python
_get_layer
<not_specific>
def _get_layer(self, conv_name, in_channels, hidden_channels, gnorm_name, leakyrelu_slope, **kwargs): """Utility function to generate graph layer.""" layer = [ (getattr(gnn, conv_name)(in_channels, hidden_channels, **kwargs), 'x, edge_index -> x'), nn.LeakyReLU(leakyrelu_slope), ...
Utility function to generate graph layer.
Utility function to generate graph layer.
[ "Utility", "function", "to", "generate", "graph", "layer", "." ]
def _get_layer(self, conv_name, in_channels, hidden_channels, gnorm_name, leakyrelu_slope, **kwargs): layer = [ (getattr(gnn, conv_name)(in_channels, hidden_channels, **kwargs), 'x, edge_index -> x'), nn.LeakyReLU(leakyrelu_slope), ] if gnorm_name: layer.appen...
[ "def", "_get_layer", "(", "self", ",", "conv_name", ",", "in_channels", ",", "hidden_channels", ",", "gnorm_name", ",", "leakyrelu_slope", ",", "**", "kwargs", ")", ":", "layer", "=", "[", "(", "getattr", "(", "gnn", ",", "conv_name", ")", "(", "in_channel...
Utility function to generate graph layer.
[ "Utility", "function", "to", "generate", "graph", "layer", "." ]
[ "\"\"\"Utility function to generate graph layer.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "conv_name", "type": null }, { "param": "in_channels", "type": null }, { "param": "hidden_channels", "type": null }, { "param": "gnorm_name", "type": null }, { "param": "leakyrelu_slope", "type": null ...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "conv_name", "type": null, "docstring": null, "docstring_token...
467dcf71362f3dc94bcecee912eb69bca9306b13
SimonKitSangChu/ProteinGNN
src/proteingnn/model.py
[ "MIT" ]
Python
_concat_step_output
Dict[str, torch.Tensor]
def _concat_step_output(outputs: List[Dict[str, torch.Tensor]], dim: int = 0, skip: Iterable = ('loss',))\ -> Dict[str, torch.Tensor]: """Concatenate step output into single batch tensor. Args: outputs: Outputs from train/validation/test_step. dim: Dimension to be concatenated. ...
Concatenate step output into single batch tensor. Args: outputs: Outputs from train/validation/test_step. dim: Dimension to be concatenated. skip: Keys to be skipped in outputs.
Concatenate step output into single batch tensor.
[ "Concatenate", "step", "output", "into", "single", "batch", "tensor", "." ]
def _concat_step_output(outputs: List[Dict[str, torch.Tensor]], dim: int = 0, skip: Iterable = ('loss',))\ -> Dict[str, torch.Tensor]: data = {} for output in outputs: for key, var in output.items(): if key in skip: continue if key in data: ...
[ "def", "_concat_step_output", "(", "outputs", ":", "List", "[", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", "]", ",", "dim", ":", "int", "=", "0", ",", "skip", ":", "Iterable", "=", "(", "'loss'", ",", ")", ")", "->", "Dict", "[", "str"...
Concatenate step output into single batch tensor.
[ "Concatenate", "step", "output", "into", "single", "batch", "tensor", "." ]
[ "\"\"\"Concatenate step output into single batch tensor.\n\n Args:\n outputs: Outputs from train/validation/test_step.\n dim: Dimension to be concatenated.\n skip: Keys to be skipped in outputs.\n \"\"\"" ]
[ { "param": "outputs", "type": "List[Dict[str, torch.Tensor]]" }, { "param": "dim", "type": "int" }, { "param": "skip", "type": "Iterable" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "outputs", "type": "List[Dict[str, torch.Tensor]]", "docstring": "Outputs from train/validation/test_step.", "docstring_tokens": [ "Outputs", "from", "train", "/", "validation", "...
467dcf71362f3dc94bcecee912eb69bca9306b13
SimonKitSangChu/ProteinGNN
src/proteingnn/model.py
[ "MIT" ]
Python
gnn_module
<not_specific>
def gnn_module(in_channels: int, hidden_channels: int, n_layers: int, leakyrelu_slope: float, dropout: float = 0., gnn_class: Any = 'GCNConv', gnorm_class: Any = None, gnn_args: str = 'x, edge_index -> x', **kwargs): """Stremalined GNN submodule. Does not support edge convolution....
Stremalined GNN submodule. Does not support edge convolution. Args: in_channels: Input channel size. hidden_channels: Hidden channel size. n_layers: Number of layers. leakyrelu_slope: LeakyReLU slope. dropout: Dropout at the final layer. gnn_class: Conv name in ...
Stremalined GNN submodule. Does not support edge convolution.
[ "Stremalined", "GNN", "submodule", ".", "Does", "not", "support", "edge", "convolution", "." ]
def gnn_module(in_channels: int, hidden_channels: int, n_layers: int, leakyrelu_slope: float, dropout: float = 0., gnn_class: Any = 'GCNConv', gnorm_class: Any = None, gnn_args: str = 'x, edge_index -> x', **kwargs): assert n_layers >= 1 if type(gnn_class) == str: gnn_class...
[ "def", "gnn_module", "(", "in_channels", ":", "int", ",", "hidden_channels", ":", "int", ",", "n_layers", ":", "int", ",", "leakyrelu_slope", ":", "float", ",", "dropout", ":", "float", "=", "0.", ",", "gnn_class", ":", "Any", "=", "'GCNConv'", ",", "gno...
Stremalined GNN submodule.
[ "Stremalined", "GNN", "submodule", "." ]
[ "\"\"\"Stremalined GNN submodule.\n\n Does not support edge convolution.\n\n Args:\n in_channels: Input channel size.\n hidden_channels: Hidden channel size.\n n_layers: Number of layers.\n leakyrelu_slope: LeakyReLU slope.\n dropout: Dropout at the final layer.\n gnn...
[ { "param": "in_channels", "type": "int" }, { "param": "hidden_channels", "type": "int" }, { "param": "n_layers", "type": "int" }, { "param": "leakyrelu_slope", "type": "float" }, { "param": "dropout", "type": "float" }, { "param": "gnn_class", "typ...
{ "returns": [], "raises": [], "params": [ { "identifier": "in_channels", "type": "int", "docstring": "Input channel size.", "docstring_tokens": [ "Input", "channel", "size", "." ], "default": null, "is_optional": null }, { ...
467dcf71362f3dc94bcecee912eb69bca9306b13
SimonKitSangChu/ProteinGNN
src/proteingnn/model.py
[ "MIT" ]
Python
training_epoch_end
None
def training_epoch_end(self, outputs: Dict[str, Any], **kwargs) -> None: """Aggregate training step logging information and plot.""" if self.global_step == 0: self.dual_dict['train'] = None return if self.log_train: outputs = _concat_step_output(outputs) ...
Aggregate training step logging information and plot.
Aggregate training step logging information and plot.
[ "Aggregate", "training", "step", "logging", "information", "and", "plot", "." ]
def training_epoch_end(self, outputs: Dict[str, Any], **kwargs) -> None: if self.global_step == 0: self.dual_dict['train'] = None return if self.log_train: outputs = _concat_step_output(outputs) if self._regression: self._log_scaler_reg(out...
[ "def", "training_epoch_end", "(", "self", ",", "outputs", ":", "Dict", "[", "str", ",", "Any", "]", ",", "**", "kwargs", ")", "->", "None", ":", "if", "self", ".", "global_step", "==", "0", ":", "self", ".", "dual_dict", "[", "'train'", "]", "=", "...
Aggregate training step logging information and plot.
[ "Aggregate", "training", "step", "logging", "information", "and", "plot", "." ]
[ "\"\"\"Aggregate training step logging information and plot.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "outputs", "type": "Dict[str, Any]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "outputs", "type": "Dict[str, Any]", "docstring": null, "docst...
467dcf71362f3dc94bcecee912eb69bca9306b13
SimonKitSangChu/ProteinGNN
src/proteingnn/model.py
[ "MIT" ]
Python
validation_epoch_end
None
def validation_epoch_end(self, outputs: Dict[str, Any]) -> None: """Aggregate validation step logging information and plot.""" if self.global_step == 0: return outputs = _concat_step_output(outputs) if self._regression: self._log_scaler_reg(outputs['y'], outputs[...
Aggregate validation step logging information and plot.
Aggregate validation step logging information and plot.
[ "Aggregate", "validation", "step", "logging", "information", "and", "plot", "." ]
def validation_epoch_end(self, outputs: Dict[str, Any]) -> None: if self.global_step == 0: return outputs = _concat_step_output(outputs) if self._regression: self._log_scaler_reg(outputs['y'], outputs['pred'], stage='val') else: self._log_scaler_cls(ou...
[ "def", "validation_epoch_end", "(", "self", ",", "outputs", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "if", "self", ".", "global_step", "==", "0", ":", "return", "outputs", "=", "_concat_step_output", "(", "outputs", ")", "if", ...
Aggregate validation step logging information and plot.
[ "Aggregate", "validation", "step", "logging", "information", "and", "plot", "." ]
[ "\"\"\"Aggregate validation step logging information and plot.\"\"\"", "# overlay train and val visualization together" ]
[ { "param": "self", "type": null }, { "param": "outputs", "type": "Dict[str, Any]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "outputs", "type": "Dict[str, Any]", "docstring": null, "docst...
467dcf71362f3dc94bcecee912eb69bca9306b13
SimonKitSangChu/ProteinGNN
src/proteingnn/model.py
[ "MIT" ]
Python
_set_final_layer
<not_specific>
def _set_final_layer(self): """Set final layer depending on regression or classification task.""" if self._regression: return nn.LazyLinear(out_features=1) else: return nn.LazyLinear(out_features=self.num_classes)
Set final layer depending on regression or classification task.
Set final layer depending on regression or classification task.
[ "Set", "final", "layer", "depending", "on", "regression", "or", "classification", "task", "." ]
def _set_final_layer(self): if self._regression: return nn.LazyLinear(out_features=1) else: return nn.LazyLinear(out_features=self.num_classes)
[ "def", "_set_final_layer", "(", "self", ")", ":", "if", "self", ".", "_regression", ":", "return", "nn", ".", "LazyLinear", "(", "out_features", "=", "1", ")", "else", ":", "return", "nn", ".", "LazyLinear", "(", "out_features", "=", "self", ".", "num_cl...
Set final layer depending on regression or classification task.
[ "Set", "final", "layer", "depending", "on", "regression", "or", "classification", "task", "." ]
[ "\"\"\"Set final layer depending on regression or classification task.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
467dcf71362f3dc94bcecee912eb69bca9306b13
SimonKitSangChu/ProteinGNN
src/proteingnn/model.py
[ "MIT" ]
Python
_log_pr_curve
null
def _log_pr_curve(self, y, pred): """Log PR curve in classification.""" assert not self._regression tensorboard = self.logger.experiment for class_i in range(self.num_classes): tensorboard.add_pr_curve(f'PR_curve_class_{class_i}', pred[:, class_i], y[:, class_i], ...
Log PR curve in classification.
Log PR curve in classification.
[ "Log", "PR", "curve", "in", "classification", "." ]
def _log_pr_curve(self, y, pred): assert not self._regression tensorboard = self.logger.experiment for class_i in range(self.num_classes): tensorboard.add_pr_curve(f'PR_curve_class_{class_i}', pred[:, class_i], y[:, class_i], global_step=self.glob...
[ "def", "_log_pr_curve", "(", "self", ",", "y", ",", "pred", ")", ":", "assert", "not", "self", ".", "_regression", "tensorboard", "=", "self", ".", "logger", ".", "experiment", "for", "class_i", "in", "range", "(", "self", ".", "num_classes", ")", ":", ...
Log PR curve in classification.
[ "Log", "PR", "curve", "in", "classification", "." ]
[ "\"\"\"Log PR curve in classification.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "y", "type": null }, { "param": "pred", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "y", "type": null, "docstring": null, "docstring_tokens": [], ...
467dcf71362f3dc94bcecee912eb69bca9306b13
SimonKitSangChu/ProteinGNN
src/proteingnn/model.py
[ "MIT" ]
Python
_get_cm
<not_specific>
def _get_cm(self, y, pred): """Get confusion matrix in classification.""" assert not self._regression cm = mF.confusion_matrix(pred, y, num_classes=self.num_classes) return cm.clone().detach().cpu().numpy()
Get confusion matrix in classification.
Get confusion matrix in classification.
[ "Get", "confusion", "matrix", "in", "classification", "." ]
def _get_cm(self, y, pred): assert not self._regression cm = mF.confusion_matrix(pred, y, num_classes=self.num_classes) return cm.clone().detach().cpu().numpy()
[ "def", "_get_cm", "(", "self", ",", "y", ",", "pred", ")", ":", "assert", "not", "self", ".", "_regression", "cm", "=", "mF", ".", "confusion_matrix", "(", "pred", ",", "y", ",", "num_classes", "=", "self", ".", "num_classes", ")", "return", "cm", "....
Get confusion matrix in classification.
[ "Get", "confusion", "matrix", "in", "classification", "." ]
[ "\"\"\"Get confusion matrix in classification.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "y", "type": null }, { "param": "pred", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "y", "type": null, "docstring": null, "docstring_tokens": [], ...
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
create_dir
bool
def create_dir(path: AnyPath, overwrite: bool = False) -> bool: """Create (and overwrite) path directory.""" path = Path(path) if overwrite: shutil.rmtree(path) path.mkdir(parents=True, exist_ok=True) return True
Create (and overwrite) path directory.
Create (and overwrite) path directory.
[ "Create", "(", "and", "overwrite", ")", "path", "directory", "." ]
def create_dir(path: AnyPath, overwrite: bool = False) -> bool: path = Path(path) if overwrite: shutil.rmtree(path) path.mkdir(parents=True, exist_ok=True) return True
[ "def", "create_dir", "(", "path", ":", "AnyPath", ",", "overwrite", ":", "bool", "=", "False", ")", "->", "bool", ":", "path", "=", "Path", "(", "path", ")", "if", "overwrite", ":", "shutil", ".", "rmtree", "(", "path", ")", "path", ".", "mkdir", "...
Create (and overwrite) path directory.
[ "Create", "(", "and", "overwrite", ")", "path", "directory", "." ]
[ "\"\"\"Create (and overwrite) path directory.\"\"\"" ]
[ { "param": "path", "type": "AnyPath" }, { "param": "overwrite", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": "AnyPath", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "overwrite", "type": "bool", "docstring": null, "docstrin...
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
sort_atom_ids
List[AtomIDType]
def sort_atom_ids(atom_ids: Iterable[AtomIDType]) -> List[AtomIDType]: """Sort AtomIDs by (residue id, atom number)""" def atom_id2int(atom_id): return atom_id.rsd(), atom_id.atomno() return sorted(atom_ids, key=atom_id2int)
Sort AtomIDs by (residue id, atom number)
Sort AtomIDs by (residue id, atom number)
[ "Sort", "AtomIDs", "by", "(", "residue", "id", "atom", "number", ")" ]
def sort_atom_ids(atom_ids: Iterable[AtomIDType]) -> List[AtomIDType]: def atom_id2int(atom_id): return atom_id.rsd(), atom_id.atomno() return sorted(atom_ids, key=atom_id2int)
[ "def", "sort_atom_ids", "(", "atom_ids", ":", "Iterable", "[", "AtomIDType", "]", ")", "->", "List", "[", "AtomIDType", "]", ":", "def", "atom_id2int", "(", "atom_id", ")", ":", "return", "atom_id", ".", "rsd", "(", ")", ",", "atom_id", ".", "atomno", ...
Sort AtomIDs by (residue id, atom number)
[ "Sort", "AtomIDs", "by", "(", "residue", "id", "atom", "number", ")" ]
[ "\"\"\"Sort AtomIDs by (residue id, atom number)\"\"\"" ]
[ { "param": "atom_ids", "type": "Iterable[AtomIDType]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "atom_ids", "type": "Iterable[AtomIDType]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
filter
Dict[AtomIDType, AtomType]
def filter(self, pose: PoseType, atoms: Dict[AtomIDType, AtomType]) -> Dict[AtomIDType, AtomType]: """Filter by arbitrary method. Filter virtual atoms regardless.""" new_atoms = {} for atom_id, atom in atoms.items(): atom_name = atom_id2atom_name(atom_id, pose) if self.f...
Filter by arbitrary method. Filter virtual atoms regardless.
Filter by arbitrary method. Filter virtual atoms regardless.
[ "Filter", "by", "arbitrary", "method", ".", "Filter", "virtual", "atoms", "regardless", "." ]
def filter(self, pose: PoseType, atoms: Dict[AtomIDType, AtomType]) -> Dict[AtomIDType, AtomType]: new_atoms = {} for atom_id, atom in atoms.items(): atom_name = atom_id2atom_name(atom_id, pose) if self.filter_func(pose, atom_id, atom_name) and self.filter_virt(pose, atom_id, ato...
[ "def", "filter", "(", "self", ",", "pose", ":", "PoseType", ",", "atoms", ":", "Dict", "[", "AtomIDType", ",", "AtomType", "]", ")", "->", "Dict", "[", "AtomIDType", ",", "AtomType", "]", ":", "new_atoms", "=", "{", "}", "for", "atom_id", ",", "atom"...
Filter by arbitrary method.
[ "Filter", "by", "arbitrary", "method", "." ]
[ "\"\"\"Filter by arbitrary method. Filter virtual atoms regardless.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "pose", "type": "PoseType" }, { "param": "atoms", "type": "Dict[AtomIDType, AtomType]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pose", "type": "PoseType", "docstring": null, "docstring_toke...
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
_update_atomname2cat
bool
def _update_atomname2cat(self) -> bool: """Update atomname2cat upon change in atom_cats and atomtypes""" mis_atomtypes = set() if not self._atomtypes: return False self._atomname2cat = {} for key, values in self._atomtypes.items(): if key not in self._at...
Update atomname2cat upon change in atom_cats and atomtypes
Update atomname2cat upon change in atom_cats and atomtypes
[ "Update", "atomname2cat", "upon", "change", "in", "atom_cats", "and", "atomtypes" ]
def _update_atomname2cat(self) -> bool: mis_atomtypes = set() if not self._atomtypes: return False self._atomname2cat = {} for key, values in self._atomtypes.items(): if key not in self._atom_cats: mis_atomtypes.add(key) for value in va...
[ "def", "_update_atomname2cat", "(", "self", ")", "->", "bool", ":", "mis_atomtypes", "=", "set", "(", ")", "if", "not", "self", ".", "_atomtypes", ":", "return", "False", "self", ".", "_atomname2cat", "=", "{", "}", "for", "key", ",", "values", "in", "...
Update atomname2cat upon change in atom_cats and atomtypes
[ "Update", "atomname2cat", "upon", "change", "in", "atom_cats", "and", "atomtypes" ]
[ "\"\"\"Update atomname2cat upon change in atom_cats and atomtypes\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
featurize
List[Number]
def featurize(self, pose: PoseType, atom_id: AtomIDType) -> List[Number]: """Annotate node by atom category in one-hot encoding""" residue = pose.residue(atom_id.rsd()) atom_name = residue.atom_name(atom_id.atomno()) atom_name = atom_name.strip() atom_cat = self._atomname2cat[ato...
Annotate node by atom category in one-hot encoding
Annotate node by atom category in one-hot encoding
[ "Annotate", "node", "by", "atom", "category", "in", "one", "-", "hot", "encoding" ]
def featurize(self, pose: PoseType, atom_id: AtomIDType) -> List[Number]: residue = pose.residue(atom_id.rsd()) atom_name = residue.atom_name(atom_id.atomno()) atom_name = atom_name.strip() atom_cat = self._atomname2cat[atom_name] encoding = [1 if atom_cat == i else 0 ...
[ "def", "featurize", "(", "self", ",", "pose", ":", "PoseType", ",", "atom_id", ":", "AtomIDType", ")", "->", "List", "[", "Number", "]", ":", "residue", "=", "pose", ".", "residue", "(", "atom_id", ".", "rsd", "(", ")", ")", "atom_name", "=", "residu...
Annotate node by atom category in one-hot encoding
[ "Annotate", "node", "by", "atom", "category", "in", "one", "-", "hot", "encoding" ]
[ "\"\"\"Annotate node by atom category in one-hot encoding\"\"\"", "# index must start at 1" ]
[ { "param": "self", "type": null }, { "param": "pose", "type": "PoseType" }, { "param": "atom_id", "type": "AtomIDType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pose", "type": "PoseType", "docstring": null, "docstring_toke...
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
featurize
List[Number]
def featurize(self, pose: PoseType, atom_id: AtomIDType) -> List[Number]: """Annotate in accordance to sub-NodeFeaturizers and append outputs.""" features = [] for component in self.components: feature = component.featurize(pose, atom_id) features += feature if s...
Annotate in accordance to sub-NodeFeaturizers and append outputs.
Annotate in accordance to sub-NodeFeaturizers and append outputs.
[ "Annotate", "in", "accordance", "to", "sub", "-", "NodeFeaturizers", "and", "append", "outputs", "." ]
def featurize(self, pose: PoseType, atom_id: AtomIDType) -> List[Number]: features = [] for component in self.components: feature = component.featurize(pose, atom_id) features += feature if self.n_features: assert len(features) == self.n_features, \ ...
[ "def", "featurize", "(", "self", ",", "pose", ":", "PoseType", ",", "atom_id", ":", "AtomIDType", ")", "->", "List", "[", "Number", "]", ":", "features", "=", "[", "]", "for", "component", "in", "self", ".", "components", ":", "feature", "=", "componen...
Annotate in accordance to sub-NodeFeaturizers and append outputs.
[ "Annotate", "in", "accordance", "to", "sub", "-", "NodeFeaturizers", "and", "append", "outputs", "." ]
[ "\"\"\"Annotate in accordance to sub-NodeFeaturizers and append outputs.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "pose", "type": "PoseType" }, { "param": "atom_id", "type": "AtomIDType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pose", "type": "PoseType", "docstring": null, "docstring_toke...
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
featurize
Tuple[bool, List[Number]]
def featurize(self, pose: PoseType, atom_id1: AtomIDType, atom_id2: AtomIDType) -> Tuple[bool, List[Number]]: """Annotate in accordance to sub-EdgeFeaturizers and append outputs.""" is_edges = [] features = [] for featurizer in self.components: is_edge, feature = featurizer.f...
Annotate in accordance to sub-EdgeFeaturizers and append outputs.
Annotate in accordance to sub-EdgeFeaturizers and append outputs.
[ "Annotate", "in", "accordance", "to", "sub", "-", "EdgeFeaturizers", "and", "append", "outputs", "." ]
def featurize(self, pose: PoseType, atom_id1: AtomIDType, atom_id2: AtomIDType) -> Tuple[bool, List[Number]]: is_edges = [] features = [] for featurizer in self.components: is_edge, feature = featurizer.featurize(pose, atom_id1, atom_id2) is_edges.append(is_edge) ...
[ "def", "featurize", "(", "self", ",", "pose", ":", "PoseType", ",", "atom_id1", ":", "AtomIDType", ",", "atom_id2", ":", "AtomIDType", ")", "->", "Tuple", "[", "bool", ",", "List", "[", "Number", "]", "]", ":", "is_edges", "=", "[", "]", "features", ...
Annotate in accordance to sub-EdgeFeaturizers and append outputs.
[ "Annotate", "in", "accordance", "to", "sub", "-", "EdgeFeaturizers", "and", "append", "outputs", "." ]
[ "\"\"\"Annotate in accordance to sub-EdgeFeaturizers and append outputs.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "pose", "type": "PoseType" }, { "param": "atom_id1", "type": "AtomIDType" }, { "param": "atom_id2", "type": "AtomIDType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pose", "type": "PoseType", "docstring": null, "docstring_toke...
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
create_from_json
<not_specific>
def create_from_json(cls, path: Optional[AnyPath] = None): """Create instance from json configuration. See create_from_dict for details. """ if path is None: path = 'dataset/config.json' path = Path(path) if not path.exists(): raise FileNotFoundE...
Create instance from json configuration. See create_from_dict for details.
Create instance from json configuration. See create_from_dict for details.
[ "Create", "instance", "from", "json", "configuration", ".", "See", "create_from_dict", "for", "details", "." ]
def create_from_json(cls, path: Optional[AnyPath] = None): if path is None: path = 'dataset/config.json' path = Path(path) if not path.exists(): raise FileNotFoundError(f'Config json {path} not found.') with path.open('r') as f: config = json.load(f) ...
[ "def", "create_from_json", "(", "cls", ",", "path", ":", "Optional", "[", "AnyPath", "]", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "'dataset/config.json'", "path", "=", "Path", "(", "path", ")", "if", "not", "path", ".", "...
Create instance from json configuration.
[ "Create", "instance", "from", "json", "configuration", "." ]
[ "\"\"\"Create instance from json configuration.\n\n See create_from_dict for details.\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "path", "type": "Optional[AnyPath]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "path", "type": "Optional[AnyPath]", "docstring": null, "docstr...
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
process_graph
torchg.data.Data
def process_graph(self, pdb: AnyPath, pos_flag: bool = False, shared_pose: bool = False, data_attr_dict: Optional[Dict[str, Callable]] = None) -> torchg.data.Data: """Process pdb structure in pyrosetta and return sample data as undirected graph. Args: pdb: path to pdb....
Process pdb structure in pyrosetta and return sample data as undirected graph. Args: pdb: path to pdb. pos_flag: include pos (xyz) in node (default: False). shared_pose: assume all pdbs are the same and reuse pose to speed up data_attr_dict: functions to annotate...
Process pdb structure in pyrosetta and return sample data as undirected graph.
[ "Process", "pdb", "structure", "in", "pyrosetta", "and", "return", "sample", "data", "as", "undirected", "graph", "." ]
def process_graph(self, pdb: AnyPath, pos_flag: bool = False, shared_pose: bool = False, data_attr_dict: Optional[Dict[str, Callable]] = None) -> torchg.data.Data: if shared_pose and (self._shared_pose is None or self._shared_atoms is None): raise ValueError('shared_pose is Tru...
[ "def", "process_graph", "(", "self", ",", "pdb", ":", "AnyPath", ",", "pos_flag", ":", "bool", "=", "False", ",", "shared_pose", ":", "bool", "=", "False", ",", "data_attr_dict", ":", "Optional", "[", "Dict", "[", "str", ",", "Callable", "]", "]", "=",...
Process pdb structure in pyrosetta and return sample data as undirected graph.
[ "Process", "pdb", "structure", "in", "pyrosetta", "and", "return", "sample", "data", "as", "undirected", "graph", "." ]
[ "\"\"\"Process pdb structure in pyrosetta and return sample data as undirected graph.\n\n Args:\n pdb: path to pdb.\n pos_flag: include pos (xyz) in node (default: False).\n shared_pose: assume all pdbs are the same and reuse pose to speed up\n data_attr_dict: func...
[ { "param": "self", "type": null }, { "param": "pdb", "type": "AnyPath" }, { "param": "pos_flag", "type": "bool" }, { "param": "shared_pose", "type": "bool" }, { "param": "data_attr_dict", "type": "Optional[Dict[str, Callable]]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pdb", "type": "AnyPath", "docstring": "path to pdb.", "docstr...
2530326d9fd3b7cc9a7ffeafa4951c5eebedf18b
SimonKitSangChu/ProteinGNN
src/proteingnn/data.py
[ "MIT" ]
Python
create_dataset
None
def create_dataset(self, naming_func: Optional[Callable] = None, overwrite: bool = False, shared_pose: bool = False, n_processes: int = 1, data_attr_dict: Optional[Dict[str, Callable]] = None, **kwargs) -> None: """Iterate through, process and save all samples under...
Iterate through, process and save all samples under predataset.
Iterate through, process and save all samples under predataset.
[ "Iterate", "through", "process", "and", "save", "all", "samples", "under", "predataset", "." ]
def create_dataset(self, naming_func: Optional[Callable] = None, overwrite: bool = False, shared_pose: bool = False, n_processes: int = 1, data_attr_dict: Optional[Dict[str, Callable]] = None, **kwargs) -> None: create_dir(self.dataset_path, overwrite) input...
[ "def", "create_dataset", "(", "self", ",", "naming_func", ":", "Optional", "[", "Callable", "]", "=", "None", ",", "overwrite", ":", "bool", "=", "False", ",", "shared_pose", ":", "bool", "=", "False", ",", "n_processes", ":", "int", "=", "1", ",", "da...
Iterate through, process and save all samples under predataset.
[ "Iterate", "through", "process", "and", "save", "all", "samples", "under", "predataset", "." ]
[ "\"\"\"Iterate through, process and save all samples under predataset.\"\"\"", "# assume all poses the same to speed up" ]
[ { "param": "self", "type": null }, { "param": "naming_func", "type": "Optional[Callable]" }, { "param": "overwrite", "type": "bool" }, { "param": "shared_pose", "type": "bool" }, { "param": "n_processes", "type": "int" }, { "param": "data_attr_dict", ...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "naming_func", "type": "Optional[Callable]", "docstring": null, ...
16a32b625f1a0501c21533c844679d6749da121f
SimonKitSangChu/ProteinGNN
src/proteingnn/example/util.py
[ "MIT" ]
Python
visual_pssm_corr
CorrType
def visual_pssm_corr(rootdir: Optional[AnyPath] = None, exp_data: Optional[Union[Dict, OrderedDict]] = None, pssm: Optional[AnyPath] = None, **kwargs) -> CorrType: """Plot pssm to log2enrichment experiment data and evaluate correlations. Args: exp_data: Dictionary of mutant name an...
Plot pssm to log2enrichment experiment data and evaluate correlations. Args: exp_data: Dictionary of mutant name and experiment data, i.e. {mut_name: y} pssm: Path to pssm file from psiblast. rootdir: Destination directory for exp-pssm.png. kwargs: Keyword arguments for seaborn.join...
Plot pssm to log2enrichment experiment data and evaluate correlations.
[ "Plot", "pssm", "to", "log2enrichment", "experiment", "data", "and", "evaluate", "correlations", "." ]
def visual_pssm_corr(rootdir: Optional[AnyPath] = None, exp_data: Optional[Union[Dict, OrderedDict]] = None, pssm: Optional[AnyPath] = None, **kwargs) -> CorrType: if exp_data is None: exp_data = read_log2en(return_type='OrderedDict') dpssm = pssm2D(pssm=pssm, return_type='OrderedDi...
[ "def", "visual_pssm_corr", "(", "rootdir", ":", "Optional", "[", "AnyPath", "]", "=", "None", ",", "exp_data", ":", "Optional", "[", "Union", "[", "Dict", ",", "OrderedDict", "]", "]", "=", "None", ",", "pssm", ":", "Optional", "[", "AnyPath", "]", "="...
Plot pssm to log2enrichment experiment data and evaluate correlations.
[ "Plot", "pssm", "to", "log2enrichment", "experiment", "data", "and", "evaluate", "correlations", "." ]
[ "\"\"\"Plot pssm to log2enrichment experiment data and evaluate correlations.\n\n Args:\n exp_data: Dictionary of mutant name and experiment data, i.e. {mut_name: y}\n pssm: Path to pssm file from psiblast.\n rootdir: Destination directory for exp-pssm.png.\n kwargs: Keyword arguments...
[ { "param": "rootdir", "type": "Optional[AnyPath]" }, { "param": "exp_data", "type": "Optional[Union[Dict, OrderedDict]]" }, { "param": "pssm", "type": "Optional[AnyPath]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "rootdir", "type": "Optional[AnyPath]", "docstring": "Destination directory for exp-pssm.png.", "docstring_tokens": [ "Destination", "directory", "for", "exp", "-", "pssm", ...
16a32b625f1a0501c21533c844679d6749da121f
SimonKitSangChu/ProteinGNN
src/proteingnn/example/util.py
[ "MIT" ]
Python
visual_esm_corr
Union[CorrType, Dict[str, CorrType]]
def visual_esm_corr(methods: Optional[Union[str, Tuple]] = None, rootdir: Optional[AnyPath] = None, pdb_name: str = '1gnx', exp_data: Optional[Union[Dict, OrderedDict]] = None, esm_dir: Optional[AnyPath] = None, **kwargs) -> Union[CorrType, Dict[str, CorrType]]: """(Legacy) p...
(Legacy) plot esm to log2enrichment experiment data and evaluate correlations. Args: exp_data: Dictionary of mutant name and experiment data, i.e. {mut_name: y} pssm: Path to pssm file from psiblast. rootdir: Destination directory for exp-pssm.png. kwargs: Keyword arguments for seab...
(Legacy) plot esm to log2enrichment experiment data and evaluate correlations.
[ "(", "Legacy", ")", "plot", "esm", "to", "log2enrichment", "experiment", "data", "and", "evaluate", "correlations", "." ]
def visual_esm_corr(methods: Optional[Union[str, Tuple]] = None, rootdir: Optional[AnyPath] = None, pdb_name: str = '1gnx', exp_data: Optional[Union[Dict, OrderedDict]] = None, esm_dir: Optional[AnyPath] = None, **kwargs) -> Union[CorrType, Dict[str, CorrType]]: esm_dir = Pat...
[ "def", "visual_esm_corr", "(", "methods", ":", "Optional", "[", "Union", "[", "str", ",", "Tuple", "]", "]", "=", "None", ",", "rootdir", ":", "Optional", "[", "AnyPath", "]", "=", "None", ",", "pdb_name", ":", "str", "=", "'1gnx'", ",", "exp_data", ...
(Legacy) plot esm to log2enrichment experiment data and evaluate correlations.
[ "(", "Legacy", ")", "plot", "esm", "to", "log2enrichment", "experiment", "data", "and", "evaluate", "correlations", "." ]
[ "\"\"\"(Legacy) plot esm to log2enrichment experiment data and evaluate correlations.\n\n Args:\n exp_data: Dictionary of mutant name and experiment data, i.e. {mut_name: y}\n pssm: Path to pssm file from psiblast.\n rootdir: Destination directory for exp-pssm.png.\n kwargs: Keyword a...
[ { "param": "methods", "type": "Optional[Union[str, Tuple]]" }, { "param": "rootdir", "type": "Optional[AnyPath]" }, { "param": "pdb_name", "type": "str" }, { "param": "exp_data", "type": "Optional[Union[Dict, OrderedDict]]" }, { "param": "esm_dir", "type": "Op...
{ "returns": [], "raises": [], "params": [ { "identifier": "methods", "type": "Optional[Union[str, Tuple]]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "rootdir", "type": "Optional[AnyPath]", ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
checkYear
<not_specific>
def checkYear(year): ''' Deturmines if the integer entered is a leap year or not. Para: year: Integer Returns: isLeap: Boolean ''' if year % 4 == 0: if year % 100 == 0 and year % 400 == 0: isLeap = True elif year % 100 != ...
Deturmines if the integer entered is a leap year or not. Para: year: Integer Returns: isLeap: Boolean
Deturmines if the integer entered is a leap year or not. Para: year: Integer
[ "Deturmines", "if", "the", "integer", "entered", "is", "a", "leap", "year", "or", "not", ".", "Para", ":", "year", ":", "Integer" ]
def checkYear(year): if year % 4 == 0: if year % 100 == 0 and year % 400 == 0: isLeap = True elif year % 100 != 0: isLeap = True else: isLeap = False else: isLeap = False return isLeap
[ "def", "checkYear", "(", "year", ")", ":", "if", "year", "%", "4", "==", "0", ":", "if", "year", "%", "100", "==", "0", "and", "year", "%", "400", "==", "0", ":", "isLeap", "=", "True", "elif", "year", "%", "100", "!=", "0", ":", "isLeap", "=...
Deturmines if the integer entered is a leap year or not.
[ "Deturmines", "if", "the", "integer", "entered", "is", "a", "leap", "year", "or", "not", "." ]
[ "'''\r\n Deturmines if the integer entered is a leap year or not. \r\n\r\n Para:\r\n year: Integer \r\n\r\n Returns:\r\n isLeap: Boolean \r\n\r\n '''" ]
[ { "param": "year", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "isLeap" } ], "raises": [], "params": [ { "identifier": "year", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": nul...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
checkDay
<not_specific>
def checkDay(day, month, isLeap): ''' Checks the day value entered and compares it against several checks to deturmine if the date is acceptable. ie. Correct number of days in a given month and checked feb leap year. Para: Day: Integer Month: Integer isLea...
Checks the day value entered and compares it against several checks to deturmine if the date is acceptable. ie. Correct number of days in a given month and checked feb leap year. Para: Day: Integer Month: Integer isLeap: Boolean Returns: Bo...
Checks the day value entered and compares it against several checks to deturmine if the date is acceptable. ie. Correct number of days in a given month and checked feb leap year. Integer Month: Integer isLeap: Boolean
[ "Checks", "the", "day", "value", "entered", "and", "compares", "it", "against", "several", "checks", "to", "deturmine", "if", "the", "date", "is", "acceptable", ".", "ie", ".", "Correct", "number", "of", "days", "in", "a", "given", "month", "and", "checked...
def checkDay(day, month, isLeap): days31 = [1, 3, 5, 7, 8, 10, 12] days30 = [4, 6, 9, 11] days28 = [2] if month in days31: if day in range(1, 32): return True else: return False elif month in days30: if day in range(1, 31): return True ...
[ "def", "checkDay", "(", "day", ",", "month", ",", "isLeap", ")", ":", "days31", "=", "[", "1", ",", "3", ",", "5", ",", "7", ",", "8", ",", "10", ",", "12", "]", "days30", "=", "[", "4", ",", "6", ",", "9", ",", "11", "]", "days28", "=", ...
Checks the day value entered and compares it against several checks to deturmine if the date is acceptable.
[ "Checks", "the", "day", "value", "entered", "and", "compares", "it", "against", "several", "checks", "to", "deturmine", "if", "the", "date", "is", "acceptable", "." ]
[ "'''\r\n Checks the day value entered and compares it against several checks to deturmine if the date is \r\n acceptable. ie. Correct number of days in a given month and checked feb leap year. \r\n\r\n Para:\r\n Day: Integer\r\n Month: Integer \r\n isLeap: Boolean\r\n\r\n ...
[ { "param": "day", "type": null }, { "param": "month", "type": null }, { "param": "isLeap", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "day", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
confirmDate
<not_specific>
def confirmDate(day, month, year): ''' Uses the funtions checkYear(year), checkMonth(month) and checkDay(day, month, isLeap) to validate the calendar date for any integer of length 8 given. Para: Day: Integer Month: Integer Year: Integer Returns: ...
Uses the funtions checkYear(year), checkMonth(month) and checkDay(day, month, isLeap) to validate the calendar date for any integer of length 8 given. Para: Day: Integer Month: Integer Year: Integer Returns: Boolean
Uses the funtions checkYear(year), checkMonth(month) and checkDay(day, month, isLeap) to validate the calendar date for any integer of length 8 given.
[ "Uses", "the", "funtions", "checkYear", "(", "year", ")", "checkMonth", "(", "month", ")", "and", "checkDay", "(", "day", "month", "isLeap", ")", "to", "validate", "the", "calendar", "date", "for", "any", "integer", "of", "length", "8", "given", "." ]
def confirmDate(day, month, year): isLeap = checkYear(year) confirmMonth = checkMonth(month) confirmDay = checkDay(day, month, isLeap) if confirmMonth == True and confirmDay == True: return True else: return False
[ "def", "confirmDate", "(", "day", ",", "month", ",", "year", ")", ":", "isLeap", "=", "checkYear", "(", "year", ")", "confirmMonth", "=", "checkMonth", "(", "month", ")", "confirmDay", "=", "checkDay", "(", "day", ",", "month", ",", "isLeap", ")", "if"...
Uses the funtions checkYear(year), checkMonth(month) and checkDay(day, month, isLeap) to validate the calendar date for any integer of length 8 given.
[ "Uses", "the", "funtions", "checkYear", "(", "year", ")", "checkMonth", "(", "month", ")", "and", "checkDay", "(", "day", "month", "isLeap", ")", "to", "validate", "the", "calendar", "date", "for", "any", "integer", "of", "length", "8", "given", "." ]
[ "'''\r\n Uses the funtions checkYear(year), checkMonth(month) and checkDay(day, month, isLeap) to validate the \r\n calendar date for any integer of length 8 given. \r\n\r\n Para:\r\n Day: Integer\r\n Month: Integer \r\n Year: Integer\r\n\r\n Returns: \r\n Boo...
[ { "param": "day", "type": null }, { "param": "month", "type": null }, { "param": "year", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "day", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
welcomeBanner
<not_specific>
def welcomeBanner(): ''' Welcome string that is printed upon the launch of the program. Para: None Returns: None ''' print('************************************\n'+ \ "WELCOME TO EPL's SUMMER READING CLUB\n"+ \ '**********************...
Welcome string that is printed upon the launch of the program. Para: None Returns: None
Welcome string that is printed upon the launch of the program. Para: None
[ "Welcome", "string", "that", "is", "printed", "upon", "the", "launch", "of", "the", "program", ".", "Para", ":", "None" ]
def welcomeBanner(): print('************************************\n'+ \ "WELCOME TO EPL's SUMMER READING CLUB\n"+ \ '************************************') return
[ "def", "welcomeBanner", "(", ")", ":", "print", "(", "'************************************\\n'", "+", "\"WELCOME TO EPL's SUMMER READING CLUB\\n\"", "+", "'************************************'", ")", "return" ]
Welcome string that is printed upon the launch of the program.
[ "Welcome", "string", "that", "is", "printed", "upon", "the", "launch", "of", "the", "program", "." ]
[ "'''\r\n Welcome string that is printed upon the launch of the program.\r\n\r\n Para:\r\n None\r\n \r\n Returns:\r\n None\r\n '''" ]
[]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [], "outlier_params": [], "others": [] }
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
openFile
<not_specific>
def openFile(fileName): ''' Opens a text file from the same directory as the .py and returns a list. Para: fileName: String Returns: fList: List ''' with open(fileName) as f: fList = f.readlines() return fList
Opens a text file from the same directory as the .py and returns a list. Para: fileName: String Returns: fList: List
Opens a text file from the same directory as the .py and returns a list. Para: fileName: String
[ "Opens", "a", "text", "file", "from", "the", "same", "directory", "as", "the", ".", "py", "and", "returns", "a", "list", ".", "Para", ":", "fileName", ":", "String" ]
def openFile(fileName): with open(fileName) as f: fList = f.readlines() return fList
[ "def", "openFile", "(", "fileName", ")", ":", "with", "open", "(", "fileName", ")", "as", "f", ":", "fList", "=", "f", ".", "readlines", "(", ")", "return", "fList" ]
Opens a text file from the same directory as the .py and returns a list.
[ "Opens", "a", "text", "file", "from", "the", "same", "directory", "as", "the", ".", "py", "and", "returns", "a", "list", "." ]
[ "'''\r\n Opens a text file from the same directory as the .py and returns a list.\r\n\r\n Para:\r\n fileName: String \r\n \r\n Returns:\r\n fList: List\r\n '''" ]
[ { "param": "fileName", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "fList" } ], "raises": [], "params": [ { "identifier": "fileName", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
fixDate
<not_specific>
def fixDate(date): ''' Converts the string value a participants birthdate into a string of numbers. ie. Feb == 02, will also convert single digit values into double digit, ie 2 becomes 02. Will return a string of the following format, 'YYYYMMDD' Para: date: string Retur...
Converts the string value a participants birthdate into a string of numbers. ie. Feb == 02, will also convert single digit values into double digit, ie 2 becomes 02. Will return a string of the following format, 'YYYYMMDD' Para: date: string Returns: date: stri...
Converts the string value a participants birthdate into a string of numbers. ie. Feb == 02, will also convert single digit values into double digit, ie 2 becomes 02. Will return a string of the following format, 'YYYYMMDD' string
[ "Converts", "the", "string", "value", "a", "participants", "birthdate", "into", "a", "string", "of", "numbers", ".", "ie", ".", "Feb", "==", "02", "will", "also", "convert", "single", "digit", "values", "into", "double", "digit", "ie", "2", "becomes", "02"...
def fixDate(date): months = ['Jan', "Feb", 'Mar', \ 'Apr', 'May', 'Jun', \ 'Jul', 'Aug', 'Sep', \ 'Oct', 'Nov', 'Dec'] date = date.split() date[0] = str(months.index(date[0]) + 1 ) if len(date[0]) < 2: date[0] = '0' + str(date[0]) if len(str(date[1])) < 2:...
[ "def", "fixDate", "(", "date", ")", ":", "months", "=", "[", "'Jan'", ",", "\"Feb\"", ",", "'Mar'", ",", "'Apr'", ",", "'May'", ",", "'Jun'", ",", "'Jul'", ",", "'Aug'", ",", "'Sep'", ",", "'Oct'", ",", "'Nov'", ",", "'Dec'", "]", "date", "=", "d...
Converts the string value a participants birthdate into a string of numbers.
[ "Converts", "the", "string", "value", "a", "participants", "birthdate", "into", "a", "string", "of", "numbers", "." ]
[ "'''\r\n Converts the string value a participants birthdate into a string of numbers. ie. Feb == 02, \r\n will also convert single digit values into double digit, ie 2 becomes 02. Will return a string \r\n of the following format, 'YYYYMMDD'\r\n\r\n Para: \r\n date: string\r\n\r\n Returns:...
[ { "param": "date", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "date" } ], "raises": [], "params": [ { "identifier": "date", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
validateLcn
<not_specific>
def validateLcn(lcn, poeple): ''' "Validate Library Card Number" will check if the lcn matchs with a participant in the participant dictionary. Returns True or False Para: lcn: string people: dictionary Returns: boolean ''' if lcn in poe...
"Validate Library Card Number" will check if the lcn matchs with a participant in the participant dictionary. Returns True or False Para: lcn: string people: dictionary Returns: boolean
"Validate Library Card Number" will check if the lcn matchs with a participant in the participant dictionary. Returns True or False string people: dictionary
[ "\"", "Validate", "Library", "Card", "Number", "\"", "will", "check", "if", "the", "lcn", "matchs", "with", "a", "participant", "in", "the", "participant", "dictionary", ".", "Returns", "True", "or", "False", "string", "people", ":", "dictionary" ]
def validateLcn(lcn, poeple): if lcn in poeple: return True else: return False
[ "def", "validateLcn", "(", "lcn", ",", "poeple", ")", ":", "if", "lcn", "in", "poeple", ":", "return", "True", "else", ":", "return", "False" ]
"Validate Library Card Number" will check if the lcn matchs with a participant in the participant dictionary.
[ "\"", "Validate", "Library", "Card", "Number", "\"", "will", "check", "if", "the", "lcn", "matchs", "with", "a", "participant", "in", "the", "participant", "dictionary", "." ]
[ "'''\r\n \"Validate Library Card Number\" will check if the lcn matchs with a participant in the \r\n participant dictionary. Returns True or False\r\n\r\n Para:\r\n lcn: string\r\n people: dictionary\r\n \r\n Returns:\r\n boolean\r\n '''" ]
[ { "param": "lcn", "type": null }, { "param": "poeple", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "lcn", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
option1
<not_specific>
def option1(people): ''' Option one of the main function. Will aquire a library card number (LCN) and validate it. Upon Validation Will ask the user for a book name and a branch name. Once given LCN, book name, and branch the function will append (write) the information seperated by '#' to the end ...
Option one of the main function. Will aquire a library card number (LCN) and validate it. Upon Validation Will ask the user for a book name and a branch name. Once given LCN, book name, and branch the function will append (write) the information seperated by '#' to the end of the text file consisting o...
Option one of the main function. Will aquire a library card number (LCN) and validate it. Upon Validation Will ask the user for a book name and a branch name. Once given LCN, book name, and branch the function will append (write) the information seperated by '#' to the end of the text file consisting of books read. di...
[ "Option", "one", "of", "the", "main", "function", ".", "Will", "aquire", "a", "library", "card", "number", "(", "LCN", ")", "and", "validate", "it", ".", "Upon", "Validation", "Will", "ask", "the", "user", "for", "a", "book", "name", "and", "a", "branc...
def option1(people): lcn = input('Card number: ') while validateLcn(lcn, people) == False: lcn = input('Invalid library card number. Card number: ') book = input('Book title: ') branch = input('Library branch: ') with open('booksRead.txt', 'a') as f: f.write('\n') f.write(('{...
[ "def", "option1", "(", "people", ")", ":", "lcn", "=", "input", "(", "'Card number: '", ")", "while", "validateLcn", "(", "lcn", ",", "people", ")", "==", "False", ":", "lcn", "=", "input", "(", "'Invalid library card number. Card number: '", ")", "book", "=...
Option one of the main function.
[ "Option", "one", "of", "the", "main", "function", "." ]
[ "'''\r\n Option one of the main function. Will aquire a library card number (LCN) and validate it. Upon Validation \r\n Will ask the user for a book name and a branch name. Once given LCN, book name, and branch the function will\r\n append (write) the information seperated by '#' to the end of the text fil...
[ { "param": "people", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "people", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
option2
<not_specific>
def option2(people, levels, read, year, month, day, theme): ''' Validates a given LCN and fetchs the birth date of the given participant. Given their birth date, computes their age. Then parses through books read dictionary using the LCN given and counts and prints the books they read (while adding...
Validates a given LCN and fetchs the birth date of the given participant. Given their birth date, computes their age. Then parses through books read dictionary using the LCN given and counts and prints the books they read (while adding a * to the book name after the 23rd character in the book name). Wi...
Validates a given LCN and fetchs the birth date of the given participant. Given their birth date, computes their age. Then parses through books read dictionary using the LCN given and counts and prints the books they read (while adding a * to the book name after the 23rd character in the book name). With the number of ...
[ "Validates", "a", "given", "LCN", "and", "fetchs", "the", "birth", "date", "of", "the", "given", "participant", ".", "Given", "their", "birth", "date", "computes", "their", "age", ".", "Then", "parses", "through", "books", "read", "dictionary", "using", "the...
def option2(people, levels, read, year, month, day, theme): lcn = input('Library Card Number: ') if validateLcn(lcn, people) == False: return print('Invalid library card number.') born = people[lcn][2] count = 0 fName, lName = firstName(people[lcn][0]).upper(), lastName(people[lcn][1]).upper...
[ "def", "option2", "(", "people", ",", "levels", ",", "read", ",", "year", ",", "month", ",", "day", ",", "theme", ")", ":", "lcn", "=", "input", "(", "'Library Card Number: '", ")", "if", "validateLcn", "(", "lcn", ",", "people", ")", "==", "False", ...
Validates a given LCN and fetchs the birth date of the given participant.
[ "Validates", "a", "given", "LCN", "and", "fetchs", "the", "birth", "date", "of", "the", "given", "participant", "." ]
[ "'''\r\n Validates a given LCN and fetchs the birth date of the given participant. Given their birth date, computes\r\n their age. Then parses through books read dictionary using the LCN given and counts and prints the books \r\n they read (while adding a * to the book name after the 23rd character in the ...
[ { "param": "people", "type": null }, { "param": "levels", "type": null }, { "param": "read", "type": null }, { "param": "year", "type": null }, { "param": "month", "type": null }, { "param": "day", "type": null }, { "param": "theme", "t...
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "people", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
fixCurrentDate
<not_specific>
def fixCurrentDate(year, month, day): ''' Converts the current date into the acceptable string layout. ie YYYY MM DD. Will change single digit strings to double digit. ie. 6 becomes 06, for both the month and day. Para: year: integer month: integer day: inte...
Converts the current date into the acceptable string layout. ie YYYY MM DD. Will change single digit strings to double digit. ie. 6 becomes 06, for both the month and day. Para: year: integer month: integer day: integer Returns: string: strin...
Converts the current date into the acceptable string layout. ie YYYY MM DD. Will change single digit strings to double digit. ie. 6 becomes 06, for both the month and day.
[ "Converts", "the", "current", "date", "into", "the", "acceptable", "string", "layout", ".", "ie", "YYYY", "MM", "DD", ".", "Will", "change", "single", "digit", "strings", "to", "double", "digit", ".", "ie", ".", "6", "becomes", "06", "for", "both", "the"...
def fixCurrentDate(year, month, day): year = str(year) month = str(month) day = str(day) if len(month) < 2: month = '0' + str(month) if len(day) < 2: day = '0' + str(day) string = ' '.join([year, month, day]) return string
[ "def", "fixCurrentDate", "(", "year", ",", "month", ",", "day", ")", ":", "year", "=", "str", "(", "year", ")", "month", "=", "str", "(", "month", ")", "day", "=", "str", "(", "day", ")", "if", "len", "(", "month", ")", "<", "2", ":", "month", ...
Converts the current date into the acceptable string layout.
[ "Converts", "the", "current", "date", "into", "the", "acceptable", "string", "layout", "." ]
[ "'''\r\n Converts the current date into the acceptable string layout. ie YYYY MM DD. Will change single digit \r\n strings to double digit. ie. 6 becomes 06, for both the month and day.\r\n\r\n Para:\r\n year: integer\r\n month: integer\r\n day: integer\r\n\r\n Returns:\...
[ { "param": "year", "type": null }, { "param": "month", "type": null }, { "param": "day", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "string" } ], "raises": [], "params": [ { "identifier": "year", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": nul...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
firstName
<not_specific>
def firstName(string): ''' If a participants first name is larger then 8 characters long, will cut it off at 7 characters long plus a asterisk. ie ARCHIBALD becomes ARCHIBA*. Para: string: string Returns: string: string ''' if len(string) > 8: ...
If a participants first name is larger then 8 characters long, will cut it off at 7 characters long plus a asterisk. ie ARCHIBALD becomes ARCHIBA*. Para: string: string Returns: string: string
If a participants first name is larger then 8 characters long, will cut it off at 7 characters long plus a asterisk. ie ARCHIBALD becomes ARCHIBA*. string
[ "If", "a", "participants", "first", "name", "is", "larger", "then", "8", "characters", "long", "will", "cut", "it", "off", "at", "7", "characters", "long", "plus", "a", "asterisk", ".", "ie", "ARCHIBALD", "becomes", "ARCHIBA", "*", ".", "string" ]
def firstName(string): if len(string) > 8: string = string[:7] + '*' return string
[ "def", "firstName", "(", "string", ")", ":", "if", "len", "(", "string", ")", ">", "8", ":", "string", "=", "string", "[", ":", "7", "]", "+", "'*'", "return", "string" ]
If a participants first name is larger then 8 characters long, will cut it off at 7 characters long plus a asterisk.
[ "If", "a", "participants", "first", "name", "is", "larger", "then", "8", "characters", "long", "will", "cut", "it", "off", "at", "7", "characters", "long", "plus", "a", "asterisk", "." ]
[ "'''\r\n If a participants first name is larger then 8 characters long, will cut it off at 7 characters long plus \r\n a asterisk. ie ARCHIBALD becomes ARCHIBA*.\r\n\r\n Para:\r\n string: string\r\n\r\n Returns:\r\n string: string\r\n '''" ]
[ { "param": "string", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "string" } ], "raises": [], "params": [ { "identifier": "string", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": n...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
lastName
<not_specific>
def lastName(string): ''' Given a last name, returns the first letter of the last name Para: string: string Returns: string: string ''' string = string[0] return string
Given a last name, returns the first letter of the last name Para: string: string Returns: string: string
Given a last name, returns the first letter of the last name Para: string: string
[ "Given", "a", "last", "name", "returns", "the", "first", "letter", "of", "the", "last", "name", "Para", ":", "string", ":", "string" ]
def lastName(string): string = string[0] return string
[ "def", "lastName", "(", "string", ")", ":", "string", "=", "string", "[", "0", "]", "return", "string" ]
Given a last name, returns the first letter of the last name Para: string: string
[ "Given", "a", "last", "name", "returns", "the", "first", "letter", "of", "the", "last", "name", "Para", ":", "string", ":", "string" ]
[ "''' \r\n Given a last name, returns the first letter of the last name\r\n\r\n Para:\r\n string: string\r\n\r\n Returns: \r\n string: string \r\n\r\n '''" ]
[ { "param": "string", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "string" } ], "raises": [], "params": [ { "identifier": "string", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": n...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
chooseLevel
<not_specific>
def chooseLevel(levels): ''' Given the levels dictionary, will parse through the key values (THEMES) and print them for the user to select from. The user will then choose one of the printed themes for the session. Will check to see if the chosen theme (the one the user entered) is valid. Pa...
Given the levels dictionary, will parse through the key values (THEMES) and print them for the user to select from. The user will then choose one of the printed themes for the session. Will check to see if the chosen theme (the one the user entered) is valid. Para: levels: dictiona...
Given the levels dictionary, will parse through the key values (THEMES) and print them for the user to select from. The user will then choose one of the printed themes for the session. Will check to see if the chosen theme (the one the user entered) is valid. dictionary
[ "Given", "the", "levels", "dictionary", "will", "parse", "through", "the", "key", "values", "(", "THEMES", ")", "and", "print", "them", "for", "the", "user", "to", "select", "from", ".", "The", "user", "will", "then", "choose", "one", "of", "the", "print...
def chooseLevel(levels): print('\nThemes to select from:') for key, value in levels.items(): print('- {}'.format(key)) theme = input('Please pick a theme from the list above: ') while theme not in levels: theme = input('Invalid entry. Please pick a theme from the list above: ') retur...
[ "def", "chooseLevel", "(", "levels", ")", ":", "print", "(", "'\\nThemes to select from:'", ")", "for", "key", ",", "value", "in", "levels", ".", "items", "(", ")", ":", "print", "(", "'- {}'", ".", "format", "(", "key", ")", ")", "theme", "=", "input"...
Given the levels dictionary, will parse through the key values (THEMES) and print them for the user to select from.
[ "Given", "the", "levels", "dictionary", "will", "parse", "through", "the", "key", "values", "(", "THEMES", ")", "and", "print", "them", "for", "the", "user", "to", "select", "from", "." ]
[ "'''\r\n Given the levels dictionary, will parse through the key values (THEMES) and print them for the user to \r\n select from. The user will then choose one of the printed themes for the session. Will check to see \r\n if the chosen theme (the one the user entered) is valid.\r\n\r\n Para:\r\n ...
[ { "param": "levels", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "theme" } ], "raises": [], "params": [ { "identifier": "levels", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": nu...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
option3
<not_specific>
def option3(people, read, year, month, day): ''' With values given by functions createAgeGroups() and topRead() (functions that split participants into age groups and returns the highest rank per age group) prints all the data into a formated UI / box for the user to read from. Para: ...
With values given by functions createAgeGroups() and topRead() (functions that split participants into age groups and returns the highest rank per age group) prints all the data into a formated UI / box for the user to read from. Para: people: dictionary read: dictionary ...
With values given by functions createAgeGroups() and topRead() (functions that split participants into age groups and returns the highest rank per age group) prints all the data into a formated UI / box for the user to read from.
[ "With", "values", "given", "by", "functions", "createAgeGroups", "()", "and", "topRead", "()", "(", "functions", "that", "split", "participants", "into", "age", "groups", "and", "returns", "the", "highest", "rank", "per", "age", "group", ")", "prints", "all", ...
def option3(people, read, year, month, day): fiveU, sixToNine, tenO = createAgeGroups(people, read, year, month, day) winner5, total5 = topRead(fiveU, read) winner9, total9 = topRead(sixToNine, read) winner13, total13 = topRead(tenO, read) print('+=============+==================+============+') ...
[ "def", "option3", "(", "people", ",", "read", ",", "year", ",", "month", ",", "day", ")", ":", "fiveU", ",", "sixToNine", ",", "tenO", "=", "createAgeGroups", "(", "people", ",", "read", ",", "year", ",", "month", ",", "day", ")", "winner5", ",", "...
With values given by functions createAgeGroups() and topRead() (functions that split participants into age groups and returns the highest rank per age group) prints all the data into a formated UI / box for the user to read from.
[ "With", "values", "given", "by", "functions", "createAgeGroups", "()", "and", "topRead", "()", "(", "functions", "that", "split", "participants", "into", "age", "groups", "and", "returns", "the", "highest", "rank", "per", "age", "group", ")", "prints", "all", ...
[ "'''\r\n With values given by functions createAgeGroups() and topRead() (functions that split participants into age groups and \r\n returns the highest rank per age group) prints all the data into a formated UI / box for the user to read from. \r\n\r\n Para: \r\n people: dictionary\r\n ...
[ { "param": "people", "type": null }, { "param": "read", "type": null }, { "param": "year", "type": null }, { "param": "month", "type": null }, { "param": "day", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "people", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
topRead
<not_specific>
def topRead(bracket, read): ''' For each participant in a given age bracket, calulates the participant who read the most number of books, checks if there is a tie, and if no participants read any books returns N/A. returns the topReader (winner), and the TOTAL number of books the age bracket read. ...
For each participant in a given age bracket, calulates the participant who read the most number of books, checks if there is a tie, and if no participants read any books returns N/A. returns the topReader (winner), and the TOTAL number of books the age bracket read. Primarily used in the option 3 funti...
For each participant in a given age bracket, calulates the participant who read the most number of books, checks if there is a tie, and if no participants read any books returns N/A. returns the topReader (winner), and the TOTAL number of books the age bracket read. Primarily used in the option 3 funtion. Whenever a ne...
[ "For", "each", "participant", "in", "a", "given", "age", "bracket", "calulates", "the", "participant", "who", "read", "the", "most", "number", "of", "books", "checks", "if", "there", "is", "a", "tie", "and", "if", "no", "participants", "read", "any", "book...
def topRead(bracket, read): bracketCount = 0 topReader = 'N/A' record = 0 for lcn in bracket: personalCount = 0 try: for book in read[lcn]: personalCount += 1 bracketCount += 1 if personalCount > record: record =...
[ "def", "topRead", "(", "bracket", ",", "read", ")", ":", "bracketCount", "=", "0", "topReader", "=", "'N/A'", "record", "=", "0", "for", "lcn", "in", "bracket", ":", "personalCount", "=", "0", "try", ":", "for", "book", "in", "read", "[", "lcn", "]",...
For each participant in a given age bracket, calulates the participant who read the most number of books, checks if there is a tie, and if no participants read any books returns N/A.
[ "For", "each", "participant", "in", "a", "given", "age", "bracket", "calulates", "the", "participant", "who", "read", "the", "most", "number", "of", "books", "checks", "if", "there", "is", "a", "tie", "and", "if", "no", "participants", "read", "any", "book...
[ "'''\r\n For each participant in a given age bracket, calulates the participant who read the most number of books, checks if there is\r\n a tie, and if no participants read any books returns N/A. returns the topReader (winner), and the TOTAL number of books \r\n the age bracket read. Primarily used in the ...
[ { "param": "bracket", "type": null }, { "param": "read", "type": null } ]
{ "returns": [ { "docstring": "string\nbracketCount: integer", "docstring_tokens": [ "string", "bracketCount", ":", "integer" ], "type": "topReader" } ], "raises": [], "params": [ { "identifier": "bracket", "type": null, "docs...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
createAgeGroups
<not_specific>
def createAgeGroups(people, read, year, month, day): ''' Parses through the participants dictionary and sort the participants into sub dictionaries by to their age relative to the entered date. Uses the getAge() function to get the age, then sorts the participants into the respective dictionaries Be...
Parses through the participants dictionary and sort the participants into sub dictionaries by to their age relative to the entered date. Uses the getAge() function to get the age, then sorts the participants into the respective dictionaries Below are index's for easier readability debugging. ...
Parses through the participants dictionary and sort the participants into sub dictionaries by to their age relative to the entered date. Uses the getAge() function to get the age, then sorts the participants into the respective dictionaries Below are index's for easier readability debugging. peopleKey = ID ...
[ "Parses", "through", "the", "participants", "dictionary", "and", "sort", "the", "participants", "into", "sub", "dictionaries", "by", "to", "their", "age", "relative", "to", "the", "entered", "date", ".", "Uses", "the", "getAge", "()", "function", "to", "get", ...
def createAgeGroups(people, read, year, month, day): fiveU, sixToNine, tenO = {}, {}, {} for key in people: age = getAge(year, month, day, people[key][2]) if age <= 5: fiveU[key] = [people[key][0], people[key][1]] elif age <= 9: sixToNine[key] = [people[key][0], ...
[ "def", "createAgeGroups", "(", "people", ",", "read", ",", "year", ",", "month", ",", "day", ")", ":", "fiveU", ",", "sixToNine", ",", "tenO", "=", "{", "}", ",", "{", "}", ",", "{", "}", "for", "key", "in", "people", ":", "age", "=", "getAge", ...
Parses through the participants dictionary and sort the participants into sub dictionaries by to their age relative to the entered date.
[ "Parses", "through", "the", "participants", "dictionary", "and", "sort", "the", "participants", "into", "sub", "dictionaries", "by", "to", "their", "age", "relative", "to", "the", "entered", "date", "." ]
[ "'''\r\n Parses through the participants dictionary and sort the participants into sub dictionaries by to their age relative to the\r\n entered date. Uses the getAge() function to get the age, then sorts the participants into the respective dictionaries\r\n Below are index's for easier readability debuggin...
[ { "param": "people", "type": null }, { "param": "read", "type": null }, { "param": "year", "type": null }, { "param": "month", "type": null }, { "param": "day", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "fiveU" } ], "raises": [], "params": [ { "identifier": "people", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": nu...
d9a4f7c19caed4f87930727f0532908e42128df9
Napkinzz/Library-Reading-Club-
Assignment1.py
[ "Apache-2.0" ]
Python
main
<not_specific>
def main(): ''' Main function that sets the variables, opens the files, creates the dictionaries needed to run the program. Asks the user for the date, theme and the option they want to do. Para: None Returns: None ''' welcomeBanner() year, ...
Main function that sets the variables, opens the files, creates the dictionaries needed to run the program. Asks the user for the date, theme and the option they want to do. Para: None Returns: None
Main function that sets the variables, opens the files, creates the dictionaries needed to run the program. Asks the user for the date, theme and the option they want to do. None
[ "Main", "function", "that", "sets", "the", "variables", "opens", "the", "files", "creates", "the", "dictionaries", "needed", "to", "run", "the", "program", ".", "Asks", "the", "user", "for", "the", "date", "theme", "and", "the", "option", "they", "want", "...
def main(): welcomeBanner() year, month, day = getDate(1) while confirmDate(day, month, year) == False: year, month, day = getDate(2) levels = levelDict(openFile('clubLevels.txt')) theme = chooseLevel(levels) quit = False while not quit: people = participantDict(openFile('par...
[ "def", "main", "(", ")", ":", "welcomeBanner", "(", ")", "year", ",", "month", ",", "day", "=", "getDate", "(", "1", ")", "while", "confirmDate", "(", "day", ",", "month", ",", "year", ")", "==", "False", ":", "year", ",", "month", ",", "day", "=...
Main function that sets the variables, opens the files, creates the dictionaries needed to run the program.
[ "Main", "function", "that", "sets", "the", "variables", "opens", "the", "files", "creates", "the", "dictionaries", "needed", "to", "run", "the", "program", "." ]
[ "'''\r\n Main function that sets the variables, opens the files, creates the dictionaries needed to run the program. Asks the user \r\n for the date, theme and the option they want to do. \r\n\r\n Para:\r\n None\r\n \r\n Returns: \r\n None\r\n\r\n '''" ]
[]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [], "outlier_params": [], "others": [] }
f17d0548dcac9a826d24572a6f90a9172ccbc1d2
aNOOBisTheGod/upgraded-discord-bot
cogs/help.py
[ "MIT" ]
Python
help
null
async def help(self, ctx, *input): """Shows all modules of that bot""" prefix = '!!' version = '0.0.5' owner = 661157502989238282 owner_name = 'aNOOBis#1420' if not input: try: owner = ctx.guild.get_member(owner).mention ...
Shows all modules of that bot
Shows all modules of that bot
[ "Shows", "all", "modules", "of", "that", "bot" ]
async def help(self, ctx, *input): prefix = '!!' version = '0.0.5' owner = 661157502989238282 owner_name = 'aNOOBis#1420' if not input: try: owner = ctx.guild.get_member(owner).mention except AttributeError as e: owner = own...
[ "async", "def", "help", "(", "self", ",", "ctx", ",", "*", "input", ")", ":", "prefix", "=", "'!!'", "version", "=", "'0.0.5'", "owner", "=", "661157502989238282", "owner_name", "=", "'aNOOBis#1420'", "if", "not", "input", ":", "try", ":", "owner", "=", ...
Shows all modules of that bot
[ "Shows", "all", "modules", "of", "that", "bot" ]
[ "\"\"\"Shows all modules of that bot\"\"\"", "# sending reply embed using our own function defined above\r" ]
[ { "param": "self", "type": null }, { "param": "ctx", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ctx", "type": null, "docstring": null, "docstring_tokens": []...
5c9e89e0ef2ec9cfd5e89ba37e6d6b486d72d06f
Este1le/gbhpo
gbopt/acquisition_functions/base_acquisition.py
[ "MIT" ]
Python
update
null
def update(self, graph): """ This method will be called if the graph is updated. Parameters ---------- graph: GraphObject The graph defined by nodes and adjacency matrix. """ self.graph = graph
This method will be called if the graph is updated. Parameters ---------- graph: GraphObject The graph defined by nodes and adjacency matrix.
This method will be called if the graph is updated. Parameters GraphObject The graph defined by nodes and adjacency matrix.
[ "This", "method", "will", "be", "called", "if", "the", "graph", "is", "updated", ".", "Parameters", "GraphObject", "The", "graph", "defined", "by", "nodes", "and", "adjacency", "matrix", "." ]
def update(self, graph): self.graph = graph
[ "def", "update", "(", "self", ",", "graph", ")", ":", "self", ".", "graph", "=", "graph" ]
This method will be called if the graph is updated.
[ "This", "method", "will", "be", "called", "if", "the", "graph", "is", "updated", "." ]
[ "\"\"\"\n This method will be called if the graph is updated.\n\n Parameters\n ----------\n graph: GraphObject\n The graph defined by nodes and adjacency matrix.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "graph", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "graph", "type": null, "docstring": null, "docstring_tokens": ...
5c9e89e0ef2ec9cfd5e89ba37e6d6b486d72d06f
Este1le/gbhpo
gbopt/acquisition_functions/base_acquisition.py
[ "MIT" ]
Python
compute
null
def compute(self, i): """ Computes the acquisition function value for a given point x. This function has to be overwritten in a derived class. Parameters ---------- i: int The index of input point where the acquisition function should be evaluated. ""...
Computes the acquisition function value for a given point x. This function has to be overwritten in a derived class. Parameters ---------- i: int The index of input point where the acquisition function should be evaluated.
Computes the acquisition function value for a given point x. This function has to be overwritten in a derived class. Parameters int The index of input point where the acquisition function should be evaluated.
[ "Computes", "the", "acquisition", "function", "value", "for", "a", "given", "point", "x", ".", "This", "function", "has", "to", "be", "overwritten", "in", "a", "derived", "class", ".", "Parameters", "int", "The", "index", "of", "input", "point", "where", "...
def compute(self, i): pass
[ "def", "compute", "(", "self", ",", "i", ")", ":", "pass" ]
Computes the acquisition function value for a given point x.
[ "Computes", "the", "acquisition", "function", "value", "for", "a", "given", "point", "x", "." ]
[ "\"\"\"\n Computes the acquisition function value for a given point x.\n This function has to be overwritten in a derived class.\n\n Parameters\n ----------\n i: int\n The index of input point where the acquisition function should be evaluated.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "i", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "i", "type": null, "docstring": null, "docstring_tokens": [], ...
e4423d4cee9ce8c30c1340d6d07d4c83457912d8
Este1le/gbhpo
gbopt/solver/gbopt.py
[ "MIT" ]
Python
choose_next
<not_specific>
def choose_next(self, graph): """ Suggests a new point to evaluate. Parameters ---------- graph: GraphObject The graph defined by nodes and an adjacency matrix. Returns ------- np.ndarray(1,D) Suggested point """ i...
Suggests a new point to evaluate. Parameters ---------- graph: GraphObject The graph defined by nodes and an adjacency matrix. Returns ------- np.ndarray(1,D) Suggested point
Suggests a new point to evaluate. Parameters GraphObject The graph defined by nodes and an adjacency matrix. Returns
[ "Suggests", "a", "new", "point", "to", "evaluate", ".", "Parameters", "GraphObject", "The", "graph", "defined", "by", "nodes", "and", "an", "adjacency", "matrix", ".", "Returns" ]
def choose_next(self, graph): if self.graph.lids is None: lid = int(self.initial_design(graph.X, 1, rng=self.rng)) else: logger.info("Label propagation through the graph...") t = time.time() self.label_prop_alg.label_propagate(graph) logger.inf...
[ "def", "choose_next", "(", "self", ",", "graph", ")", ":", "if", "self", ".", "graph", ".", "lids", "is", "None", ":", "lid", "=", "int", "(", "self", ".", "initial_design", "(", "graph", ".", "X", ",", "1", ",", "rng", "=", "self", ".", "rng", ...
Suggests a new point to evaluate.
[ "Suggests", "a", "new", "point", "to", "evaluate", "." ]
[ "\"\"\"\n Suggests a new point to evaluate.\n\n Parameters\n ----------\n graph: GraphObject\n The graph defined by nodes and an adjacency matrix.\n\n Returns\n -------\n np.ndarray(1,D)\n Suggested point\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "graph", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "graph", "type": null, "docstring": null, "docstring_tokens": ...
5be0d1f9fa195223465d6630c1d94453a25697b4
Este1le/gbhpo
gbopt/acquisition_functions/eif.py
[ "MIT" ]
Python
_normalize
<not_specific>
def _normalize(self): """ Scale Y to the range [0,1]. Set the max labeled point as a pivot, and set its value to 1. Scale the predictions of unlabeled points that is greater than pivot to [0.5, 1]. Scale the predictions of unlabeled points that it smaller than pivot to [0. 0.5). ...
Scale Y to the range [0,1]. Set the max labeled point as a pivot, and set its value to 1. Scale the predictions of unlabeled points that is greater than pivot to [0.5, 1]. Scale the predictions of unlabeled points that it smaller than pivot to [0. 0.5).
Scale Y to the range [0,1]. Set the max labeled point as a pivot, and set its value to 1. Scale the predictions of unlabeled points that is greater than pivot to [0.5, 1]. Scale the predictions of unlabeled points that it smaller than pivot to [0.
[ "Scale", "Y", "to", "the", "range", "[", "0", "1", "]", ".", "Set", "the", "max", "labeled", "point", "as", "a", "pivot", "and", "set", "its", "value", "to", "1", ".", "Scale", "the", "predictions", "of", "unlabeled", "points", "that", "is", "greater...
def _normalize(self): lids = self.graph.lids Y = self.graph.Y n = Y.shape[0] uids = np.delete(np.arange(Y.shape[0]), lids) YU = Y[uids] YL = Y[lids] Y_norm = np.zeros((n)) pivot = max(YL) pivot_id = lids[np.argmax(YL)] Y_norm[pivot_id] = 1 ...
[ "def", "_normalize", "(", "self", ")", ":", "lids", "=", "self", ".", "graph", ".", "lids", "Y", "=", "self", ".", "graph", ".", "Y", "n", "=", "Y", ".", "shape", "[", "0", "]", "uids", "=", "np", ".", "delete", "(", "np", ".", "arange", "(",...
Scale Y to the range [0,1].
[ "Scale", "Y", "to", "the", "range", "[", "0", "1", "]", "." ]
[ "\"\"\"\n Scale Y to the range [0,1].\n Set the max labeled point as a pivot, and set its value to 1.\n Scale the predictions of unlabeled points that is greater than pivot to [0.5, 1].\n Scale the predictions of unlabeled points that it smaller than pivot to [0. 0.5).\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5be0d1f9fa195223465d6630c1d94453a25697b4
Este1le/gbhpo
gbopt/acquisition_functions/eif.py
[ "MIT" ]
Python
compute
<not_specific>
def compute(self, i): """ Computes the EIF value for a given point x. Parameters ---------- i: int The index of input point where the acquisition function should be evaluated. Returns ------- np.ndarray(1,1) Expected influence of ...
Computes the EIF value for a given point x. Parameters ---------- i: int The index of input point where the acquisition function should be evaluated. Returns ------- np.ndarray(1,1) Expected influence of x.
Computes the EIF value for a given point x. Parameters int The index of input point where the acquisition function should be evaluated. Returns np.ndarray(1,1) Expected influence of x.
[ "Computes", "the", "EIF", "value", "for", "a", "given", "point", "x", ".", "Parameters", "int", "The", "index", "of", "input", "point", "where", "the", "acquisition", "function", "should", "be", "evaluated", ".", "Returns", "np", ".", "ndarray", "(", "1", ...
def compute(self, i): Y_norm = self._normalize() Y = self.graph.Y self.graph.Y = Y_norm y = self.graph.Y[i] self.graph.update(i, 0) self.label_prop_alg.label_propagate(self.graph) uids = np.delete(np.arange(self.graph.Y.shape[0]), self.graph.lids) YU0 = se...
[ "def", "compute", "(", "self", ",", "i", ")", ":", "Y_norm", "=", "self", ".", "_normalize", "(", ")", "Y", "=", "self", ".", "graph", ".", "Y", "self", ".", "graph", ".", "Y", "=", "Y_norm", "y", "=", "self", ".", "graph", ".", "Y", "[", "i"...
Computes the EIF value for a given point x. Parameters
[ "Computes", "the", "EIF", "value", "for", "a", "given", "point", "x", ".", "Parameters" ]
[ "\"\"\"\n Computes the EIF value for a given point x.\n\n Parameters\n ----------\n i: int\n The index of input point where the acquisition function should be evaluated.\n\n Returns\n -------\n np.ndarray(1,1)\n Expected influence of x.\n ...
[ { "param": "self", "type": null }, { "param": "i", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "i", "type": null, "docstring": null, "docstring_tokens": [], ...
5dc3c86f35a32d6f55a76901697e8b05495be4cc
Este1le/gbhpo
gbopt/fmin/gbopt.py
[ "MIT" ]
Python
gb_opt
<not_specific>
def gb_opt(graph, objective_function, label_prop_alg="hmn", acquisition_func="eif", maximize_func="random", n_samples=-1, num_iterations=1000, initial_design="random", n_init=10, lids_init=None, Y_init=None, rng=None, output_path=None): """ General interface for graph-based semi...
General interface for graph-based semi-supervised learning for global black box optimization problems. Parameters ---------- graph: GraphObject The graph defined by features and labels of nodes, and an adjacency matrix. objective_func: Function handle of for the objective funct...
General interface for graph-based semi-supervised learning for global black box optimization problems. Parameters GraphObject The graph defined by features and labels of nodes, and an adjacency matrix. objective_func: Function handle of for the objective function. label_prop_alg: LabelPropagationAlgObject The label p...
[ "General", "interface", "for", "graph", "-", "based", "semi", "-", "supervised", "learning", "for", "global", "black", "box", "optimization", "problems", ".", "Parameters", "GraphObject", "The", "graph", "defined", "by", "features", "and", "labels", "of", "nodes...
def gb_opt(graph, objective_function, label_prop_alg="hmn", acquisition_func="eif", maximize_func="random", n_samples=-1, num_iterations=1000, initial_design="random", n_init=10, lids_init=None, Y_init=None, rng=None, output_path=None): assert n_init <= num_iterations, "Number of in...
[ "def", "gb_opt", "(", "graph", ",", "objective_function", ",", "label_prop_alg", "=", "\"hmn\"", ",", "acquisition_func", "=", "\"eif\"", ",", "maximize_func", "=", "\"random\"", ",", "n_samples", "=", "-", "1", ",", "num_iterations", "=", "1000", ",", "initia...
General interface for graph-based semi-supervised learning for global black box optimization problems.
[ "General", "interface", "for", "graph", "-", "based", "semi", "-", "supervised", "learning", "for", "global", "black", "box", "optimization", "problems", "." ]
[ "\"\"\"\n General interface for graph-based semi-supervised learning for global\n black box optimization problems.\n\n Parameters\n ----------\n graph: GraphObject\n The graph defined by features and labels of nodes, and an adjacency matrix.\n objective_func:\n Function handle of for...
[ { "param": "graph", "type": null }, { "param": "objective_function", "type": null }, { "param": "label_prop_alg", "type": null }, { "param": "acquisition_func", "type": null }, { "param": "maximize_func", "type": null }, { "param": "n_samples", "ty...
{ "returns": [], "raises": [], "params": [ { "identifier": "graph", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "objective_function", "type": null, "docstring": null, "docst...
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
exists
<not_specific>
def exists(self): """Detect if the cache exists. """ return os.path.exists(self._local_storage_path)
Detect if the cache exists.
Detect if the cache exists.
[ "Detect", "if", "the", "cache", "exists", "." ]
def exists(self): return os.path.exists(self._local_storage_path)
[ "def", "exists", "(", "self", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "self", ".", "_local_storage_path", ")" ]
Detect if the cache exists.
[ "Detect", "if", "the", "cache", "exists", "." ]
[ "\"\"\"Detect if the cache exists.\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": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_add_to_graph
null
def _add_to_graph(self, fact): """Adds a (subject, predicate, object) RDF triple to the graph. """ self.graph.add(fact)
Adds a (subject, predicate, object) RDF triple to the graph.
Adds a (subject, predicate, object) RDF triple to the graph.
[ "Adds", "a", "(", "subject", "predicate", "object", ")", "RDF", "triple", "to", "the", "graph", "." ]
def _add_to_graph(self, fact): self.graph.add(fact)
[ "def", "_add_to_graph", "(", "self", ",", "fact", ")", ":", "self", ".", "graph", ".", "add", "(", "fact", ")" ]
Adds a (subject, predicate, object) RDF triple to the graph.
[ "Adds", "a", "(", "subject", "predicate", "object", ")", "RDF", "triple", "to", "the", "graph", "." ]
[ "\"\"\"Adds a (subject, predicate, object) RDF triple to the graph.\n\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "fact", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fact", "type": null, "docstring": null, "docstring_tokens": [...
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_populate_setup
null
def _populate_setup(self): """Executes operations necessary before the cache can be populated. """ pass
Executes operations necessary before the cache can be populated.
Executes operations necessary before the cache can be populated.
[ "Executes", "operations", "necessary", "before", "the", "cache", "can", "be", "populated", "." ]
def _populate_setup(self): pass
[ "def", "_populate_setup", "(", "self", ")", ":", "pass" ]
Executes operations necessary before the cache can be populated.
[ "Executes", "operations", "necessary", "before", "the", "cache", "can", "be", "populated", "." ]
[ "\"\"\"Executes operations necessary before the cache can be populated.\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": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
refresh
null
def refresh(self): """Refresh the cache by deleting the old one and creating a new one. """ if self.exists: self.delete() self.populate() self.open()
Refresh the cache by deleting the old one and creating a new one.
Refresh the cache by deleting the old one and creating a new one.
[ "Refresh", "the", "cache", "by", "deleting", "the", "old", "one", "and", "creating", "a", "new", "one", "." ]
def refresh(self): if self.exists: self.delete() self.populate() self.open()
[ "def", "refresh", "(", "self", ")", ":", "if", "self", ".", "exists", ":", "self", ".", "delete", "(", ")", "self", ".", "populate", "(", ")", "self", ".", "open", "(", ")" ]
Refresh the cache by deleting the old one and creating a new one.
[ "Refresh", "the", "cache", "by", "deleting", "the", "old", "one", "and", "creating", "a", "new", "one", "." ]
[ "\"\"\"Refresh the cache by deleting the old one and creating a new one.\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": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_local_storage_path
<not_specific>
def _local_storage_path(self): """Returns a path to the on-disk structure of the cache. """ return self.cache_uri
Returns a path to the on-disk structure of the cache.
Returns a path to the on-disk structure of the cache.
[ "Returns", "a", "path", "to", "the", "on", "-", "disk", "structure", "of", "the", "cache", "." ]
def _local_storage_path(self): return self.cache_uri
[ "def", "_local_storage_path", "(", "self", ")", ":", "return", "self", ".", "cache_uri" ]
Returns a path to the on-disk structure of the cache.
[ "Returns", "a", "path", "to", "the", "on", "-", "disk", "structure", "of", "the", "cache", "." ]
[ "\"\"\"Returns a path to the on-disk structure of the cache.\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": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_add_namespaces
null
def _add_namespaces(graph): """Function to ensure that the graph always has some specific namespace aliases set. """ graph.bind('pgterms', PGTERMS) graph.bind('dcterms', DCTERMS)
Function to ensure that the graph always has some specific namespace aliases set.
Function to ensure that the graph always has some specific namespace aliases set.
[ "Function", "to", "ensure", "that", "the", "graph", "always", "has", "some", "specific", "namespace", "aliases", "set", "." ]
def _add_namespaces(graph): graph.bind('pgterms', PGTERMS) graph.bind('dcterms', DCTERMS)
[ "def", "_add_namespaces", "(", "graph", ")", ":", "graph", ".", "bind", "(", "'pgterms'", ",", "PGTERMS", ")", "graph", ".", "bind", "(", "'dcterms'", ",", "DCTERMS", ")" ]
Function to ensure that the graph always has some specific namespace aliases set.
[ "Function", "to", "ensure", "that", "the", "graph", "always", "has", "some", "specific", "namespace", "aliases", "set", "." ]
[ "\"\"\"Function to ensure that the graph always has some specific namespace\n aliases set.\n\n \"\"\"" ]
[ { "param": "graph", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "graph", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_download_metadata_archive
null
def _download_metadata_archive(self): """Makes a remote call to the Project Gutenberg servers and downloads the entire Project Gutenberg meta-data catalog. The catalog describes the texts on Project Gutenberg in RDF. The function returns a file-pointer to the catalog. """ ...
Makes a remote call to the Project Gutenberg servers and downloads the entire Project Gutenberg meta-data catalog. The catalog describes the texts on Project Gutenberg in RDF. The function returns a file-pointer to the catalog.
Makes a remote call to the Project Gutenberg servers and downloads the entire Project Gutenberg meta-data catalog. The catalog describes the texts on Project Gutenberg in RDF. The function returns a file-pointer to the catalog.
[ "Makes", "a", "remote", "call", "to", "the", "Project", "Gutenberg", "servers", "and", "downloads", "the", "entire", "Project", "Gutenberg", "meta", "-", "data", "catalog", ".", "The", "catalog", "describes", "the", "texts", "on", "Project", "Gutenberg", "in",...
def _download_metadata_archive(self): with tempfile.NamedTemporaryFile(delete=False) as metadata_archive: shutil.copyfileobj(urlopen(self.catalog_source), metadata_archive) yield metadata_archive.name remove(metadata_archive.name)
[ "def", "_download_metadata_archive", "(", "self", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "as", "metadata_archive", ":", "shutil", ".", "copyfileobj", "(", "urlopen", "(", "self", ".", "catalog_source", ")", "...
Makes a remote call to the Project Gutenberg servers and downloads the entire Project Gutenberg meta-data catalog.
[ "Makes", "a", "remote", "call", "to", "the", "Project", "Gutenberg", "servers", "and", "downloads", "the", "entire", "Project", "Gutenberg", "meta", "-", "data", "catalog", "." ]
[ "\"\"\"Makes a remote call to the Project Gutenberg servers and downloads\n the entire Project Gutenberg meta-data catalog. The catalog describes\n the texts on Project Gutenberg in RDF. The function returns a\n file-pointer to the catalog.\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": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_metadata_is_invalid
<not_specific>
def _metadata_is_invalid(cls, fact): """Determines if the fact is not well formed. """ return any(isinstance(token, URIRef) and ' ' in token for token in fact)
Determines if the fact is not well formed.
Determines if the fact is not well formed.
[ "Determines", "if", "the", "fact", "is", "not", "well", "formed", "." ]
def _metadata_is_invalid(cls, fact): return any(isinstance(token, URIRef) and ' ' in token for token in fact)
[ "def", "_metadata_is_invalid", "(", "cls", ",", "fact", ")", ":", "return", "any", "(", "isinstance", "(", "token", ",", "URIRef", ")", "and", "' '", "in", "token", "for", "token", "in", "fact", ")" ]
Determines if the fact is not well formed.
[ "Determines", "if", "the", "fact", "is", "not", "well", "formed", "." ]
[ "\"\"\"Determines if the fact is not well formed.\n\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "fact", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fact", "type": null, "docstring": null, "docstring_tokens": []...
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_iter_metadata_triples
null
def _iter_metadata_triples(cls, metadata_archive_path): """Yields all meta-data of Project Gutenberg texts contained in the catalog dump. """ pg_rdf_regex = re.compile(r'pg\d+.rdf$') with closing(tarfile.open(metadata_archive_path)) as metadata_archive: for item in m...
Yields all meta-data of Project Gutenberg texts contained in the catalog dump.
Yields all meta-data of Project Gutenberg texts contained in the catalog dump.
[ "Yields", "all", "meta", "-", "data", "of", "Project", "Gutenberg", "texts", "contained", "in", "the", "catalog", "dump", "." ]
def _iter_metadata_triples(cls, metadata_archive_path): pg_rdf_regex = re.compile(r'pg\d+.rdf$') with closing(tarfile.open(metadata_archive_path)) as metadata_archive: for item in metadata_archive: if pg_rdf_regex.search(item.name): with disable_logging():...
[ "def", "_iter_metadata_triples", "(", "cls", ",", "metadata_archive_path", ")", ":", "pg_rdf_regex", "=", "re", ".", "compile", "(", "r'pg\\d+.rdf$'", ")", "with", "closing", "(", "tarfile", ".", "open", "(", "metadata_archive_path", ")", ")", "as", "metadata_ar...
Yields all meta-data of Project Gutenberg texts contained in the catalog dump.
[ "Yields", "all", "meta", "-", "data", "of", "Project", "Gutenberg", "texts", "contained", "in", "the", "catalog", "dump", "." ]
[ "\"\"\"Yields all meta-data of Project Gutenberg texts contained in the\n catalog dump.\n\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "metadata_archive_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "metadata_archive_path", "type": null, "docstring": null, "docs...
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_populate_setup
null
def _populate_setup(self): """Just create a local marker file since the actual database should already be created on the Fuseki server. """ makedirs(os.path.dirname(self._cache_marker)) with codecs.open(self._cache_marker, 'w', encoding='utf-8') as fobj: fobj.write(s...
Just create a local marker file since the actual database should already be created on the Fuseki server.
Just create a local marker file since the actual database should already be created on the Fuseki server.
[ "Just", "create", "a", "local", "marker", "file", "since", "the", "actual", "database", "should", "already", "be", "created", "on", "the", "Fuseki", "server", "." ]
def _populate_setup(self): makedirs(os.path.dirname(self._cache_marker)) with codecs.open(self._cache_marker, 'w', encoding='utf-8') as fobj: fobj.write(self.cache_uri) self.graph.open(self.cache_uri)
[ "def", "_populate_setup", "(", "self", ")", ":", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "_cache_marker", ")", ")", "with", "codecs", ".", "open", "(", "self", ".", "_cache_marker", ",", "'w'", ",", "encoding", "=", "'utf-...
Just create a local marker file since the actual database should already be created on the Fuseki server.
[ "Just", "create", "a", "local", "marker", "file", "since", "the", "actual", "database", "should", "already", "be", "created", "on", "the", "Fuseki", "server", "." ]
[ "\"\"\"Just create a local marker file since the actual database should\n already be created on the Fuseki server.\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": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
delete
null
def delete(self): """Deletes the local marker file and also any data in the Fuseki server. """ MetadataCache.delete(self) try: self.graph.query('DELETE WHERE { ?s ?p ?o . }') except ResultException: # this is often just a false positive since Jena...
Deletes the local marker file and also any data in the Fuseki server.
Deletes the local marker file and also any data in the Fuseki server.
[ "Deletes", "the", "local", "marker", "file", "and", "also", "any", "data", "in", "the", "Fuseki", "server", "." ]
def delete(self): MetadataCache.delete(self) try: self.graph.query('DELETE WHERE { ?s ?p ?o . }') except ResultException: logging.exception('error when deleting graph')
[ "def", "delete", "(", "self", ")", ":", "MetadataCache", ".", "delete", "(", "self", ")", "try", ":", "self", ".", "graph", ".", "query", "(", "'DELETE WHERE { ?s ?p ?o . }'", ")", "except", "ResultException", ":", "logging", ".", "exception", "(", "'error w...
Deletes the local marker file and also any data in the Fuseki server.
[ "Deletes", "the", "local", "marker", "file", "and", "also", "any", "data", "in", "the", "Fuseki", "server", "." ]
[ "\"\"\"Deletes the local marker file and also any data in the Fuseki\n server.\n\n \"\"\"", "# this is often just a false positive since Jena Fuseki does not", "# return tuples for a deletion query, so swallowing the exception", "# here is fine" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_local_storage_path
<not_specific>
def _local_storage_path(self): """Returns the path to the local marker file that gets written when the cache was created. """ return self._cache_marker
Returns the path to the local marker file that gets written when the cache was created.
Returns the path to the local marker file that gets written when the cache was created.
[ "Returns", "the", "path", "to", "the", "local", "marker", "file", "that", "gets", "written", "when", "the", "cache", "was", "created", "." ]
def _local_storage_path(self): return self._cache_marker
[ "def", "_local_storage_path", "(", "self", ")", ":", "return", "self", ".", "_cache_marker" ]
Returns the path to the local marker file that gets written when the cache was created.
[ "Returns", "the", "path", "to", "the", "local", "marker", "file", "that", "gets", "written", "when", "the", "cache", "was", "created", "." ]
[ "\"\"\"Returns the path to the local marker file that gets written when\n the cache was created.\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": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_check_can_be_instantiated
null
def _check_can_be_instantiated(cls, cache_location): """Pre-conditions: the cache location is the URL to a Fuseki server and the SPARQLWrapper library exists (transitive dependency of RDFlib's sparqlstore). """ if not any(cache_location.startswith(prefix) for ...
Pre-conditions: the cache location is the URL to a Fuseki server and the SPARQLWrapper library exists (transitive dependency of RDFlib's sparqlstore).
Pre-conditions: the cache location is the URL to a Fuseki server and the SPARQLWrapper library exists (transitive dependency of RDFlib's sparqlstore).
[ "Pre", "-", "conditions", ":", "the", "cache", "location", "is", "the", "URL", "to", "a", "Fuseki", "server", "and", "the", "SPARQLWrapper", "library", "exists", "(", "transitive", "dependency", "of", "RDFlib", "'", "s", "sparqlstore", ")", "." ]
def _check_can_be_instantiated(cls, cache_location): if not any(cache_location.startswith(prefix) for prefix in cls._CACHE_URL_PREFIXES): raise InvalidCacheException('cache location is not a Fuseki url') try: from rdflib.plugins.stores.sparqlstore import SPARQL...
[ "def", "_check_can_be_instantiated", "(", "cls", ",", "cache_location", ")", ":", "if", "not", "any", "(", "cache_location", ".", "startswith", "(", "prefix", ")", "for", "prefix", "in", "cls", ".", "_CACHE_URL_PREFIXES", ")", ":", "raise", "InvalidCacheExceptio...
Pre-conditions: the cache location is the URL to a Fuseki server and the SPARQLWrapper library exists (transitive dependency of RDFlib's sparqlstore).
[ "Pre", "-", "conditions", ":", "the", "cache", "location", "is", "the", "URL", "to", "a", "Fuseki", "server", "and", "the", "SPARQLWrapper", "library", "exists", "(", "transitive", "dependency", "of", "RDFlib", "'", "s", "sparqlstore", ")", "." ]
[ "\"\"\"Pre-conditions: the cache location is the URL to a Fuseki server\n and the SPARQLWrapper library exists (transitive dependency of\n RDFlib's sparqlstore).\n\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "cache_location", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "cache_location", "type": null, "docstring": null, "docstring_t...
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_metadata_is_invalid
<not_specific>
def _metadata_is_invalid(cls, fact): """Filters out blank nodes since the SPARQLUpdateStore does not support them. """ return (MetadataCache._metadata_is_invalid(fact) or any(isinstance(token, BNode) for token in fact))
Filters out blank nodes since the SPARQLUpdateStore does not support them.
Filters out blank nodes since the SPARQLUpdateStore does not support them.
[ "Filters", "out", "blank", "nodes", "since", "the", "SPARQLUpdateStore", "does", "not", "support", "them", "." ]
def _metadata_is_invalid(cls, fact): return (MetadataCache._metadata_is_invalid(fact) or any(isinstance(token, BNode) for token in fact))
[ "def", "_metadata_is_invalid", "(", "cls", ",", "fact", ")", ":", "return", "(", "MetadataCache", ".", "_metadata_is_invalid", "(", "fact", ")", "or", "any", "(", "isinstance", "(", "token", ",", "BNode", ")", "for", "token", "in", "fact", ")", ")" ]
Filters out blank nodes since the SPARQLUpdateStore does not support them.
[ "Filters", "out", "blank", "nodes", "since", "the", "SPARQLUpdateStore", "does", "not", "support", "them", "." ]
[ "\"\"\"Filters out blank nodes since the SPARQLUpdateStore does not\n support them.\n\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "fact", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fact", "type": null, "docstring": null, "docstring_tokens": []...
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_is_graph_add_exception_acceptable
<not_specific>
def _is_graph_add_exception_acceptable(cls, ex): """Checks if a graph-add exception can be safely ignored. """ # integrity errors due to violating unique constraints should be safe # to ignore since the only unique constraints in rdflib-sqlalchemy are # on index columns ...
Checks if a graph-add exception can be safely ignored.
Checks if a graph-add exception can be safely ignored.
[ "Checks", "if", "a", "graph", "-", "add", "exception", "can", "be", "safely", "ignored", "." ]
def _is_graph_add_exception_acceptable(cls, ex): return 'UNIQUE constraint failed' in text_type(ex)
[ "def", "_is_graph_add_exception_acceptable", "(", "cls", ",", "ex", ")", ":", "return", "'UNIQUE constraint failed'", "in", "text_type", "(", "ex", ")" ]
Checks if a graph-add exception can be safely ignored.
[ "Checks", "if", "a", "graph", "-", "add", "exception", "can", "be", "safely", "ignored", "." ]
[ "\"\"\"Checks if a graph-add exception can be safely ignored.\n\n \"\"\"", "# integrity errors due to violating unique constraints should be safe", "# to ignore since the only unique constraints in rdflib-sqlalchemy are", "# on index columns" ]
[ { "param": "cls", "type": null }, { "param": "ex", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ex", "type": null, "docstring": null, "docstring_tokens": [], ...
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
_create_metadata_cache
<not_specific>
def _create_metadata_cache(cache_location): """Creates a new metadata cache instance appropriate for this platform. """ cache_url = os.getenv('GUTENBERG_FUSEKI_URL') if cache_url: return FusekiMetadataCache(cache_location, cache_url) try: return SleepycatMetadataCache(cache_locatio...
Creates a new metadata cache instance appropriate for this platform.
Creates a new metadata cache instance appropriate for this platform.
[ "Creates", "a", "new", "metadata", "cache", "instance", "appropriate", "for", "this", "platform", "." ]
def _create_metadata_cache(cache_location): cache_url = os.getenv('GUTENBERG_FUSEKI_URL') if cache_url: return FusekiMetadataCache(cache_location, cache_url) try: return SleepycatMetadataCache(cache_location) except InvalidCacheException: logging.warning('Unable to create cache b...
[ "def", "_create_metadata_cache", "(", "cache_location", ")", ":", "cache_url", "=", "os", ".", "getenv", "(", "'GUTENBERG_FUSEKI_URL'", ")", "if", "cache_url", ":", "return", "FusekiMetadataCache", "(", "cache_location", ",", "cache_url", ")", "try", ":", "return"...
Creates a new metadata cache instance appropriate for this platform.
[ "Creates", "a", "new", "metadata", "cache", "instance", "appropriate", "for", "this", "platform", "." ]
[ "\"\"\"Creates a new metadata cache instance appropriate for this platform.\n\n \"\"\"" ]
[ { "param": "cache_location", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cache_location", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
603c00e22912842d4d0aa8f939403f5559c9e15d
bwindsor22/gutenberg
gutenberg/acquire/metadata.py
[ "Apache-2.0" ]
Python
load_metadata
<not_specific>
def load_metadata(refresh_cache=False): """Returns a graph representing meta-data for all Project Gutenberg texts. Pertinent information about texts or about how texts relate to each other (e.g. shared authors, shared subjects) can be extracted using standard RDF processing techniques (e.g. SPARQL queri...
Returns a graph representing meta-data for all Project Gutenberg texts. Pertinent information about texts or about how texts relate to each other (e.g. shared authors, shared subjects) can be extracted using standard RDF processing techniques (e.g. SPARQL queries). After making an initial remote call to...
Returns a graph representing meta-data for all Project Gutenberg texts. Pertinent information about texts or about how texts relate to each other can be extracted using standard RDF processing techniques . After making an initial remote call to Project Gutenberg's servers, the meta-data is persisted locally.
[ "Returns", "a", "graph", "representing", "meta", "-", "data", "for", "all", "Project", "Gutenberg", "texts", ".", "Pertinent", "information", "about", "texts", "or", "about", "how", "texts", "relate", "to", "each", "other", "can", "be", "extracted", "using", ...
def load_metadata(refresh_cache=False): cache = get_metadata_cache() if refresh_cache: cache.refresh() if not cache.is_open: cache.open() return cache.graph
[ "def", "load_metadata", "(", "refresh_cache", "=", "False", ")", ":", "cache", "=", "get_metadata_cache", "(", ")", "if", "refresh_cache", ":", "cache", ".", "refresh", "(", ")", "if", "not", "cache", ".", "is_open", ":", "cache", ".", "open", "(", ")", ...
Returns a graph representing meta-data for all Project Gutenberg texts.
[ "Returns", "a", "graph", "representing", "meta", "-", "data", "for", "all", "Project", "Gutenberg", "texts", "." ]
[ "\"\"\"Returns a graph representing meta-data for all Project Gutenberg texts.\n Pertinent information about texts or about how texts relate to each other\n (e.g. shared authors, shared subjects) can be extracted using standard RDF\n processing techniques (e.g. SPARQL queries). After making an initial remo...
[ { "param": "refresh_cache", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "refresh_cache", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9267e55a38cfe6c7603db6a51a0b6b4ad4e8de9f
bwindsor22/gutenberg
tests/_util.py
[ "Apache-2.0" ]
Python
always_throw
<not_specific>
def always_throw(exception_type): """Factory to create methods that throw exceptions. Args: exception_type: The type of exception to throw Returns: function: A function that always throws an exception when called. """ # noinspection PyUnusedLocal def wrapped(*args, **kwargs): ...
Factory to create methods that throw exceptions. Args: exception_type: The type of exception to throw Returns: function: A function that always throws an exception when called.
Factory to create methods that throw exceptions.
[ "Factory", "to", "create", "methods", "that", "throw", "exceptions", "." ]
def always_throw(exception_type): def wrapped(*args, **kwargs): raise exception_type return wrapped
[ "def", "always_throw", "(", "exception_type", ")", ":", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "raise", "exception_type", "return", "wrapped" ]
Factory to create methods that throw exceptions.
[ "Factory", "to", "create", "methods", "that", "throw", "exceptions", "." ]
[ "\"\"\"Factory to create methods that throw exceptions.\n\n Args:\n exception_type: The type of exception to throw\n\n Returns:\n function: A function that always throws an exception when called.\n\n \"\"\"", "# noinspection PyUnusedLocal" ]
[ { "param": "exception_type", "type": null } ]
{ "returns": [ { "docstring": "A function that always throws an exception when called.", "docstring_tokens": [ "A", "function", "that", "always", "throws", "an", "exception", "when", "called", "." ], "type": "f...
f2f75ba29d551033ddb337e16c48142f2571aa67
bwindsor22/gutenberg
gutenberg/_util/logging.py
[ "Apache-2.0" ]
Python
disable_logging
null
def disable_logging(logger=None): """Context manager to temporarily suppress all logging for a given logger or the root logger if no particular logger is specified. """ logger = logger or logging.getLogger() disabled = logger.disabled logger.disabled = True yield logger.disabled = disab...
Context manager to temporarily suppress all logging for a given logger or the root logger if no particular logger is specified.
Context manager to temporarily suppress all logging for a given logger or the root logger if no particular logger is specified.
[ "Context", "manager", "to", "temporarily", "suppress", "all", "logging", "for", "a", "given", "logger", "or", "the", "root", "logger", "if", "no", "particular", "logger", "is", "specified", "." ]
def disable_logging(logger=None): logger = logger or logging.getLogger() disabled = logger.disabled logger.disabled = True yield logger.disabled = disabled
[ "def", "disable_logging", "(", "logger", "=", "None", ")", ":", "logger", "=", "logger", "or", "logging", ".", "getLogger", "(", ")", "disabled", "=", "logger", ".", "disabled", "logger", ".", "disabled", "=", "True", "yield", "logger", ".", "disabled", ...
Context manager to temporarily suppress all logging for a given logger or the root logger if no particular logger is specified.
[ "Context", "manager", "to", "temporarily", "suppress", "all", "logging", "for", "a", "given", "logger", "or", "the", "root", "logger", "if", "no", "particular", "logger", "is", "specified", "." ]
[ "\"\"\"Context manager to temporarily suppress all logging for a given logger\n or the root logger if no particular logger is specified.\n\n \"\"\"" ]
[ { "param": "logger", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "logger", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }