repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
NickMonzillo/SmartCloud
SmartCloud/wordplay.py
eliminate_repeats
def eliminate_repeats(text): '''Returns a list of words that occur in the text. Eliminates stopwords.''' bannedwords = read_file('stopwords.txt') alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: ...
python
def eliminate_repeats(text): '''Returns a list of words that occur in the text. Eliminates stopwords.''' bannedwords = read_file('stopwords.txt') alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: ...
[ "def", "eliminate_repeats", "(", "text", ")", ":", "bannedwords", "=", "read_file", "(", "'stopwords.txt'", ")", "alphabet", "=", "'abcdefghijklmnopqrstuvwxyz'", "words", "=", "text", ".", "split", "(", ")", "standardwords", "=", "[", "]", "for", "word", "in",...
Returns a list of words that occur in the text. Eliminates stopwords.
[ "Returns", "a", "list", "of", "words", "that", "occur", "in", "the", "text", ".", "Eliminates", "stopwords", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/wordplay.py#L21-L36
train
56,700
NickMonzillo/SmartCloud
SmartCloud/wordplay.py
wordcount
def wordcount(text): '''Returns the count of the words in a file.''' bannedwords = read_file('stopwords.txt') wordcount = {} separated = separate(text) for word in separated: if word not in bannedwords: if not wordcount.has_key(word): wordcount[word] = 1 ...
python
def wordcount(text): '''Returns the count of the words in a file.''' bannedwords = read_file('stopwords.txt') wordcount = {} separated = separate(text) for word in separated: if word not in bannedwords: if not wordcount.has_key(word): wordcount[word] = 1 ...
[ "def", "wordcount", "(", "text", ")", ":", "bannedwords", "=", "read_file", "(", "'stopwords.txt'", ")", "wordcount", "=", "{", "}", "separated", "=", "separate", "(", "text", ")", "for", "word", "in", "separated", ":", "if", "word", "not", "in", "banned...
Returns the count of the words in a file.
[ "Returns", "the", "count", "of", "the", "words", "in", "a", "file", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/wordplay.py#L38-L49
train
56,701
NickMonzillo/SmartCloud
SmartCloud/wordplay.py
tuplecount
def tuplecount(text): '''Changes a dictionary into a list of tuples.''' worddict = wordcount(text) countlist = [] for key in worddict.keys(): countlist.append((key,worddict[key])) countlist = list(reversed(sorted(countlist,key = lambda x: x[1]))) return countlist
python
def tuplecount(text): '''Changes a dictionary into a list of tuples.''' worddict = wordcount(text) countlist = [] for key in worddict.keys(): countlist.append((key,worddict[key])) countlist = list(reversed(sorted(countlist,key = lambda x: x[1]))) return countlist
[ "def", "tuplecount", "(", "text", ")", ":", "worddict", "=", "wordcount", "(", "text", ")", "countlist", "=", "[", "]", "for", "key", "in", "worddict", ".", "keys", "(", ")", ":", "countlist", ".", "append", "(", "(", "key", ",", "worddict", "[", "...
Changes a dictionary into a list of tuples.
[ "Changes", "a", "dictionary", "into", "a", "list", "of", "tuples", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/wordplay.py#L51-L58
train
56,702
akissa/clamavmirror
clamavmirror/__init__.py
get_file_md5
def get_file_md5(filename): """Get a file's MD5""" if os.path.exists(filename): blocksize = 65536 try: hasher = hashlib.md5() except BaseException: hasher = hashlib.new('md5', usedForSecurity=False) with open(filename, 'rb') as afile: buf = afi...
python
def get_file_md5(filename): """Get a file's MD5""" if os.path.exists(filename): blocksize = 65536 try: hasher = hashlib.md5() except BaseException: hasher = hashlib.new('md5', usedForSecurity=False) with open(filename, 'rb') as afile: buf = afi...
[ "def", "get_file_md5", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "blocksize", "=", "65536", "try", ":", "hasher", "=", "hashlib", ".", "md5", "(", ")", "except", "BaseException", ":", "hasher", "=", ...
Get a file's MD5
[ "Get", "a", "file", "s", "MD5" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L91-L106
train
56,703
akissa/clamavmirror
clamavmirror/__init__.py
get_md5
def get_md5(string): """Get a string's MD5""" try: hasher = hashlib.md5() except BaseException: hasher = hashlib.new('md5', usedForSecurity=False) hasher.update(string) return hasher.hexdigest()
python
def get_md5(string): """Get a string's MD5""" try: hasher = hashlib.md5() except BaseException: hasher = hashlib.new('md5', usedForSecurity=False) hasher.update(string) return hasher.hexdigest()
[ "def", "get_md5", "(", "string", ")", ":", "try", ":", "hasher", "=", "hashlib", ".", "md5", "(", ")", "except", "BaseException", ":", "hasher", "=", "hashlib", ".", "new", "(", "'md5'", ",", "usedForSecurity", "=", "False", ")", "hasher", ".", "update...
Get a string's MD5
[ "Get", "a", "string", "s", "MD5" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L109-L116
train
56,704
akissa/clamavmirror
clamavmirror/__init__.py
deploy_signature
def deploy_signature(source, dest, user=None, group=None): """Deploy a signature fole""" move(source, dest) os.chmod(dest, 0644) if user and group: try: uid = pwd.getpwnam(user).pw_uid gid = grp.getgrnam(group).gr_gid os.chown(dest, uid, gid) except (K...
python
def deploy_signature(source, dest, user=None, group=None): """Deploy a signature fole""" move(source, dest) os.chmod(dest, 0644) if user and group: try: uid = pwd.getpwnam(user).pw_uid gid = grp.getgrnam(group).gr_gid os.chown(dest, uid, gid) except (K...
[ "def", "deploy_signature", "(", "source", ",", "dest", ",", "user", "=", "None", ",", "group", "=", "None", ")", ":", "move", "(", "source", ",", "dest", ")", "os", ".", "chmod", "(", "dest", ",", "0644", ")", "if", "user", "and", "group", ":", "...
Deploy a signature fole
[ "Deploy", "a", "signature", "fole" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L129-L139
train
56,705
akissa/clamavmirror
clamavmirror/__init__.py
get_local_version
def get_local_version(sigdir, sig): """Get the local version of a signature""" version = None filename = os.path.join(sigdir, '%s.cvd' % sig) if os.path.exists(filename): cmd = ['sigtool', '-i', filename] sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE) while True: line...
python
def get_local_version(sigdir, sig): """Get the local version of a signature""" version = None filename = os.path.join(sigdir, '%s.cvd' % sig) if os.path.exists(filename): cmd = ['sigtool', '-i', filename] sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE) while True: line...
[ "def", "get_local_version", "(", "sigdir", ",", "sig", ")", ":", "version", "=", "None", "filename", "=", "os", ".", "path", ".", "join", "(", "sigdir", ",", "'%s.cvd'", "%", "sig", ")", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ...
Get the local version of a signature
[ "Get", "the", "local", "version", "of", "a", "signature" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L157-L172
train
56,706
akissa/clamavmirror
clamavmirror/__init__.py
verify_sigfile
def verify_sigfile(sigdir, sig): """Verify a signature file""" cmd = ['sigtool', '-i', '%s/%s.cvd' % (sigdir, sig)] sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE) ret_val = sigtool.wait() return ret_val == 0
python
def verify_sigfile(sigdir, sig): """Verify a signature file""" cmd = ['sigtool', '-i', '%s/%s.cvd' % (sigdir, sig)] sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE) ret_val = sigtool.wait() return ret_val == 0
[ "def", "verify_sigfile", "(", "sigdir", ",", "sig", ")", ":", "cmd", "=", "[", "'sigtool'", ",", "'-i'", ",", "'%s/%s.cvd'", "%", "(", "sigdir", ",", "sig", ")", "]", "sigtool", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "...
Verify a signature file
[ "Verify", "a", "signature", "file" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L175-L180
train
56,707
akissa/clamavmirror
clamavmirror/__init__.py
check_download
def check_download(obj, *args, **kwargs): """Verify a download""" version = args[0] workdir = args[1] signame = args[2] if version: local_version = get_local_version(workdir, signame) if not verify_sigfile(workdir, signame) or version != local_version: error("[-] \033[91m...
python
def check_download(obj, *args, **kwargs): """Verify a download""" version = args[0] workdir = args[1] signame = args[2] if version: local_version = get_local_version(workdir, signame) if not verify_sigfile(workdir, signame) or version != local_version: error("[-] \033[91m...
[ "def", "check_download", "(", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "version", "=", "args", "[", "0", "]", "workdir", "=", "args", "[", "1", "]", "signame", "=", "args", "[", "2", "]", "if", "version", ":", "local_version", ...
Verify a download
[ "Verify", "a", "download" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L184-L194
train
56,708
akissa/clamavmirror
clamavmirror/__init__.py
download_sig
def download_sig(opts, sig, version=None): """Download signature from hostname""" code = None downloaded = False useagent = 'ClamAV/0.101.1 (OS: linux-gnu, ARCH: x86_64, CPU: x86_64)' manager = PoolManager( headers=make_headers(user_agent=useagent), cert_reqs='CERT_REQUIRED', ...
python
def download_sig(opts, sig, version=None): """Download signature from hostname""" code = None downloaded = False useagent = 'ClamAV/0.101.1 (OS: linux-gnu, ARCH: x86_64, CPU: x86_64)' manager = PoolManager( headers=make_headers(user_agent=useagent), cert_reqs='CERT_REQUIRED', ...
[ "def", "download_sig", "(", "opts", ",", "sig", ",", "version", "=", "None", ")", ":", "code", "=", "None", "downloaded", "=", "False", "useagent", "=", "'ClamAV/0.101.1 (OS: linux-gnu, ARCH: x86_64, CPU: x86_64)'", "manager", "=", "PoolManager", "(", "headers", "...
Download signature from hostname
[ "Download", "signature", "from", "hostname" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L197-L224
train
56,709
akissa/clamavmirror
clamavmirror/__init__.py
copy_sig
def copy_sig(sig, opts, isdiff): """Deploy a sig""" info("[+] \033[92mDeploying signature:\033[0m %s" % sig) if isdiff: sourcefile = os.path.join(opts.workdir, '%s.cdiff' % sig) destfile = os.path.join(opts.mirrordir, '%s.cdiff' % sig) else: sourcefile = os.path.join(opts.workdir...
python
def copy_sig(sig, opts, isdiff): """Deploy a sig""" info("[+] \033[92mDeploying signature:\033[0m %s" % sig) if isdiff: sourcefile = os.path.join(opts.workdir, '%s.cdiff' % sig) destfile = os.path.join(opts.mirrordir, '%s.cdiff' % sig) else: sourcefile = os.path.join(opts.workdir...
[ "def", "copy_sig", "(", "sig", ",", "opts", ",", "isdiff", ")", ":", "info", "(", "\"[+] \\033[92mDeploying signature:\\033[0m %s\"", "%", "sig", ")", "if", "isdiff", ":", "sourcefile", "=", "os", ".", "path", ".", "join", "(", "opts", ".", "workdir", ",",...
Deploy a sig
[ "Deploy", "a", "sig" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L247-L257
train
56,710
akissa/clamavmirror
clamavmirror/__init__.py
create_dns_file
def create_dns_file(opts, record): """Create the DNS record file""" info("[+] \033[92mUpdating dns.txt file\033[0m") filename = os.path.join(opts.mirrordir, 'dns.txt') localmd5 = get_file_md5(filename) remotemd5 = get_md5(record) if localmd5 != remotemd5: create_file(filename, record) ...
python
def create_dns_file(opts, record): """Create the DNS record file""" info("[+] \033[92mUpdating dns.txt file\033[0m") filename = os.path.join(opts.mirrordir, 'dns.txt') localmd5 = get_file_md5(filename) remotemd5 = get_md5(record) if localmd5 != remotemd5: create_file(filename, record) ...
[ "def", "create_dns_file", "(", "opts", ",", "record", ")", ":", "info", "(", "\"[+] \\033[92mUpdating dns.txt file\\033[0m\"", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "opts", ".", "mirrordir", ",", "'dns.txt'", ")", "localmd5", "=", "get_fil...
Create the DNS record file
[ "Create", "the", "DNS", "record", "file" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L301-L311
train
56,711
akissa/clamavmirror
clamavmirror/__init__.py
download_diffs
def download_diffs(queue): """Download the cdiff files""" while True: options, signature_type, localver, remotever = queue.get() for num in range(int(localver), int(remotever) + 1): sig_diff = '%s-%d' % (signature_type, num) filename = os.path.join(options.mirrordir, '%s....
python
def download_diffs(queue): """Download the cdiff files""" while True: options, signature_type, localver, remotever = queue.get() for num in range(int(localver), int(remotever) + 1): sig_diff = '%s-%d' % (signature_type, num) filename = os.path.join(options.mirrordir, '%s....
[ "def", "download_diffs", "(", "queue", ")", ":", "while", "True", ":", "options", ",", "signature_type", ",", "localver", ",", "remotever", "=", "queue", ".", "get", "(", ")", "for", "num", "in", "range", "(", "int", "(", "localver", ")", ",", "int", ...
Download the cdiff files
[ "Download", "the", "cdiff", "files" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L314-L323
train
56,712
akissa/clamavmirror
clamavmirror/__init__.py
work
def work(options): """The work functions""" # pylint: disable=too-many-locals record = get_record(options) _, mainv, dailyv, _, _, _, safebrowsingv, bytecodev = record.split(':') versions = {'main': mainv, 'daily': dailyv, 'safebrowsing': safebrowsingv, 'bytecode': by...
python
def work(options): """The work functions""" # pylint: disable=too-many-locals record = get_record(options) _, mainv, dailyv, _, _, _, safebrowsingv, bytecodev = record.split(':') versions = {'main': mainv, 'daily': dailyv, 'safebrowsing': safebrowsingv, 'bytecode': by...
[ "def", "work", "(", "options", ")", ":", "# pylint: disable=too-many-locals", "record", "=", "get_record", "(", "options", ")", "_", ",", "mainv", ",", "dailyv", ",", "_", ",", "_", ",", "_", ",", "safebrowsingv", ",", "bytecodev", "=", "record", ".", "s...
The work functions
[ "The", "work", "functions" ]
6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6
https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L326-L369
train
56,713
mardix/Yass
yass/cli.py
copy_resource
def copy_resource(src, dest): """ To copy package data to destination """ package_name = "yass" dest = (dest + "/" + os.path.basename(src)).rstrip("/") if pkg_resources.resource_isdir(package_name, src): if not os.path.isdir(dest): os.makedirs(dest) for res in pkg_res...
python
def copy_resource(src, dest): """ To copy package data to destination """ package_name = "yass" dest = (dest + "/" + os.path.basename(src)).rstrip("/") if pkg_resources.resource_isdir(package_name, src): if not os.path.isdir(dest): os.makedirs(dest) for res in pkg_res...
[ "def", "copy_resource", "(", "src", ",", "dest", ")", ":", "package_name", "=", "\"yass\"", "dest", "=", "(", "dest", "+", "\"/\"", "+", "os", ".", "path", ".", "basename", "(", "src", ")", ")", ".", "rstrip", "(", "\"/\"", ")", "if", "pkg_resources"...
To copy package data to destination
[ "To", "copy", "package", "data", "to", "destination" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/cli.py#L61-L78
train
56,714
mardix/Yass
yass/cli.py
publish
def publish(endpoint, purge_files, rebuild_manifest, skip_upload): """Publish the site""" print("Publishing site to %s ..." % endpoint.upper()) yass = Yass(CWD) target = endpoint.lower() sitename = yass.sitename if not sitename: raise ValueError("Missing site name") endpoint = yas...
python
def publish(endpoint, purge_files, rebuild_manifest, skip_upload): """Publish the site""" print("Publishing site to %s ..." % endpoint.upper()) yass = Yass(CWD) target = endpoint.lower() sitename = yass.sitename if not sitename: raise ValueError("Missing site name") endpoint = yas...
[ "def", "publish", "(", "endpoint", ",", "purge_files", ",", "rebuild_manifest", ",", "skip_upload", ")", ":", "print", "(", "\"Publishing site to %s ...\"", "%", "endpoint", ".", "upper", "(", ")", ")", "yass", "=", "Yass", "(", "CWD", ")", "target", "=", ...
Publish the site
[ "Publish", "the", "site" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/cli.py#L134-L188
train
56,715
mardix/Yass
yass/cli.py
setup_dns
def setup_dns(endpoint): """Setup site domain to route to static site""" print("Setting up DNS...") yass = Yass(CWD) target = endpoint.lower() sitename = yass.sitename if not sitename: raise ValueError("Missing site name") endpoint = yass.config.get("hosting.%s" % target) if n...
python
def setup_dns(endpoint): """Setup site domain to route to static site""" print("Setting up DNS...") yass = Yass(CWD) target = endpoint.lower() sitename = yass.sitename if not sitename: raise ValueError("Missing site name") endpoint = yass.config.get("hosting.%s" % target) if n...
[ "def", "setup_dns", "(", "endpoint", ")", ":", "print", "(", "\"Setting up DNS...\"", ")", "yass", "=", "Yass", "(", "CWD", ")", "target", "=", "endpoint", ".", "lower", "(", ")", "sitename", "=", "yass", ".", "sitename", "if", "not", "sitename", ":", ...
Setup site domain to route to static site
[ "Setup", "site", "domain", "to", "route", "to", "static", "site" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/cli.py#L194-L222
train
56,716
mardix/Yass
yass/cli.py
create_site
def create_site(sitename): """Create a new site directory and init Yass""" sitepath = os.path.join(CWD, sitename) if os.path.isdir(sitepath): print("Site directory '%s' exists already!" % sitename) else: print("Creating site: %s..." % sitename) os.makedirs(sitepath) copy_...
python
def create_site(sitename): """Create a new site directory and init Yass""" sitepath = os.path.join(CWD, sitename) if os.path.isdir(sitepath): print("Site directory '%s' exists already!" % sitename) else: print("Creating site: %s..." % sitename) os.makedirs(sitepath) copy_...
[ "def", "create_site", "(", "sitename", ")", ":", "sitepath", "=", "os", ".", "path", ".", "join", "(", "CWD", ",", "sitename", ")", "if", "os", ".", "path", ".", "isdir", "(", "sitepath", ")", ":", "print", "(", "\"Site directory '%s' exists already!\"", ...
Create a new site directory and init Yass
[ "Create", "a", "new", "site", "directory", "and", "init", "Yass" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/cli.py#L227-L240
train
56,717
mardix/Yass
yass/cli.py
init
def init(): """Initialize Yass in the current directory """ yass_conf = os.path.join(CWD, "yass.yml") if os.path.isfile(yass_conf): print("::ALERT::") print("It seems like Yass is already initialized here.") print("If it's a mistake, delete 'yass.yml' in this directory") else: ...
python
def init(): """Initialize Yass in the current directory """ yass_conf = os.path.join(CWD, "yass.yml") if os.path.isfile(yass_conf): print("::ALERT::") print("It seems like Yass is already initialized here.") print("If it's a mistake, delete 'yass.yml' in this directory") else: ...
[ "def", "init", "(", ")", ":", "yass_conf", "=", "os", ".", "path", ".", "join", "(", "CWD", ",", "\"yass.yml\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "yass_conf", ")", ":", "print", "(", "\"::ALERT::\"", ")", "print", "(", "\"It seems li...
Initialize Yass in the current directory
[ "Initialize", "Yass", "in", "the", "current", "directory" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/cli.py#L244-L258
train
56,718
mardix/Yass
yass/cli.py
create_page
def create_page(pagename): """ Create a new page Omit the extension, it will create it as .jade file """ page = pagename.lstrip("/").rstrip("/") _, _ext = os.path.splitext(pagename) # If the file doesn't have an extension, we'll just create one if not _ext or _ext == "": page += ".jade" ...
python
def create_page(pagename): """ Create a new page Omit the extension, it will create it as .jade file """ page = pagename.lstrip("/").rstrip("/") _, _ext = os.path.splitext(pagename) # If the file doesn't have an extension, we'll just create one if not _ext or _ext == "": page += ".jade" ...
[ "def", "create_page", "(", "pagename", ")", ":", "page", "=", "pagename", ".", "lstrip", "(", "\"/\"", ")", ".", "rstrip", "(", "\"/\"", ")", "_", ",", "_ext", "=", "os", ".", "path", ".", "splitext", "(", "pagename", ")", "# If the file doesn't have an ...
Create a new page Omit the extension, it will create it as .jade file
[ "Create", "a", "new", "page", "Omit", "the", "extension", "it", "will", "create", "it", "as", ".", "jade", "file" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/cli.py#L263-L304
train
56,719
mardix/Yass
yass/cli.py
serve
def serve(port, no_livereload, open_url): """Serve the site """ engine = Yass(CWD) if not port: port = engine.config.get("local_server.port", 8000) if no_livereload is None: no_livereload = True if engine.config.get("local_server.livereload") is False else False if open_url is None:...
python
def serve(port, no_livereload, open_url): """Serve the site """ engine = Yass(CWD) if not port: port = engine.config.get("local_server.port", 8000) if no_livereload is None: no_livereload = True if engine.config.get("local_server.livereload") is False else False if open_url is None:...
[ "def", "serve", "(", "port", ",", "no_livereload", ",", "open_url", ")", ":", "engine", "=", "Yass", "(", "CWD", ")", "if", "not", "port", ":", "port", "=", "engine", ".", "config", ".", "get", "(", "\"local_server.port\"", ",", "8000", ")", "if", "n...
Serve the site
[ "Serve", "the", "site" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/cli.py#L310-L339
train
56,720
hackedd/gw2api
gw2api/mumble.py
GuildWars2FileMapping.get_map_location
def get_map_location(self): """Get the location of the player, converted to world coordinates. :return: a tuple (x, y, z). """ map_data = self.get_map() (bounds_e, bounds_n), (bounds_w, bounds_s) = map_data["continent_rect"] (map_e, map_n), (map_w, map_s) = map_data["ma...
python
def get_map_location(self): """Get the location of the player, converted to world coordinates. :return: a tuple (x, y, z). """ map_data = self.get_map() (bounds_e, bounds_n), (bounds_w, bounds_s) = map_data["continent_rect"] (map_e, map_n), (map_w, map_s) = map_data["ma...
[ "def", "get_map_location", "(", "self", ")", ":", "map_data", "=", "self", ".", "get_map", "(", ")", "(", "bounds_e", ",", "bounds_n", ")", ",", "(", "bounds_w", ",", "bounds_s", ")", "=", "map_data", "[", "\"continent_rect\"", "]", "(", "map_e", ",", ...
Get the location of the player, converted to world coordinates. :return: a tuple (x, y, z).
[ "Get", "the", "location", "of", "the", "player", "converted", "to", "world", "coordinates", "." ]
5543a78e6e3ed0573b7e84c142c44004b4779eac
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/mumble.py#L93-L117
train
56,721
nuSTORM/gnomon
gnomon/Graph.py
Graph.CreateVertices
def CreateVertices(self, points): """ Returns a dictionary object with keys that are 2tuples represnting a point. """ gr = digraph() for z, x, Q in points: node = (z, x, Q) gr.add_nodes([node]) return gr
python
def CreateVertices(self, points): """ Returns a dictionary object with keys that are 2tuples represnting a point. """ gr = digraph() for z, x, Q in points: node = (z, x, Q) gr.add_nodes([node]) return gr
[ "def", "CreateVertices", "(", "self", ",", "points", ")", ":", "gr", "=", "digraph", "(", ")", "for", "z", ",", "x", ",", "Q", "in", "points", ":", "node", "=", "(", "z", ",", "x", ",", "Q", ")", "gr", ".", "add_nodes", "(", "[", "node", "]",...
Returns a dictionary object with keys that are 2tuples represnting a point.
[ "Returns", "a", "dictionary", "object", "with", "keys", "that", "are", "2tuples", "represnting", "a", "point", "." ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/Graph.py#L29-L40
train
56,722
nuSTORM/gnomon
gnomon/Graph.py
Graph.GetFarthestNode
def GetFarthestNode(self, gr, node): """node is start node""" # Remember: weights are negative distance = minmax.shortest_path_bellman_ford(gr, node)[1] # Find the farthest node, which is end of track min_key = None for key, value in distance.iteritems(): if ...
python
def GetFarthestNode(self, gr, node): """node is start node""" # Remember: weights are negative distance = minmax.shortest_path_bellman_ford(gr, node)[1] # Find the farthest node, which is end of track min_key = None for key, value in distance.iteritems(): if ...
[ "def", "GetFarthestNode", "(", "self", ",", "gr", ",", "node", ")", ":", "# Remember: weights are negative", "distance", "=", "minmax", ".", "shortest_path_bellman_ford", "(", "gr", ",", "node", ")", "[", "1", "]", "# Find the farthest node, which is end of track", ...
node is start node
[ "node", "is", "start", "node" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/Graph.py#L71-L82
train
56,723
Julian/Minion
minion/deferred.py
_CallbackChain.on_success
def on_success(self, fn, *args, **kwargs): """ Call the given callback if or when the connected deferred succeeds. """ self._callbacks.append((fn, args, kwargs)) result = self._resulted_in if result is not _NOTHING_YET: self._succeed(result=result)
python
def on_success(self, fn, *args, **kwargs): """ Call the given callback if or when the connected deferred succeeds. """ self._callbacks.append((fn, args, kwargs)) result = self._resulted_in if result is not _NOTHING_YET: self._succeed(result=result)
[ "def", "on_success", "(", "self", ",", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_callbacks", ".", "append", "(", "(", "fn", ",", "args", ",", "kwargs", ")", ")", "result", "=", "self", ".", "_resulted_in", "if", "r...
Call the given callback if or when the connected deferred succeeds.
[ "Call", "the", "given", "callback", "if", "or", "when", "the", "connected", "deferred", "succeeds", "." ]
518d06f9ffd38dcacc0de4d94e72d1f8452157a8
https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/minion/deferred.py#L35-L45
train
56,724
Julian/Minion
minion/deferred.py
_CallbackChain._succeed
def _succeed(self, result): """ Fire the success chain. """ for fn, args, kwargs in self._callbacks: fn(result, *args, **kwargs) self._resulted_in = result
python
def _succeed(self, result): """ Fire the success chain. """ for fn, args, kwargs in self._callbacks: fn(result, *args, **kwargs) self._resulted_in = result
[ "def", "_succeed", "(", "self", ",", "result", ")", ":", "for", "fn", ",", "args", ",", "kwargs", "in", "self", ".", "_callbacks", ":", "fn", "(", "result", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_resulted_in", "=", "result" ...
Fire the success chain.
[ "Fire", "the", "success", "chain", "." ]
518d06f9ffd38dcacc0de4d94e72d1f8452157a8
https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/minion/deferred.py#L53-L61
train
56,725
nuSTORM/gnomon
gnomon/Configuration.py
fetch_config
def fetch_config(filename): """Fetch the Configuration schema information Finds the schema file, loads the file and reads the JSON, then converts to a dictionary that is returned """ # This trick gets the directory of *this* file Configuration.py thus # allowing to find the schema files relative ...
python
def fetch_config(filename): """Fetch the Configuration schema information Finds the schema file, loads the file and reads the JSON, then converts to a dictionary that is returned """ # This trick gets the directory of *this* file Configuration.py thus # allowing to find the schema files relative ...
[ "def", "fetch_config", "(", "filename", ")", ":", "# This trick gets the directory of *this* file Configuration.py thus", "# allowing to find the schema files relative to this file.", "dir_name", "=", "get_source_dir", "(", ")", "# Append json", "filename", "=", "os", ".", "path...
Fetch the Configuration schema information Finds the schema file, loads the file and reads the JSON, then converts to a dictionary that is returned
[ "Fetch", "the", "Configuration", "schema", "information" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/Configuration.py#L117-L132
train
56,726
nuSTORM/gnomon
gnomon/Configuration.py
populate_args_level
def populate_args_level(schema, parser): """Use a schema to populate a command line argument parser""" for key, value in schema['properties'].iteritems(): if key == 'name': continue arg = '--%s' % key desc = value['description'] if 'type' in value: if va...
python
def populate_args_level(schema, parser): """Use a schema to populate a command line argument parser""" for key, value in schema['properties'].iteritems(): if key == 'name': continue arg = '--%s' % key desc = value['description'] if 'type' in value: if va...
[ "def", "populate_args_level", "(", "schema", ",", "parser", ")", ":", "for", "key", ",", "value", "in", "schema", "[", "'properties'", "]", ".", "iteritems", "(", ")", ":", "if", "key", "==", "'name'", ":", "continue", "arg", "=", "'--%s'", "%", "key",...
Use a schema to populate a command line argument parser
[ "Use", "a", "schema", "to", "populate", "a", "command", "line", "argument", "parser" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/Configuration.py#L143-L173
train
56,727
nuSTORM/gnomon
gnomon/Configuration.py
ConfigurationBase.set_json
def set_json(self, config_json): """Permanently set the JSON configuration Unable to call twice.""" if self.configuration_dict is not None: raise RuntimeError("Can only set configuration once", self.configuration_dict) schema = fetch_config('ConfigurationSchema.json') ...
python
def set_json(self, config_json): """Permanently set the JSON configuration Unable to call twice.""" if self.configuration_dict is not None: raise RuntimeError("Can only set configuration once", self.configuration_dict) schema = fetch_config('ConfigurationSchema.json') ...
[ "def", "set_json", "(", "self", ",", "config_json", ")", ":", "if", "self", ".", "configuration_dict", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"Can only set configuration once\"", ",", "self", ".", "configuration_dict", ")", "schema", "=", "fet...
Permanently set the JSON configuration Unable to call twice.
[ "Permanently", "set", "the", "JSON", "configuration" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/Configuration.py#L43-L60
train
56,728
inveniosoftware-attic/invenio-utils
invenio_utils/mimetype.py
file_strip_ext
def file_strip_ext( afile, skip_version=False, only_known_extensions=False, allow_subformat=True): """ Strip in the best way the extension from a filename. >>> file_strip_ext("foo.tar.gz") 'foo' >>> file_strip_ext("foo.buz.gz") 'foo.buz' >>> file_strip_ext("f...
python
def file_strip_ext( afile, skip_version=False, only_known_extensions=False, allow_subformat=True): """ Strip in the best way the extension from a filename. >>> file_strip_ext("foo.tar.gz") 'foo' >>> file_strip_ext("foo.buz.gz") 'foo.buz' >>> file_strip_ext("f...
[ "def", "file_strip_ext", "(", "afile", ",", "skip_version", "=", "False", ",", "only_known_extensions", "=", "False", ",", "allow_subformat", "=", "True", ")", ":", "import", "os", "afile", "=", "afile", ".", "split", "(", "';'", ")", "if", "len", "(", "...
Strip in the best way the extension from a filename. >>> file_strip_ext("foo.tar.gz") 'foo' >>> file_strip_ext("foo.buz.gz") 'foo.buz' >>> file_strip_ext("foo.buz") 'foo' >>> file_strip_ext("foo.buz", only_known_extensions=True) 'foo.buz' >>> file_strip_ext("foo.buz;1", skip_version...
[ "Strip", "in", "the", "best", "way", "the", "extension", "from", "a", "filename", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/mimetype.py#L142-L193
train
56,729
inveniosoftware-attic/invenio-utils
invenio_utils/mimetype.py
guess_extension
def guess_extension(amimetype, normalize=False): """ Tries to guess extension for a mimetype. @param amimetype: name of a mimetype @time amimetype: string @return: the extension @rtype: string """ ext = _mimes.guess_extension(amimetype) if ext and normalize: # Normalize some...
python
def guess_extension(amimetype, normalize=False): """ Tries to guess extension for a mimetype. @param amimetype: name of a mimetype @time amimetype: string @return: the extension @rtype: string """ ext = _mimes.guess_extension(amimetype) if ext and normalize: # Normalize some...
[ "def", "guess_extension", "(", "amimetype", ",", "normalize", "=", "False", ")", ":", "ext", "=", "_mimes", ".", "guess_extension", "(", "amimetype", ")", "if", "ext", "and", "normalize", ":", "# Normalize some common magic mis-interpreation", "ext", "=", "{", "...
Tries to guess extension for a mimetype. @param amimetype: name of a mimetype @time amimetype: string @return: the extension @rtype: string
[ "Tries", "to", "guess", "extension", "for", "a", "mimetype", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/mimetype.py#L208-L223
train
56,730
inveniosoftware-attic/invenio-utils
invenio_utils/mimetype.py
get_magic_guesses
def get_magic_guesses(fullpath): """ Return all the possible guesses from the magic library about the content of the file. @param fullpath: location of the file @type fullpath: string @return: guesses about content of the file @rtype: tuple """ if CFG_HAS_MAGIC == 1: magic_c...
python
def get_magic_guesses(fullpath): """ Return all the possible guesses from the magic library about the content of the file. @param fullpath: location of the file @type fullpath: string @return: guesses about content of the file @rtype: tuple """ if CFG_HAS_MAGIC == 1: magic_c...
[ "def", "get_magic_guesses", "(", "fullpath", ")", ":", "if", "CFG_HAS_MAGIC", "==", "1", ":", "magic_cookies", "=", "_get_magic_cookies", "(", ")", "magic_result", "=", "[", "]", "for", "key", "in", "magic_cookies", ".", "keys", "(", ")", ":", "magic_result"...
Return all the possible guesses from the magic library about the content of the file. @param fullpath: location of the file @type fullpath: string @return: guesses about content of the file @rtype: tuple
[ "Return", "all", "the", "possible", "guesses", "from", "the", "magic", "library", "about", "the", "content", "of", "the", "file", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/mimetype.py#L226-L248
train
56,731
inveniosoftware-attic/invenio-utils
invenio_utils/mimetype.py
LazyMimeCache.mimes
def mimes(self): """ Returns extended MimeTypes. """ _mimes = MimeTypes(strict=False) _mimes.suffix_map.update({'.tbz2': '.tar.bz2'}) _mimes.encodings_map.update({'.bz2': 'bzip2'}) if cfg['CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYPES']: for key, value in...
python
def mimes(self): """ Returns extended MimeTypes. """ _mimes = MimeTypes(strict=False) _mimes.suffix_map.update({'.tbz2': '.tar.bz2'}) _mimes.encodings_map.update({'.bz2': 'bzip2'}) if cfg['CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYPES']: for key, value in...
[ "def", "mimes", "(", "self", ")", ":", "_mimes", "=", "MimeTypes", "(", "strict", "=", "False", ")", "_mimes", ".", "suffix_map", ".", "update", "(", "{", "'.tbz2'", ":", "'.tar.bz2'", "}", ")", "_mimes", ".", "encodings_map", ".", "update", "(", "{", ...
Returns extended MimeTypes.
[ "Returns", "extended", "MimeTypes", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/mimetype.py#L89-L103
train
56,732
inveniosoftware-attic/invenio-utils
invenio_utils/mimetype.py
LazyMimeCache.extensions
def extensions(self): """ Generate the regular expression to match all the known extensions. @return: the regular expression. @rtype: regular expression object """ _tmp_extensions = self.mimes.encodings_map.keys() + \ self.mimes.suffix_map.keys() + \ ...
python
def extensions(self): """ Generate the regular expression to match all the known extensions. @return: the regular expression. @rtype: regular expression object """ _tmp_extensions = self.mimes.encodings_map.keys() + \ self.mimes.suffix_map.keys() + \ ...
[ "def", "extensions", "(", "self", ")", ":", "_tmp_extensions", "=", "self", ".", "mimes", ".", "encodings_map", ".", "keys", "(", ")", "+", "self", ".", "mimes", ".", "suffix_map", ".", "keys", "(", ")", "+", "self", ".", "mimes", ".", "types_map", "...
Generate the regular expression to match all the known extensions. @return: the regular expression. @rtype: regular expression object
[ "Generate", "the", "regular", "expression", "to", "match", "all", "the", "known", "extensions", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/mimetype.py#L106-L128
train
56,733
jaraco/jaraco.services
jaraco/services/__init__.py
ServiceManager.start
def start(self, service): """ Start the service, catching and logging exceptions """ try: map(self.start_class, service.depends) if service.is_running(): return if service in self.failed: log.warning("%s previously faile...
python
def start(self, service): """ Start the service, catching and logging exceptions """ try: map(self.start_class, service.depends) if service.is_running(): return if service in self.failed: log.warning("%s previously faile...
[ "def", "start", "(", "self", ",", "service", ")", ":", "try", ":", "map", "(", "self", ".", "start_class", ",", "service", ".", "depends", ")", "if", "service", ".", "is_running", "(", ")", ":", "return", "if", "service", "in", "self", ".", "failed",...
Start the service, catching and logging exceptions
[ "Start", "the", "service", "catching", "and", "logging", "exceptions" ]
4ccce53541201f778035b69e9c59e41e34ee5992
https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L73-L87
train
56,734
jaraco/jaraco.services
jaraco/services/__init__.py
ServiceManager.start_class
def start_class(self, class_): """ Start all services of a given class. If this manager doesn't already have a service of that class, it constructs one and starts it. """ matches = filter(lambda svc: isinstance(svc, class_), self) if not matches: svc = class_(...
python
def start_class(self, class_): """ Start all services of a given class. If this manager doesn't already have a service of that class, it constructs one and starts it. """ matches = filter(lambda svc: isinstance(svc, class_), self) if not matches: svc = class_(...
[ "def", "start_class", "(", "self", ",", "class_", ")", ":", "matches", "=", "filter", "(", "lambda", "svc", ":", "isinstance", "(", "svc", ",", "class_", ")", ",", "self", ")", "if", "not", "matches", ":", "svc", "=", "class_", "(", ")", "self", "....
Start all services of a given class. If this manager doesn't already have a service of that class, it constructs one and starts it.
[ "Start", "all", "services", "of", "a", "given", "class", ".", "If", "this", "manager", "doesn", "t", "already", "have", "a", "service", "of", "that", "class", "it", "constructs", "one", "and", "starts", "it", "." ]
4ccce53541201f778035b69e9c59e41e34ee5992
https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L94-L105
train
56,735
jaraco/jaraco.services
jaraco/services/__init__.py
ServiceManager.stop_class
def stop_class(self, class_): "Stop all services of a given class" matches = filter(lambda svc: isinstance(svc, class_), self) map(self.stop, matches)
python
def stop_class(self, class_): "Stop all services of a given class" matches = filter(lambda svc: isinstance(svc, class_), self) map(self.stop, matches)
[ "def", "stop_class", "(", "self", ",", "class_", ")", ":", "matches", "=", "filter", "(", "lambda", "svc", ":", "isinstance", "(", "svc", ",", "class_", ")", ",", "self", ")", "map", "(", "self", ".", "stop", ",", "matches", ")" ]
Stop all services of a given class
[ "Stop", "all", "services", "of", "a", "given", "class" ]
4ccce53541201f778035b69e9c59e41e34ee5992
https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L110-L113
train
56,736
jaraco/jaraco.services
jaraco/services/__init__.py
Subprocess._get_more_data
def _get_more_data(self, file, timeout): """ Return data from the file, if available. If no data is received by the timeout, then raise RuntimeError. """ timeout = datetime.timedelta(seconds=timeout) timer = Stopwatch() while timer.split() < timeout: d...
python
def _get_more_data(self, file, timeout): """ Return data from the file, if available. If no data is received by the timeout, then raise RuntimeError. """ timeout = datetime.timedelta(seconds=timeout) timer = Stopwatch() while timer.split() < timeout: d...
[ "def", "_get_more_data", "(", "self", ",", "file", ",", "timeout", ")", ":", "timeout", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "timeout", ")", "timer", "=", "Stopwatch", "(", ")", "while", "timer", ".", "split", "(", ")", "<", "timeout...
Return data from the file, if available. If no data is received by the timeout, then raise RuntimeError.
[ "Return", "data", "from", "the", "file", "if", "available", ".", "If", "no", "data", "is", "received", "by", "the", "timeout", "then", "raise", "RuntimeError", "." ]
4ccce53541201f778035b69e9c59e41e34ee5992
https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L233-L244
train
56,737
jaraco/jaraco.services
jaraco/services/__init__.py
PythonService._run_env
def _run_env(self): """ Augment the current environment providing the PYTHONUSERBASE. """ env = dict(os.environ) env.update( getattr(self, 'env', {}), PYTHONUSERBASE=self.env_path, PIP_USER="1", ) self._disable_venv(env) ...
python
def _run_env(self): """ Augment the current environment providing the PYTHONUSERBASE. """ env = dict(os.environ) env.update( getattr(self, 'env', {}), PYTHONUSERBASE=self.env_path, PIP_USER="1", ) self._disable_venv(env) ...
[ "def", "_run_env", "(", "self", ")", ":", "env", "=", "dict", "(", "os", ".", "environ", ")", "env", ".", "update", "(", "getattr", "(", "self", ",", "'env'", ",", "{", "}", ")", ",", "PYTHONUSERBASE", "=", "self", ".", "env_path", ",", "PIP_USER",...
Augment the current environment providing the PYTHONUSERBASE.
[ "Augment", "the", "current", "environment", "providing", "the", "PYTHONUSERBASE", "." ]
4ccce53541201f778035b69e9c59e41e34ee5992
https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L350-L361
train
56,738
jaraco/jaraco.services
jaraco/services/__init__.py
PythonService._disable_venv
def _disable_venv(self, env): """ Disable virtualenv and venv in the environment. """ venv = env.pop('VIRTUAL_ENV', None) if venv: venv_path, sep, env['PATH'] = env['PATH'].partition(os.pathsep)
python
def _disable_venv(self, env): """ Disable virtualenv and venv in the environment. """ venv = env.pop('VIRTUAL_ENV', None) if venv: venv_path, sep, env['PATH'] = env['PATH'].partition(os.pathsep)
[ "def", "_disable_venv", "(", "self", ",", "env", ")", ":", "venv", "=", "env", ".", "pop", "(", "'VIRTUAL_ENV'", ",", "None", ")", "if", "venv", ":", "venv_path", ",", "sep", ",", "env", "[", "'PATH'", "]", "=", "env", "[", "'PATH'", "]", ".", "p...
Disable virtualenv and venv in the environment.
[ "Disable", "virtualenv", "and", "venv", "in", "the", "environment", "." ]
4ccce53541201f778035b69e9c59e41e34ee5992
https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L363-L369
train
56,739
jaraco/jaraco.services
jaraco/services/__init__.py
PythonService.create_env
def create_env(self): """ Create a PEP-370 environment """ root = path.Path(os.environ.get('SERVICES_ROOT', 'services')) self.env_path = (root / self.name).abspath() cmd = [ self.python, '-c', 'import site; print(site.getusersitepackages())', ...
python
def create_env(self): """ Create a PEP-370 environment """ root = path.Path(os.environ.get('SERVICES_ROOT', 'services')) self.env_path = (root / self.name).abspath() cmd = [ self.python, '-c', 'import site; print(site.getusersitepackages())', ...
[ "def", "create_env", "(", "self", ")", ":", "root", "=", "path", ".", "Path", "(", "os", ".", "environ", ".", "get", "(", "'SERVICES_ROOT'", ",", "'services'", ")", ")", "self", ".", "env_path", "=", "(", "root", "/", "self", ".", "name", ")", ".",...
Create a PEP-370 environment
[ "Create", "a", "PEP", "-", "370", "environment" ]
4ccce53541201f778035b69e9c59e41e34ee5992
https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L371-L383
train
56,740
objectrocket/python-client
objectrocket/instances/mongodb.py
MongodbInstance.compaction
def compaction(self, request_compaction=False): """Retrieve a report on, or request compaction for this instance. :param bool request_compaction: A boolean indicating whether or not to request compaction. """ url = self._service_url + 'compaction/' if request_compaction: ...
python
def compaction(self, request_compaction=False): """Retrieve a report on, or request compaction for this instance. :param bool request_compaction: A boolean indicating whether or not to request compaction. """ url = self._service_url + 'compaction/' if request_compaction: ...
[ "def", "compaction", "(", "self", ",", "request_compaction", "=", "False", ")", ":", "url", "=", "self", ".", "_service_url", "+", "'compaction/'", "if", "request_compaction", ":", "response", "=", "requests", ".", "post", "(", "url", ",", "*", "*", "self"...
Retrieve a report on, or request compaction for this instance. :param bool request_compaction: A boolean indicating whether or not to request compaction.
[ "Retrieve", "a", "report", "on", "or", "request", "compaction", "for", "this", "instance", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L48-L60
train
56,741
objectrocket/python-client
objectrocket/instances/mongodb.py
MongodbInstance.get_authenticated_connection
def get_authenticated_connection(self, user, passwd, db='admin', ssl=True): """Get an authenticated connection to this instance. :param str user: The username to use for authentication. :param str passwd: The password to use for authentication. :param str db: The name of the database to...
python
def get_authenticated_connection(self, user, passwd, db='admin', ssl=True): """Get an authenticated connection to this instance. :param str user: The username to use for authentication. :param str passwd: The password to use for authentication. :param str db: The name of the database to...
[ "def", "get_authenticated_connection", "(", "self", ",", "user", ",", "passwd", ",", "db", "=", "'admin'", ",", "ssl", "=", "True", ")", ":", "# Attempt to establish an authenticated connection.", "try", ":", "connection", "=", "self", ".", "get_connection", "(", ...
Get an authenticated connection to this instance. :param str user: The username to use for authentication. :param str passwd: The password to use for authentication. :param str db: The name of the database to authenticate against. Defaults to ``'Admin'``. :param bool ssl: Use SSL/TLS if...
[ "Get", "an", "authenticated", "connection", "to", "this", "instance", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L62-L80
train
56,742
objectrocket/python-client
objectrocket/instances/mongodb.py
MongodbInstance.shards
def shards(self, add_shard=False): """Get a list of shards belonging to this instance. :param bool add_shard: A boolean indicating whether to add a new shard to the specified instance. """ url = self._service_url + 'shards/' if add_shard: response = reque...
python
def shards(self, add_shard=False): """Get a list of shards belonging to this instance. :param bool add_shard: A boolean indicating whether to add a new shard to the specified instance. """ url = self._service_url + 'shards/' if add_shard: response = reque...
[ "def", "shards", "(", "self", ",", "add_shard", "=", "False", ")", ":", "url", "=", "self", ".", "_service_url", "+", "'shards/'", "if", "add_shard", ":", "response", "=", "requests", ".", "post", "(", "url", ",", "*", "*", "self", ".", "_instances", ...
Get a list of shards belonging to this instance. :param bool add_shard: A boolean indicating whether to add a new shard to the specified instance.
[ "Get", "a", "list", "of", "shards", "belonging", "to", "this", "instance", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L90-L102
train
56,743
objectrocket/python-client
objectrocket/instances/mongodb.py
MongodbInstance.new_relic_stats
def new_relic_stats(self): """ Get stats for this instance. """ if self._new_relic_stats is None: # if this is a sharded instance, fetch shard stats in parallel if self.type == 'mongodb_sharded': shards = [Shard(self.name, self._service_url + 'shar...
python
def new_relic_stats(self): """ Get stats for this instance. """ if self._new_relic_stats is None: # if this is a sharded instance, fetch shard stats in parallel if self.type == 'mongodb_sharded': shards = [Shard(self.name, self._service_url + 'shar...
[ "def", "new_relic_stats", "(", "self", ")", ":", "if", "self", ".", "_new_relic_stats", "is", "None", ":", "# if this is a sharded instance, fetch shard stats in parallel", "if", "self", ".", "type", "==", "'mongodb_sharded'", ":", "shards", "=", "[", "Shard", "(", ...
Get stats for this instance.
[ "Get", "stats", "for", "this", "instance", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L110-L145
train
56,744
objectrocket/python-client
objectrocket/instances/mongodb.py
MongodbInstance._rollup_shard_stats_to_instance_stats
def _rollup_shard_stats_to_instance_stats(self, shard_stats): """ roll up all shard stats to instance level stats :param shard_stats: dict of {shard_name: shard level stats} """ instance_stats = {} opcounters_per_node = [] # aggregate replication_lag ins...
python
def _rollup_shard_stats_to_instance_stats(self, shard_stats): """ roll up all shard stats to instance level stats :param shard_stats: dict of {shard_name: shard level stats} """ instance_stats = {} opcounters_per_node = [] # aggregate replication_lag ins...
[ "def", "_rollup_shard_stats_to_instance_stats", "(", "self", ",", "shard_stats", ")", ":", "instance_stats", "=", "{", "}", "opcounters_per_node", "=", "[", "]", "# aggregate replication_lag", "instance_stats", "[", "'replication_lag'", "]", "=", "max", "(", "map", ...
roll up all shard stats to instance level stats :param shard_stats: dict of {shard_name: shard level stats}
[ "roll", "up", "all", "shard", "stats", "to", "instance", "level", "stats" ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L147-L174
train
56,745
objectrocket/python-client
objectrocket/instances/mongodb.py
MongodbInstance._compile_new_relic_stats
def _compile_new_relic_stats(self, stats_this_second, stats_next_second): """ from instance 'stats_this_second' and instance 'stats_next_second', compute some per second stats metrics and other aggregated metrics :param dict stats_this_second: :param dict stats_next_second: ...
python
def _compile_new_relic_stats(self, stats_this_second, stats_next_second): """ from instance 'stats_this_second' and instance 'stats_next_second', compute some per second stats metrics and other aggregated metrics :param dict stats_this_second: :param dict stats_next_second: ...
[ "def", "_compile_new_relic_stats", "(", "self", ",", "stats_this_second", ",", "stats_next_second", ")", ":", "server_statistics_per_second", "=", "{", "}", "opcounters_per_node_per_second", "=", "[", "]", "for", "subdoc", "in", "[", "\"opcounters\"", ",", "\"network\...
from instance 'stats_this_second' and instance 'stats_next_second', compute some per second stats metrics and other aggregated metrics :param dict stats_this_second: :param dict stats_next_second: :return: compiled instance stats that has metrics {'opcounters_per_node_per_secon...
[ "from", "instance", "stats_this_second", "and", "instance", "stats_next_second", "compute", "some", "per", "second", "stats", "metrics", "and", "other", "aggregated", "metrics" ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L176-L213
train
56,746
objectrocket/python-client
objectrocket/instances/mongodb.py
MongodbInstance.get_stepdown_window
def get_stepdown_window(self): """Get information on this instance's stepdown window.""" url = self._service_url + 'stepdown/' response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
python
def get_stepdown_window(self): """Get information on this instance's stepdown window.""" url = self._service_url + 'stepdown/' response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
[ "def", "get_stepdown_window", "(", "self", ")", ":", "url", "=", "self", ".", "_service_url", "+", "'stepdown/'", "response", "=", "requests", ".", "get", "(", "url", ",", "*", "*", "self", ".", "_instances", ".", "_default_request_kwargs", ")", "return", ...
Get information on this instance's stepdown window.
[ "Get", "information", "on", "this", "instance", "s", "stepdown", "window", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L221-L225
train
56,747
objectrocket/python-client
objectrocket/instances/mongodb.py
MongodbInstance.set_stepdown_window
def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True): """Set the stepdown window for this instance. Date times are assumed to be UTC, so use UTC date times. :param datetime.datetime start: The datetime which the stepdown window is to open. :param datetim...
python
def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True): """Set the stepdown window for this instance. Date times are assumed to be UTC, so use UTC date times. :param datetime.datetime start: The datetime which the stepdown window is to open. :param datetim...
[ "def", "set_stepdown_window", "(", "self", ",", "start", ",", "end", ",", "enabled", "=", "True", ",", "scheduled", "=", "True", ",", "weekly", "=", "True", ")", ":", "# Ensure a logical start and endtime is requested.", "if", "not", "start", "<", "end", ":", ...
Set the stepdown window for this instance. Date times are assumed to be UTC, so use UTC date times. :param datetime.datetime start: The datetime which the stepdown window is to open. :param datetime.datetime end: The datetime which the stepdown window is to close. :param bool enabled: ...
[ "Set", "the", "stepdown", "window", "for", "this", "instance", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L228-L262
train
56,748
tradenity/python-sdk
tradenity/resources/payment_card.py
PaymentCard.brand
def brand(self, brand): """Sets the brand of this PaymentCard. :param brand: The brand of this PaymentCard. :type: str """ allowed_values = ["visa", "mastercard", "americanExpress", "discover"] if brand is not None and brand not in allowed_values: raise Valu...
python
def brand(self, brand): """Sets the brand of this PaymentCard. :param brand: The brand of this PaymentCard. :type: str """ allowed_values = ["visa", "mastercard", "americanExpress", "discover"] if brand is not None and brand not in allowed_values: raise Valu...
[ "def", "brand", "(", "self", ",", "brand", ")", ":", "allowed_values", "=", "[", "\"visa\"", ",", "\"mastercard\"", ",", "\"americanExpress\"", ",", "\"discover\"", "]", "if", "brand", "is", "not", "None", "and", "brand", "not", "in", "allowed_values", ":", ...
Sets the brand of this PaymentCard. :param brand: The brand of this PaymentCard. :type: str
[ "Sets", "the", "brand", "of", "this", "PaymentCard", "." ]
d13fbe23f4d6ff22554c6d8d2deaf209371adaf1
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/payment_card.py#L253-L267
train
56,749
orbeckst/RecSQL
recsql/export.py
latex_quote
def latex_quote(s): """Quote special characters for LaTeX. (Incomplete, currently only deals with underscores, dollar and hash.) """ special = {'_':r'\_', '$':r'\$', '#':r'\#'} s = str(s) for char,repl in special.items(): new = s.replace(char, repl) s = new[:] return s
python
def latex_quote(s): """Quote special characters for LaTeX. (Incomplete, currently only deals with underscores, dollar and hash.) """ special = {'_':r'\_', '$':r'\$', '#':r'\#'} s = str(s) for char,repl in special.items(): new = s.replace(char, repl) s = new[:] return s
[ "def", "latex_quote", "(", "s", ")", ":", "special", "=", "{", "'_'", ":", "r'\\_'", ",", "'$'", ":", "r'\\$'", ",", "'#'", ":", "r'\\#'", "}", "s", "=", "str", "(", "s", ")", "for", "char", ",", "repl", "in", "special", ".", "items", "(", ")",...
Quote special characters for LaTeX. (Incomplete, currently only deals with underscores, dollar and hash.)
[ "Quote", "special", "characters", "for", "LaTeX", "." ]
6acbf821022361719391697c9c2f0822f9f8022a
https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/export.py#L38-L48
train
56,750
Aluriak/bubble-tools
bubbletools/_bubble.py
tree_to_file
def tree_to_file(tree:'BubbleTree', outfile:str): """Compute the bubble representation of given power graph, and push it into given file.""" with open(outfile, 'w') as fd: fd.write(tree_to_bubble(tree))
python
def tree_to_file(tree:'BubbleTree', outfile:str): """Compute the bubble representation of given power graph, and push it into given file.""" with open(outfile, 'w') as fd: fd.write(tree_to_bubble(tree))
[ "def", "tree_to_file", "(", "tree", ":", "'BubbleTree'", ",", "outfile", ":", "str", ")", ":", "with", "open", "(", "outfile", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "tree_to_bubble", "(", "tree", ")", ")" ]
Compute the bubble representation of given power graph, and push it into given file.
[ "Compute", "the", "bubble", "representation", "of", "given", "power", "graph", "and", "push", "it", "into", "given", "file", "." ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/_bubble.py#L1-L5
train
56,751
Aluriak/bubble-tools
bubbletools/_bubble.py
lines_from_tree
def lines_from_tree(tree, nodes_and_set:bool=False) -> iter: """Yield lines of bubble describing given BubbleTree""" NODE = 'NODE\t{}' INCL = 'IN\t{}\t{}' EDGE = 'EDGE\t{}\t{}\t1.0' SET = 'SET\t{}' if nodes_and_set: for node in tree.nodes(): yield NODE.format(node) ...
python
def lines_from_tree(tree, nodes_and_set:bool=False) -> iter: """Yield lines of bubble describing given BubbleTree""" NODE = 'NODE\t{}' INCL = 'IN\t{}\t{}' EDGE = 'EDGE\t{}\t{}\t1.0' SET = 'SET\t{}' if nodes_and_set: for node in tree.nodes(): yield NODE.format(node) ...
[ "def", "lines_from_tree", "(", "tree", ",", "nodes_and_set", ":", "bool", "=", "False", ")", "->", "iter", ":", "NODE", "=", "'NODE\\t{}'", "INCL", "=", "'IN\\t{}\\t{}'", "EDGE", "=", "'EDGE\\t{}\\t{}\\t1.0'", "SET", "=", "'SET\\t{}'", "if", "nodes_and_set", "...
Yield lines of bubble describing given BubbleTree
[ "Yield", "lines", "of", "bubble", "describing", "given", "BubbleTree" ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/_bubble.py#L16-L36
train
56,752
inveniosoftware-attic/invenio-utils
invenio_utils/forms.py
TimeField.process_formdata
def process_formdata(self, valuelist): """Join time string.""" if valuelist: time_str = u' '.join(valuelist) try: timetuple = time.strptime(time_str, self.format) self.data = datetime.time(*timetuple[3:6]) except ValueError: ...
python
def process_formdata(self, valuelist): """Join time string.""" if valuelist: time_str = u' '.join(valuelist) try: timetuple = time.strptime(time_str, self.format) self.data = datetime.time(*timetuple[3:6]) except ValueError: ...
[ "def", "process_formdata", "(", "self", ",", "valuelist", ")", ":", "if", "valuelist", ":", "time_str", "=", "u' '", ".", "join", "(", "valuelist", ")", "try", ":", "timetuple", "=", "time", ".", "strptime", "(", "time_str", ",", "self", ".", "format", ...
Join time string.
[ "Join", "time", "string", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/forms.py#L92-L101
train
56,753
inveniosoftware-attic/invenio-utils
invenio_utils/forms.py
InvenioBaseForm.validate_csrf_token
def validate_csrf_token(self, field): """Disable CRSF proection during testing.""" if current_app.testing: return super(InvenioBaseForm, self).validate_csrf_token(field)
python
def validate_csrf_token(self, field): """Disable CRSF proection during testing.""" if current_app.testing: return super(InvenioBaseForm, self).validate_csrf_token(field)
[ "def", "validate_csrf_token", "(", "self", ",", "field", ")", ":", "if", "current_app", ".", "testing", ":", "return", "super", "(", "InvenioBaseForm", ",", "self", ")", ".", "validate_csrf_token", "(", "field", ")" ]
Disable CRSF proection during testing.
[ "Disable", "CRSF", "proection", "during", "testing", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/forms.py#L370-L374
train
56,754
wdbm/abstraction
abstraction.py
load_exchange_word_vectors
def load_exchange_word_vectors( filename = "database.db", maximum_number_of_events = None ): """ Load exchange data and return dataset. """ log.info("load word vectors of database {filename}".format( filename = filename )) # Ensure that the database exists. ...
python
def load_exchange_word_vectors( filename = "database.db", maximum_number_of_events = None ): """ Load exchange data and return dataset. """ log.info("load word vectors of database {filename}".format( filename = filename )) # Ensure that the database exists. ...
[ "def", "load_exchange_word_vectors", "(", "filename", "=", "\"database.db\"", ",", "maximum_number_of_events", "=", "None", ")", ":", "log", ".", "info", "(", "\"load word vectors of database {filename}\"", ".", "format", "(", "filename", "=", "filename", ")", ")", ...
Load exchange data and return dataset.
[ "Load", "exchange", "data", "and", "return", "dataset", "." ]
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L314-L373
train
56,755
wdbm/abstraction
abstraction.py
load_HEP_data
def load_HEP_data( ROOT_filename = "output.root", tree_name = "nominal", maximum_number_of_events = None ): """ Load HEP data and return dataset. """ ROOT_file = open_ROOT_file(ROOT_filename) tree = ROOT_file.Get(tree_name) number_of_e...
python
def load_HEP_data( ROOT_filename = "output.root", tree_name = "nominal", maximum_number_of_events = None ): """ Load HEP data and return dataset. """ ROOT_file = open_ROOT_file(ROOT_filename) tree = ROOT_file.Get(tree_name) number_of_e...
[ "def", "load_HEP_data", "(", "ROOT_filename", "=", "\"output.root\"", ",", "tree_name", "=", "\"nominal\"", ",", "maximum_number_of_events", "=", "None", ")", ":", "ROOT_file", "=", "open_ROOT_file", "(", "ROOT_filename", ")", "tree", "=", "ROOT_file", ".", "Get",...
Load HEP data and return dataset.
[ "Load", "HEP", "data", "and", "return", "dataset", "." ]
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L408-L480
train
56,756
wdbm/abstraction
abstraction.py
sentiment
def sentiment( text = None, confidence = False ): """ This function accepts a string text input. It calculates the sentiment of the text, "pos" or "neg". By default, it returns this calculated sentiment. If selected, it returns a tuple of the calculated sentiment and the classifica...
python
def sentiment( text = None, confidence = False ): """ This function accepts a string text input. It calculates the sentiment of the text, "pos" or "neg". By default, it returns this calculated sentiment. If selected, it returns a tuple of the calculated sentiment and the classifica...
[ "def", "sentiment", "(", "text", "=", "None", ",", "confidence", "=", "False", ")", ":", "try", ":", "words", "=", "text", ".", "split", "(", "\" \"", ")", "# Remove empty strings.", "words", "=", "[", "word", "for", "word", "in", "words", "if", "word"...
This function accepts a string text input. It calculates the sentiment of the text, "pos" or "neg". By default, it returns this calculated sentiment. If selected, it returns a tuple of the calculated sentiment and the classificaton confidence.
[ "This", "function", "accepts", "a", "string", "text", "input", ".", "It", "calculates", "the", "sentiment", "of", "the", "text", "pos", "or", "neg", ".", "By", "default", "it", "returns", "this", "calculated", "sentiment", ".", "If", "selected", "it", "ret...
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L1930-L1956
train
56,757
wdbm/abstraction
abstraction.py
Tweets.usernames
def usernames( self ): """ This function returns the list of unique usernames corresponding to the tweets stored in self. """ try: return list(set([tweet.username for tweet in self])) except: log.error("error -- possibly a problem w...
python
def usernames( self ): """ This function returns the list of unique usernames corresponding to the tweets stored in self. """ try: return list(set([tweet.username for tweet in self])) except: log.error("error -- possibly a problem w...
[ "def", "usernames", "(", "self", ")", ":", "try", ":", "return", "list", "(", "set", "(", "[", "tweet", ".", "username", "for", "tweet", "in", "self", "]", ")", ")", "except", ":", "log", ".", "error", "(", "\"error -- possibly a problem with tweets stored...
This function returns the list of unique usernames corresponding to the tweets stored in self.
[ "This", "function", "returns", "the", "list", "of", "unique", "usernames", "corresponding", "to", "the", "tweets", "stored", "in", "self", "." ]
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L824-L834
train
56,758
wdbm/abstraction
abstraction.py
Tweets.user_sentiments
def user_sentiments( self, username = None ): """ This function returns a list of all sentiments of the tweets of a specified user. """ try: return [tweet.sentiment for tweet in self if tweet.username == username] except: log...
python
def user_sentiments( self, username = None ): """ This function returns a list of all sentiments of the tweets of a specified user. """ try: return [tweet.sentiment for tweet in self if tweet.username == username] except: log...
[ "def", "user_sentiments", "(", "self", ",", "username", "=", "None", ")", ":", "try", ":", "return", "[", "tweet", ".", "sentiment", "for", "tweet", "in", "self", "if", "tweet", ".", "username", "==", "username", "]", "except", ":", "log", ".", "error"...
This function returns a list of all sentiments of the tweets of a specified user.
[ "This", "function", "returns", "a", "list", "of", "all", "sentiments", "of", "the", "tweets", "of", "a", "specified", "user", "." ]
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L836-L848
train
56,759
wdbm/abstraction
abstraction.py
Tweets.user_sentiments_most_frequent
def user_sentiments_most_frequent( self, username = None, single_most_frequent = True ): """ This function returns the most frequent calculated sentiments expressed in tweets of a specified user. By default, the single most frequent sentiment i...
python
def user_sentiments_most_frequent( self, username = None, single_most_frequent = True ): """ This function returns the most frequent calculated sentiments expressed in tweets of a specified user. By default, the single most frequent sentiment i...
[ "def", "user_sentiments_most_frequent", "(", "self", ",", "username", "=", "None", ",", "single_most_frequent", "=", "True", ")", ":", "try", ":", "sentiment_frequencies", "=", "collections", ".", "Counter", "(", "self", ".", "user_sentiments", "(", "username", ...
This function returns the most frequent calculated sentiments expressed in tweets of a specified user. By default, the single most frequent sentiment is returned. All sentiments with their corresponding frequencies can be returned also.
[ "This", "function", "returns", "the", "most", "frequent", "calculated", "sentiments", "expressed", "in", "tweets", "of", "a", "specified", "user", ".", "By", "default", "the", "single", "most", "frequent", "sentiment", "is", "returned", ".", "All", "sentiments",...
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L850-L871
train
56,760
wdbm/abstraction
abstraction.py
Tweets.users_sentiments_single_most_frequent
def users_sentiments_single_most_frequent( self, usernames = None, ): """ This function returns the single most frequent calculated sentiment expressed by all stored users or by a list of specified users as a dictionary. """ users_sentiments_single...
python
def users_sentiments_single_most_frequent( self, usernames = None, ): """ This function returns the single most frequent calculated sentiment expressed by all stored users or by a list of specified users as a dictionary. """ users_sentiments_single...
[ "def", "users_sentiments_single_most_frequent", "(", "self", ",", "usernames", "=", "None", ",", ")", ":", "users_sentiments_single_most_frequent", "=", "dict", "(", ")", "if", "usernames", "is", "None", ":", "usernames", "=", "self", ".", "usernames", "(", ")",...
This function returns the single most frequent calculated sentiment expressed by all stored users or by a list of specified users as a dictionary.
[ "This", "function", "returns", "the", "single", "most", "frequent", "calculated", "sentiment", "expressed", "by", "all", "stored", "users", "or", "by", "a", "list", "of", "specified", "users", "as", "a", "dictionary", "." ]
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L873-L895
train
56,761
trevisanj/a99
a99/textinterface.py
format_progress
def format_progress(i, n): """Returns string containing a progress bar, a percentage, etc.""" if n == 0: fraction = 0 else: fraction = float(i)/n LEN_BAR = 25 num_plus = int(round(fraction*LEN_BAR)) s_plus = '+'*num_plus s_point = '.'*(LEN_BAR-num_plus) return '...
python
def format_progress(i, n): """Returns string containing a progress bar, a percentage, etc.""" if n == 0: fraction = 0 else: fraction = float(i)/n LEN_BAR = 25 num_plus = int(round(fraction*LEN_BAR)) s_plus = '+'*num_plus s_point = '.'*(LEN_BAR-num_plus) return '...
[ "def", "format_progress", "(", "i", ",", "n", ")", ":", "if", "n", "==", "0", ":", "fraction", "=", "0", "else", ":", "fraction", "=", "float", "(", "i", ")", "/", "n", "LEN_BAR", "=", "25", "num_plus", "=", "int", "(", "round", "(", "fraction", ...
Returns string containing a progress bar, a percentage, etc.
[ "Returns", "string", "containing", "a", "progress", "bar", "a", "percentage", "etc", "." ]
193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/textinterface.py#L284-L294
train
56,762
trevisanj/a99
a99/textinterface.py
_format_exe_info
def _format_exe_info(py_len, exeinfo, format, indlevel): """Renders ExeInfo object in specified format""" ret = [] ind = " " * indlevel * NIND if format.startswith("text") else "" if format == "markdown-list": for si in exeinfo: ret.append(" - `{0!s}`: {1!s}".format(si.filenam...
python
def _format_exe_info(py_len, exeinfo, format, indlevel): """Renders ExeInfo object in specified format""" ret = [] ind = " " * indlevel * NIND if format.startswith("text") else "" if format == "markdown-list": for si in exeinfo: ret.append(" - `{0!s}`: {1!s}".format(si.filenam...
[ "def", "_format_exe_info", "(", "py_len", ",", "exeinfo", ",", "format", ",", "indlevel", ")", ":", "ret", "=", "[", "]", "ind", "=", "\" \"", "*", "indlevel", "*", "NIND", "if", "format", ".", "startswith", "(", "\"text\"", ")", "else", "\"\"", "if", ...
Renders ExeInfo object in specified format
[ "Renders", "ExeInfo", "object", "in", "specified", "format" ]
193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/textinterface.py#L301-L329
train
56,763
koenedaele/pyramid_skosprovider
pyramid_skosprovider/renderers.py
_map_relation
def _map_relation(c, language='any'): """ Map related concept or collection, leaving out the relations. :param c: the concept or collection to map :param string language: Language to render the relation's label in :rtype: :class:`dict` """ label = c.label(language) return { 'id'...
python
def _map_relation(c, language='any'): """ Map related concept or collection, leaving out the relations. :param c: the concept or collection to map :param string language: Language to render the relation's label in :rtype: :class:`dict` """ label = c.label(language) return { 'id'...
[ "def", "_map_relation", "(", "c", ",", "language", "=", "'any'", ")", ":", "label", "=", "c", ".", "label", "(", "language", ")", "return", "{", "'id'", ":", "c", ".", "id", ",", "'type'", ":", "c", ".", "type", ",", "'uri'", ":", "c", ".", "ur...
Map related concept or collection, leaving out the relations. :param c: the concept or collection to map :param string language: Language to render the relation's label in :rtype: :class:`dict`
[ "Map", "related", "concept", "or", "collection", "leaving", "out", "the", "relations", "." ]
3affdb53cac7ad01bf3656ecd4c4d7ad9b4948b6
https://github.com/koenedaele/pyramid_skosprovider/blob/3affdb53cac7ad01bf3656ecd4c4d7ad9b4948b6/pyramid_skosprovider/renderers.py#L103-L117
train
56,764
blockadeio/analyst_toolbench
blockade/libs/indicators.py
IndicatorClient.add_indicators
def add_indicators(self, indicators=list(), private=False, tags=list()): """Add indicators to the remote instance.""" if len(indicators) == 0: raise Exception("No indicators were identified.") self.logger.debug("Checking {} indicators".format(len(indicators))) cleaned = clean...
python
def add_indicators(self, indicators=list(), private=False, tags=list()): """Add indicators to the remote instance.""" if len(indicators) == 0: raise Exception("No indicators were identified.") self.logger.debug("Checking {} indicators".format(len(indicators))) cleaned = clean...
[ "def", "add_indicators", "(", "self", ",", "indicators", "=", "list", "(", ")", ",", "private", "=", "False", ",", "tags", "=", "list", "(", ")", ")", ":", "if", "len", "(", "indicators", ")", "==", "0", ":", "raise", "Exception", "(", "\"No indicato...
Add indicators to the remote instance.
[ "Add", "indicators", "to", "the", "remote", "instance", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/libs/indicators.py#L22-L69
train
56,765
blockadeio/analyst_toolbench
blockade/libs/indicators.py
IndicatorClient.get_indicators
def get_indicators(self): """List indicators available on the remote instance.""" response = self._get('', 'get-indicators') response['message'] = "%i indicators:\n%s" % ( len(response['indicators']), "\n".join(response['indicators']) ) return response
python
def get_indicators(self): """List indicators available on the remote instance.""" response = self._get('', 'get-indicators') response['message'] = "%i indicators:\n%s" % ( len(response['indicators']), "\n".join(response['indicators']) ) return response
[ "def", "get_indicators", "(", "self", ")", ":", "response", "=", "self", ".", "_get", "(", "''", ",", "'get-indicators'", ")", "response", "[", "'message'", "]", "=", "\"%i indicators:\\n%s\"", "%", "(", "len", "(", "response", "[", "'indicators'", "]", ")...
List indicators available on the remote instance.
[ "List", "indicators", "available", "on", "the", "remote", "instance", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/libs/indicators.py#L71-L78
train
56,766
orbeckst/RecSQL
recsql/convert.py
besttype
def besttype(x, encoding="utf-8", percentify=True): """Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned. The string can contain any number of quotes, it is only im...
python
def besttype(x, encoding="utf-8", percentify=True): """Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned. The string can contain any number of quotes, it is only im...
[ "def", "besttype", "(", "x", ",", "encoding", "=", "\"utf-8\"", ",", "percentify", "=", "True", ")", ":", "def", "unicodify", "(", "x", ")", ":", "return", "to_unicode", "(", "x", ",", "encoding", ")", "def", "percent", "(", "x", ")", ":", "try", "...
Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned. The string can contain any number of quotes, it is only important that it begins and ends with either single or d...
[ "Convert", "string", "x", "to", "the", "most", "useful", "type", "i", ".", "e", ".", "int", "float", "or", "unicode", "string", "." ]
6acbf821022361719391697c9c2f0822f9f8022a
https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/convert.py#L169-L214
train
56,767
cdumay/kser
src/kser/controller.py
BaseController._onmessage
def _onmessage(cls, kmsg): """ Call on received message :param kser.schemas.Message kmsg: Kafka message :return: Kafka message :rtype: kser.schemas.Message """ logger.debug( "{}.ReceivedMessage {}[{}]".format( cls.__name__, kmsg.entrypoint, km...
python
def _onmessage(cls, kmsg): """ Call on received message :param kser.schemas.Message kmsg: Kafka message :return: Kafka message :rtype: kser.schemas.Message """ logger.debug( "{}.ReceivedMessage {}[{}]".format( cls.__name__, kmsg.entrypoint, km...
[ "def", "_onmessage", "(", "cls", ",", "kmsg", ")", ":", "logger", ".", "debug", "(", "\"{}.ReceivedMessage {}[{}]\"", ".", "format", "(", "cls", ".", "__name__", ",", "kmsg", ".", "entrypoint", ",", "kmsg", ".", "uuid", ")", ",", "extra", "=", "dict", ...
Call on received message :param kser.schemas.Message kmsg: Kafka message :return: Kafka message :rtype: kser.schemas.Message
[ "Call", "on", "received", "message" ]
fbd6fe9ab34b8b89d9937e5ff727614304af48c1
https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/controller.py#L88-L101
train
56,768
cdumay/kser
src/kser/controller.py
Controller.register
def register(cls, name, entrypoint): """ Register a new entrypoint :param str name: Key used by messages :param kser.entry.Entrypoint entrypoint: class to load :raises ValidationError: Invalid entry """ if not issubclass(entrypoint, Entrypoint): raise Validat...
python
def register(cls, name, entrypoint): """ Register a new entrypoint :param str name: Key used by messages :param kser.entry.Entrypoint entrypoint: class to load :raises ValidationError: Invalid entry """ if not issubclass(entrypoint, Entrypoint): raise Validat...
[ "def", "register", "(", "cls", ",", "name", ",", "entrypoint", ")", ":", "if", "not", "issubclass", "(", "entrypoint", ",", "Entrypoint", ")", ":", "raise", "ValidationError", "(", "\"Invalid type for entry '{}', MUST implement \"", "\"kser.entry.Entrypoint\"", ".", ...
Register a new entrypoint :param str name: Key used by messages :param kser.entry.Entrypoint entrypoint: class to load :raises ValidationError: Invalid entry
[ "Register", "a", "new", "entrypoint" ]
fbd6fe9ab34b8b89d9937e5ff727614304af48c1
https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/controller.py#L129-L143
train
56,769
cdumay/kser
src/kser/controller.py
Controller.run
def run(cls, raw_data): """description of run""" logger.debug("{}.ReceivedFromKafka: {}".format( cls.__name__, raw_data )) try: kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data)) except Exception as exc: logger.error( "{}.Impo...
python
def run(cls, raw_data): """description of run""" logger.debug("{}.ReceivedFromKafka: {}".format( cls.__name__, raw_data )) try: kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data)) except Exception as exc: logger.error( "{}.Impo...
[ "def", "run", "(", "cls", ",", "raw_data", ")", ":", "logger", ".", "debug", "(", "\"{}.ReceivedFromKafka: {}\"", ".", "format", "(", "cls", ".", "__name__", ",", "raw_data", ")", ")", "try", ":", "kmsg", "=", "cls", ".", "_onmessage", "(", "cls", ".",...
description of run
[ "description", "of", "run" ]
fbd6fe9ab34b8b89d9937e5ff727614304af48c1
https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/controller.py#L146-L186
train
56,770
DeVilhena-Paulo/KdQuery
kdquery.py
Tree.deactivate
def deactivate(self, node_id): """Deactivate the node identified by node_id. Deactivates the node corresponding to node_id, which means that it can never be the output of a nearest_point query. Note: The node is not removed from the tree, its data is steel available. ...
python
def deactivate(self, node_id): """Deactivate the node identified by node_id. Deactivates the node corresponding to node_id, which means that it can never be the output of a nearest_point query. Note: The node is not removed from the tree, its data is steel available. ...
[ "def", "deactivate", "(", "self", ",", "node_id", ")", ":", "node", "=", "self", ".", "node_list", "[", "node_id", "]", "self", ".", "node_list", "[", "node_id", "]", "=", "node", ".", "_replace", "(", "active", "=", "False", ")" ]
Deactivate the node identified by node_id. Deactivates the node corresponding to node_id, which means that it can never be the output of a nearest_point query. Note: The node is not removed from the tree, its data is steel available. Args: node_id (int): The no...
[ "Deactivate", "the", "node", "identified", "by", "node_id", "." ]
76e3791e25b2db2168c1007fe1b92c3f8ec20005
https://github.com/DeVilhena-Paulo/KdQuery/blob/76e3791e25b2db2168c1007fe1b92c3f8ec20005/kdquery.py#L83-L98
train
56,771
DeVilhena-Paulo/KdQuery
kdquery.py
Tree.insert
def insert(self, point, data=None): """Insert a new node in the tree. Args: point (:obj:`tuple` of float or int): Stores the position of the node. data (:obj, optional): The information stored by the node. Returns: int: The identifier of the ...
python
def insert(self, point, data=None): """Insert a new node in the tree. Args: point (:obj:`tuple` of float or int): Stores the position of the node. data (:obj, optional): The information stored by the node. Returns: int: The identifier of the ...
[ "def", "insert", "(", "self", ",", "point", ",", "data", "=", "None", ")", ":", "assert", "len", "(", "point", ")", "==", "self", ".", "k", "if", "self", ".", "size", "==", "0", ":", "if", "self", ".", "region", "is", "None", ":", "self", ".", ...
Insert a new node in the tree. Args: point (:obj:`tuple` of float or int): Stores the position of the node. data (:obj, optional): The information stored by the node. Returns: int: The identifier of the new node. Example: >>> tre...
[ "Insert", "a", "new", "node", "in", "the", "tree", "." ]
76e3791e25b2db2168c1007fe1b92c3f8ec20005
https://github.com/DeVilhena-Paulo/KdQuery/blob/76e3791e25b2db2168c1007fe1b92c3f8ec20005/kdquery.py#L100-L156
train
56,772
mozilla/rna
rna/admin.py
ReleaseAdmin.set_to_public
def set_to_public(self, request, queryset): """ Set one or several releases to public """ queryset.update(is_public=True, modified=now())
python
def set_to_public(self, request, queryset): """ Set one or several releases to public """ queryset.update(is_public=True, modified=now())
[ "def", "set_to_public", "(", "self", ",", "request", ",", "queryset", ")", ":", "queryset", ".", "update", "(", "is_public", "=", "True", ",", "modified", "=", "now", "(", ")", ")" ]
Set one or several releases to public
[ "Set", "one", "or", "several", "releases", "to", "public" ]
c1d3931f577dc9c54997f876d36bc0b44dc225ea
https://github.com/mozilla/rna/blob/c1d3931f577dc9c54997f876d36bc0b44dc225ea/rna/admin.py#L102-L104
train
56,773
cdumay/kser
src/kser/schemas.py
Message.loads
def loads(cls, json_data): """description of load""" try: return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data)) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[0])
python
def loads(cls, json_data): """description of load""" try: return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data)) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[0])
[ "def", "loads", "(", "cls", ",", "json_data", ")", ":", "try", ":", "return", "cls", "(", "*", "*", "cls", ".", "MARSHMALLOW_SCHEMA", ".", "loads", "(", "json_data", ")", ")", "except", "marshmallow", ".", "exceptions", ".", "ValidationError", "as", "exc...
description of load
[ "description", "of", "load" ]
fbd6fe9ab34b8b89d9937e5ff727614304af48c1
https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/schemas.py#L50-L55
train
56,774
wuher/devil
devil/datamapper.py
DataMapper.format
def format(self, response): """ Format the data. In derived classes, it is usually better idea to override ``_format_data()`` than this method. :param response: devil's ``Response`` object or the data itself. May also be ``None``. :return: django's ``Ht...
python
def format(self, response): """ Format the data. In derived classes, it is usually better idea to override ``_format_data()`` than this method. :param response: devil's ``Response`` object or the data itself. May also be ``None``. :return: django's ``Ht...
[ "def", "format", "(", "self", ",", "response", ")", ":", "res", "=", "self", ".", "_prepare_response", "(", "response", ")", "res", ".", "content", "=", "self", ".", "_format_data", "(", "res", ".", "content", ",", "self", ".", "charset", ")", "return"...
Format the data. In derived classes, it is usually better idea to override ``_format_data()`` than this method. :param response: devil's ``Response`` object or the data itself. May also be ``None``. :return: django's ``HttpResponse`` todo: this shouldn...
[ "Format", "the", "data", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L26-L42
train
56,775
wuher/devil
devil/datamapper.py
DataMapper.parse
def parse(self, data, charset=None): """ Parse the data. It is usually a better idea to override ``_parse_data()`` than this method in derived classes. :param charset: the charset of the data. Uses datamapper's default (``self.charset``) if not given. :returns: ...
python
def parse(self, data, charset=None): """ Parse the data. It is usually a better idea to override ``_parse_data()`` than this method in derived classes. :param charset: the charset of the data. Uses datamapper's default (``self.charset``) if not given. :returns: ...
[ "def", "parse", "(", "self", ",", "data", ",", "charset", "=", "None", ")", ":", "charset", "=", "charset", "or", "self", ".", "charset", "return", "self", ".", "_parse_data", "(", "data", ",", "charset", ")" ]
Parse the data. It is usually a better idea to override ``_parse_data()`` than this method in derived classes. :param charset: the charset of the data. Uses datamapper's default (``self.charset``) if not given. :returns:
[ "Parse", "the", "data", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L44-L56
train
56,776
wuher/devil
devil/datamapper.py
DataMapper._decode_data
def _decode_data(self, data, charset): """ Decode string data. :returns: unicode string """ try: return smart_unicode(data, charset) except UnicodeDecodeError: raise errors.BadRequest('wrong charset')
python
def _decode_data(self, data, charset): """ Decode string data. :returns: unicode string """ try: return smart_unicode(data, charset) except UnicodeDecodeError: raise errors.BadRequest('wrong charset')
[ "def", "_decode_data", "(", "self", ",", "data", ",", "charset", ")", ":", "try", ":", "return", "smart_unicode", "(", "data", ",", "charset", ")", "except", "UnicodeDecodeError", ":", "raise", "errors", ".", "BadRequest", "(", "'wrong charset'", ")" ]
Decode string data. :returns: unicode string
[ "Decode", "string", "data", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L58-L67
train
56,777
wuher/devil
devil/datamapper.py
DataMapper._parse_data
def _parse_data(self, data, charset): """ Parse the data :param data: the data (may be None) """ return self._decode_data(data, charset) if data else u''
python
def _parse_data(self, data, charset): """ Parse the data :param data: the data (may be None) """ return self._decode_data(data, charset) if data else u''
[ "def", "_parse_data", "(", "self", ",", "data", ",", "charset", ")", ":", "return", "self", ".", "_decode_data", "(", "data", ",", "charset", ")", "if", "data", "else", "u''" ]
Parse the data :param data: the data (may be None)
[ "Parse", "the", "data" ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L81-L87
train
56,778
wuher/devil
devil/datamapper.py
DataMapper._finalize_response
def _finalize_response(self, response): """ Convert the ``Response`` object into django's ``HttpResponse`` :return: django's ``HttpResponse`` """ res = HttpResponse(content=response.content, content_type=self._get_content_type()) # status_code is set ...
python
def _finalize_response(self, response): """ Convert the ``Response`` object into django's ``HttpResponse`` :return: django's ``HttpResponse`` """ res = HttpResponse(content=response.content, content_type=self._get_content_type()) # status_code is set ...
[ "def", "_finalize_response", "(", "self", ",", "response", ")", ":", "res", "=", "HttpResponse", "(", "content", "=", "response", ".", "content", ",", "content_type", "=", "self", ".", "_get_content_type", "(", ")", ")", "# status_code is set separately to allow z...
Convert the ``Response`` object into django's ``HttpResponse`` :return: django's ``HttpResponse``
[ "Convert", "the", "Response", "object", "into", "django", "s", "HttpResponse" ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L102-L112
train
56,779
wuher/devil
devil/datamapper.py
DataMapperManager.register_mapper
def register_mapper(self, mapper, content_type, shortname=None): """ Register new mapper. :param mapper: mapper object needs to implement ``parse()`` and ``format()`` functions. """ self._check_mapper(mapper) cont_type_names = self._get_content_type_names(content_type, ...
python
def register_mapper(self, mapper, content_type, shortname=None): """ Register new mapper. :param mapper: mapper object needs to implement ``parse()`` and ``format()`` functions. """ self._check_mapper(mapper) cont_type_names = self._get_content_type_names(content_type, ...
[ "def", "register_mapper", "(", "self", ",", "mapper", ",", "content_type", ",", "shortname", "=", "None", ")", ":", "self", ".", "_check_mapper", "(", "mapper", ")", "cont_type_names", "=", "self", ".", "_get_content_type_names", "(", "content_type", ",", "sho...
Register new mapper. :param mapper: mapper object needs to implement ``parse()`` and ``format()`` functions.
[ "Register", "new", "mapper", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L147-L156
train
56,780
wuher/devil
devil/datamapper.py
DataMapperManager.select_formatter
def select_formatter(self, request, resource): """ Select appropriate formatter based on the request. :param request: the HTTP request :param resource: the invoked resource """ # 1. get from resource if resource.mapper: return resource.mapper # 2. ge...
python
def select_formatter(self, request, resource): """ Select appropriate formatter based on the request. :param request: the HTTP request :param resource: the invoked resource """ # 1. get from resource if resource.mapper: return resource.mapper # 2. ge...
[ "def", "select_formatter", "(", "self", ",", "request", ",", "resource", ")", ":", "# 1. get from resource", "if", "resource", ".", "mapper", ":", "return", "resource", ".", "mapper", "# 2. get from url", "mapper_name", "=", "self", ".", "_get_name_from_url", "(",...
Select appropriate formatter based on the request. :param request: the HTTP request :param resource: the invoked resource
[ "Select", "appropriate", "formatter", "based", "on", "the", "request", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L158-L180
train
56,781
wuher/devil
devil/datamapper.py
DataMapperManager.select_parser
def select_parser(self, request, resource): """ Select appropriate parser based on the request. :param request: the HTTP request :param resource: the invoked resource """ # 1. get from resource if resource.mapper: return resource.mapper # 2. get from...
python
def select_parser(self, request, resource): """ Select appropriate parser based on the request. :param request: the HTTP request :param resource: the invoked resource """ # 1. get from resource if resource.mapper: return resource.mapper # 2. get from...
[ "def", "select_parser", "(", "self", ",", "request", ",", "resource", ")", ":", "# 1. get from resource", "if", "resource", ".", "mapper", ":", "return", "resource", ".", "mapper", "# 2. get from content type", "mapper_name", "=", "self", ".", "_get_name_from_conten...
Select appropriate parser based on the request. :param request: the HTTP request :param resource: the invoked resource
[ "Select", "appropriate", "parser", "based", "on", "the", "request", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L182-L204
train
56,782
wuher/devil
devil/datamapper.py
DataMapperManager.get_mapper_by_content_type
def get_mapper_by_content_type(self, content_type): """ Returs mapper based on the content type. """ content_type = util.strip_charset(content_type) return self._get_mapper(content_type)
python
def get_mapper_by_content_type(self, content_type): """ Returs mapper based on the content type. """ content_type = util.strip_charset(content_type) return self._get_mapper(content_type)
[ "def", "get_mapper_by_content_type", "(", "self", ",", "content_type", ")", ":", "content_type", "=", "util", ".", "strip_charset", "(", "content_type", ")", "return", "self", ".", "_get_mapper", "(", "content_type", ")" ]
Returs mapper based on the content type.
[ "Returs", "mapper", "based", "on", "the", "content", "type", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L206-L210
train
56,783
wuher/devil
devil/datamapper.py
DataMapperManager._get_mapper
def _get_mapper(self, mapper_name): """ Return the mapper based on the given name. :returns: the mapper based on the given ``mapper_name`` :raises: NotAcceptable if we don't support the requested format. """ if mapper_name in self._datamappers: # mapper found ...
python
def _get_mapper(self, mapper_name): """ Return the mapper based on the given name. :returns: the mapper based on the given ``mapper_name`` :raises: NotAcceptable if we don't support the requested format. """ if mapper_name in self._datamappers: # mapper found ...
[ "def", "_get_mapper", "(", "self", ",", "mapper_name", ")", ":", "if", "mapper_name", "in", "self", ".", "_datamappers", ":", "# mapper found", "return", "self", ".", "_datamappers", "[", "mapper_name", "]", "else", ":", "# unsupported format", "return", "self",...
Return the mapper based on the given name. :returns: the mapper based on the given ``mapper_name`` :raises: NotAcceptable if we don't support the requested format.
[ "Return", "the", "mapper", "based", "on", "the", "given", "name", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L232-L244
train
56,784
wuher/devil
devil/datamapper.py
DataMapperManager._get_name_from_content_type
def _get_name_from_content_type(self, request): """ Get name from Content-Type header """ content_type = request.META.get('CONTENT_TYPE', None) if content_type: # remove the possible charset-encoding info return util.strip_charset(content_type) return None
python
def _get_name_from_content_type(self, request): """ Get name from Content-Type header """ content_type = request.META.get('CONTENT_TYPE', None) if content_type: # remove the possible charset-encoding info return util.strip_charset(content_type) return None
[ "def", "_get_name_from_content_type", "(", "self", ",", "request", ")", ":", "content_type", "=", "request", ".", "META", ".", "get", "(", "'CONTENT_TYPE'", ",", "None", ")", "if", "content_type", ":", "# remove the possible charset-encoding info", "return", "util",...
Get name from Content-Type header
[ "Get", "name", "from", "Content", "-", "Type", "header" ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L246-L253
train
56,785
wuher/devil
devil/datamapper.py
DataMapperManager._get_name_from_accept
def _get_name_from_accept(self, request): """ Process the Accept HTTP header. Find the most suitable mapper that the client wants and we support. :returns: the preferred mapper based on the accept header or ``None``. """ accepts = util.parse_accept_header(request.META.get("HTT...
python
def _get_name_from_accept(self, request): """ Process the Accept HTTP header. Find the most suitable mapper that the client wants and we support. :returns: the preferred mapper based on the accept header or ``None``. """ accepts = util.parse_accept_header(request.META.get("HTT...
[ "def", "_get_name_from_accept", "(", "self", ",", "request", ")", ":", "accepts", "=", "util", ".", "parse_accept_header", "(", "request", ".", "META", ".", "get", "(", "\"HTTP_ACCEPT\"", ",", "\"\"", ")", ")", "if", "not", "accepts", ":", "return", "None"...
Process the Accept HTTP header. Find the most suitable mapper that the client wants and we support. :returns: the preferred mapper based on the accept header or ``None``.
[ "Process", "the", "Accept", "HTTP", "header", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L255-L270
train
56,786
wuher/devil
devil/datamapper.py
DataMapperManager._get_name_from_url
def _get_name_from_url(self, request): """ Determine short name for the mapper based on the URL. Short name can be either in query string (e.g. ?format=json) or as an extension to the URL (e.g. myresource.json). :returns: short name of the mapper or ``None`` if not found. """ ...
python
def _get_name_from_url(self, request): """ Determine short name for the mapper based on the URL. Short name can be either in query string (e.g. ?format=json) or as an extension to the URL (e.g. myresource.json). :returns: short name of the mapper or ``None`` if not found. """ ...
[ "def", "_get_name_from_url", "(", "self", ",", "request", ")", ":", "format", "=", "request", ".", "GET", ".", "get", "(", "'format'", ",", "None", ")", "if", "not", "format", ":", "match", "=", "self", ".", "_format_query_pattern", ".", "match", "(", ...
Determine short name for the mapper based on the URL. Short name can be either in query string (e.g. ?format=json) or as an extension to the URL (e.g. myresource.json). :returns: short name of the mapper or ``None`` if not found.
[ "Determine", "short", "name", "for", "the", "mapper", "based", "on", "the", "URL", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L272-L286
train
56,787
wuher/devil
devil/datamapper.py
DataMapperManager._check_mapper
def _check_mapper(self, mapper): """ Check that the mapper has valid signature. """ if not hasattr(mapper, 'parse') or not callable(mapper.parse): raise ValueError('mapper must implement parse()') if not hasattr(mapper, 'format') or not callable(mapper.format): raise Valu...
python
def _check_mapper(self, mapper): """ Check that the mapper has valid signature. """ if not hasattr(mapper, 'parse') or not callable(mapper.parse): raise ValueError('mapper must implement parse()') if not hasattr(mapper, 'format') or not callable(mapper.format): raise Valu...
[ "def", "_check_mapper", "(", "self", ",", "mapper", ")", ":", "if", "not", "hasattr", "(", "mapper", ",", "'parse'", ")", "or", "not", "callable", "(", "mapper", ".", "parse", ")", ":", "raise", "ValueError", "(", "'mapper must implement parse()'", ")", "i...
Check that the mapper has valid signature.
[ "Check", "that", "the", "mapper", "has", "valid", "signature", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L305-L310
train
56,788
TissueMAPS/TmDeploy
elasticluster/elasticluster/providers/ansible_provider.py
AnsibleSetupProvider.cleanup
def cleanup(self, cluster): """Deletes the inventory file used last recently used. :param cluster: cluster to clear up inventory file for :type cluster: :py:class:`elasticluster.cluster.Cluster` """ if self._storage_path and os.path.exists(self._storage_path): fname ...
python
def cleanup(self, cluster): """Deletes the inventory file used last recently used. :param cluster: cluster to clear up inventory file for :type cluster: :py:class:`elasticluster.cluster.Cluster` """ if self._storage_path and os.path.exists(self._storage_path): fname ...
[ "def", "cleanup", "(", "self", ",", "cluster", ")", ":", "if", "self", ".", "_storage_path", "and", "os", ".", "path", ".", "exists", "(", "self", ".", "_storage_path", ")", ":", "fname", "=", "'%s.%s'", "%", "(", "AnsibleSetupProvider", ".", "inventory_...
Deletes the inventory file used last recently used. :param cluster: cluster to clear up inventory file for :type cluster: :py:class:`elasticluster.cluster.Cluster`
[ "Deletes", "the", "inventory", "file", "used", "last", "recently", "used", "." ]
f891b4ffb21431988bc4a063ae871da3bf284a45
https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/ansible_provider.py#L348-L368
train
56,789
tradenity/python-sdk
tradenity/resources/tax_rate.py
TaxRate.based_on
def based_on(self, based_on): """Sets the based_on of this TaxRate. :param based_on: The based_on of this TaxRate. :type: str """ allowed_values = ["shippingAddress", "billingAddress"] if based_on is not None and based_on not in allowed_values: raise ValueEr...
python
def based_on(self, based_on): """Sets the based_on of this TaxRate. :param based_on: The based_on of this TaxRate. :type: str """ allowed_values = ["shippingAddress", "billingAddress"] if based_on is not None and based_on not in allowed_values: raise ValueEr...
[ "def", "based_on", "(", "self", ",", "based_on", ")", ":", "allowed_values", "=", "[", "\"shippingAddress\"", ",", "\"billingAddress\"", "]", "if", "based_on", "is", "not", "None", "and", "based_on", "not", "in", "allowed_values", ":", "raise", "ValueError", "...
Sets the based_on of this TaxRate. :param based_on: The based_on of this TaxRate. :type: str
[ "Sets", "the", "based_on", "of", "this", "TaxRate", "." ]
d13fbe23f4d6ff22554c6d8d2deaf209371adaf1
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/tax_rate.py#L339-L353
train
56,790
claymcleod/celcius
lib/celcius/tasks.py
build_append_file_task
def build_append_file_task(urllocation, filelocation): """Build a task to watch a specific remote url and append that data to the file. This method should be used when you would like to keep all of the information stored on the local machine, but also append the new information found at the url. For instance, if t...
python
def build_append_file_task(urllocation, filelocation): """Build a task to watch a specific remote url and append that data to the file. This method should be used when you would like to keep all of the information stored on the local machine, but also append the new information found at the url. For instance, if t...
[ "def", "build_append_file_task", "(", "urllocation", ",", "filelocation", ")", ":", "config", "=", "file_utils", ".", "get_celcius_config", "(", ")", "basename", "=", "filelocation", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "tmp_filelocation", "=", ...
Build a task to watch a specific remote url and append that data to the file. This method should be used when you would like to keep all of the information stored on the local machine, but also append the new information found at the url. For instance, if the local file is: ``` foo ``` And the remote file is: ``` b...
[ "Build", "a", "task", "to", "watch", "a", "specific", "remote", "url", "and", "append", "that", "data", "to", "the", "file", ".", "This", "method", "should", "be", "used", "when", "you", "would", "like", "to", "keep", "all", "of", "the", "information", ...
e46a3c1ba112af9de23360d1455ab1e037a38ea1
https://github.com/claymcleod/celcius/blob/e46a3c1ba112af9de23360d1455ab1e037a38ea1/lib/celcius/tasks.py#L11-L56
train
56,791
volfpeter/graphscraper
src/graphscraper/igraphwrapper.py
IGraphWrapper._create_memory_database_interface
def _create_memory_database_interface(self) -> GraphDatabaseInterface: """ Creates and returns the in-memory database interface the graph will use. """ Base = declarative_base() engine = sqlalchemy.create_engine("sqlite://", poolclass=StaticPool) Session = sessionmaker(bi...
python
def _create_memory_database_interface(self) -> GraphDatabaseInterface: """ Creates and returns the in-memory database interface the graph will use. """ Base = declarative_base() engine = sqlalchemy.create_engine("sqlite://", poolclass=StaticPool) Session = sessionmaker(bi...
[ "def", "_create_memory_database_interface", "(", "self", ")", "->", "GraphDatabaseInterface", ":", "Base", "=", "declarative_base", "(", ")", "engine", "=", "sqlalchemy", ".", "create_engine", "(", "\"sqlite://\"", ",", "poolclass", "=", "StaticPool", ")", "Session"...
Creates and returns the in-memory database interface the graph will use.
[ "Creates", "and", "returns", "the", "in", "-", "memory", "database", "interface", "the", "graph", "will", "use", "." ]
11d407509956a282ee25190ed6491a162fc0fe7f
https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/igraphwrapper.py#L107-L122
train
56,792
volfpeter/graphscraper
src/graphscraper/igraphwrapper.py
IGraphNodeList._create_node
def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> IGraphNode: """ Returns a new `IGraphNode` instance with the given index and name. Arguments: index (int): The index of the node to create. name (str): The name of the node to create. ...
python
def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> IGraphNode: """ Returns a new `IGraphNode` instance with the given index and name. Arguments: index (int): The index of the node to create. name (str): The name of the node to create. ...
[ "def", "_create_node", "(", "self", ",", "index", ":", "int", ",", "name", ":", "str", ",", "external_id", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "IGraphNode", ":", "return", "IGraphNode", "(", "graph", "=", "self", ".", "_graph", ...
Returns a new `IGraphNode` instance with the given index and name. Arguments: index (int): The index of the node to create. name (str): The name of the node to create. external_id (Optional[str]): The external ID of the node.
[ "Returns", "a", "new", "IGraphNode", "instance", "with", "the", "given", "index", "and", "name", "." ]
11d407509956a282ee25190ed6491a162fc0fe7f
https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/igraphwrapper.py#L218-L227
train
56,793
orbeckst/RecSQL
recsql/rest_table.py
Table2array.parse
def parse(self): """Parse the table data string into records.""" self.parse_fields() records = [] for line in self.t['data'].split('\n'): if EMPTY_ROW.match(line): continue row = [self.autoconvert(line[start_field:end_field+1]) ...
python
def parse(self): """Parse the table data string into records.""" self.parse_fields() records = [] for line in self.t['data'].split('\n'): if EMPTY_ROW.match(line): continue row = [self.autoconvert(line[start_field:end_field+1]) ...
[ "def", "parse", "(", "self", ")", ":", "self", ".", "parse_fields", "(", ")", "records", "=", "[", "]", "for", "line", "in", "self", ".", "t", "[", "'data'", "]", ".", "split", "(", "'\\n'", ")", ":", "if", "EMPTY_ROW", ".", "match", "(", "line",...
Parse the table data string into records.
[ "Parse", "the", "table", "data", "string", "into", "records", "." ]
6acbf821022361719391697c9c2f0822f9f8022a
https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/rest_table.py#L191-L202
train
56,794
orbeckst/RecSQL
recsql/rest_table.py
Table2array.parse_fields
def parse_fields(self): """Determine the start and end columns and names of the fields.""" rule = self.t['toprule'].rstrip() # keep leading space for correct columns!! if not (rule == self.t['midrule'].rstrip() and rule == self.t['botrule'].rstrip()): raise ParseError("Table rules ...
python
def parse_fields(self): """Determine the start and end columns and names of the fields.""" rule = self.t['toprule'].rstrip() # keep leading space for correct columns!! if not (rule == self.t['midrule'].rstrip() and rule == self.t['botrule'].rstrip()): raise ParseError("Table rules ...
[ "def", "parse_fields", "(", "self", ")", ":", "rule", "=", "self", ".", "t", "[", "'toprule'", "]", ".", "rstrip", "(", ")", "# keep leading space for correct columns!!", "if", "not", "(", "rule", "==", "self", ".", "t", "[", "'midrule'", "]", ".", "rstr...
Determine the start and end columns and names of the fields.
[ "Determine", "the", "start", "and", "end", "columns", "and", "names", "of", "the", "fields", "." ]
6acbf821022361719391697c9c2f0822f9f8022a
https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/rest_table.py#L234-L262
train
56,795
inveniosoftware-attic/invenio-utils
invenio_utils/autodiscovery/checkers.py
check_arguments_compatibility
def check_arguments_compatibility(the_callable, argd): """ Check if calling the_callable with the given arguments would be correct or not. >>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd): ... pass >>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'}) ...
python
def check_arguments_compatibility(the_callable, argd): """ Check if calling the_callable with the given arguments would be correct or not. >>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd): ... pass >>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'}) ...
[ "def", "check_arguments_compatibility", "(", "the_callable", ",", "argd", ")", ":", "if", "not", "argd", ":", "argd", "=", "{", "}", "args", ",", "dummy", ",", "varkw", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "the_callable", ")", "tmp_args...
Check if calling the_callable with the given arguments would be correct or not. >>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd): ... pass >>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'}) ... except ValueError as err: print 'failed' ... else: print...
[ "Check", "if", "calling", "the_callable", "with", "the", "given", "arguments", "would", "be", "correct", "or", "not", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/checkers.py#L176-L242
train
56,796
henocdz/workon
workon/script.py
WorkOn._print
def _print(self, text, color=None, **kwargs): """print text with given color to terminal """ COLORS = { 'red': '\033[91m{}\033[00m', 'green': '\033[92m{}\033[00m', 'yellow': '\033[93m{}\033[00m', 'cyan': '\033[96m{}\033[00m' } _ = C...
python
def _print(self, text, color=None, **kwargs): """print text with given color to terminal """ COLORS = { 'red': '\033[91m{}\033[00m', 'green': '\033[92m{}\033[00m', 'yellow': '\033[93m{}\033[00m', 'cyan': '\033[96m{}\033[00m' } _ = C...
[ "def", "_print", "(", "self", ",", "text", ",", "color", "=", "None", ",", "*", "*", "kwargs", ")", ":", "COLORS", "=", "{", "'red'", ":", "'\\033[91m{}\\033[00m'", ",", "'green'", ":", "'\\033[92m{}\\033[00m'", ",", "'yellow'", ":", "'\\033[93m{}\\033[00m'"...
print text with given color to terminal
[ "print", "text", "with", "given", "color", "to", "terminal" ]
46f1f6dc4ea95d8efd10adf93a06737237a6874d
https://github.com/henocdz/workon/blob/46f1f6dc4ea95d8efd10adf93a06737237a6874d/workon/script.py#L22-L32
train
56,797
henocdz/workon
workon/script.py
WorkOn._is_unique
def _is_unique(self, name, path): """verify if there is a project with given name or path on the database """ project = None try: project = Project.select().where( (Project.name == name) | (Project.path == path) )[0] ...
python
def _is_unique(self, name, path): """verify if there is a project with given name or path on the database """ project = None try: project = Project.select().where( (Project.name == name) | (Project.path == path) )[0] ...
[ "def", "_is_unique", "(", "self", ",", "name", ",", "path", ")", ":", "project", "=", "None", "try", ":", "project", "=", "Project", ".", "select", "(", ")", ".", "where", "(", "(", "Project", ".", "name", "==", "name", ")", "|", "(", "Project", ...
verify if there is a project with given name or path on the database
[ "verify", "if", "there", "is", "a", "project", "with", "given", "name", "or", "path", "on", "the", "database" ]
46f1f6dc4ea95d8efd10adf93a06737237a6874d
https://github.com/henocdz/workon/blob/46f1f6dc4ea95d8efd10adf93a06737237a6874d/workon/script.py#L34-L47
train
56,798
henocdz/workon
workon/script.py
WorkOn.add
def add(self, name, path=None, **kwargs): """add new project with given name and path to database if the path is not given, current working directory will be taken ...as default """ path = path or kwargs.pop('default_path', None) if not self._path_is_valid(path): ...
python
def add(self, name, path=None, **kwargs): """add new project with given name and path to database if the path is not given, current working directory will be taken ...as default """ path = path or kwargs.pop('default_path', None) if not self._path_is_valid(path): ...
[ "def", "add", "(", "self", ",", "name", ",", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "path", "or", "kwargs", ".", "pop", "(", "'default_path'", ",", "None", ")", "if", "not", "self", ".", "_path_is_valid", "(", "path", ...
add new project with given name and path to database if the path is not given, current working directory will be taken ...as default
[ "add", "new", "project", "with", "given", "name", "and", "path", "to", "database", "if", "the", "path", "is", "not", "given", "current", "working", "directory", "will", "be", "taken", "...", "as", "default" ]
46f1f6dc4ea95d8efd10adf93a06737237a6874d
https://github.com/henocdz/workon/blob/46f1f6dc4ea95d8efd10adf93a06737237a6874d/workon/script.py#L76-L95
train
56,799