labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does this function do? | def fix_eols(s):
s = re.sub('(?<!\\r)\\n', CRLF, s)
s = re.sub('\\r(?!\\n)', CRLF, s)
return s
| null | null | null | Replace all line-ending characters with | pcsd | def fix eols s s = re sub ' ?<!\\r \ ' CRLF s s = re sub '\\r ?!\ ' CRLF s return s | 5963 | def fix_eols(s):
s = re.sub('(?<!\\r)\\n', CRLF, s)
s = re.sub('\\r(?!\\n)', CRLF, s)
return s
| Replace all line-ending characters with | replace all line - ending characters with | Question:
What does this function do?
Code:
def fix_eols(s):
s = re.sub('(?<!\\r)\\n', CRLF, s)
s = re.sub('\\r(?!\\n)', CRLF, s)
return s
|
null | null | null | What does this function do? | @app.route('/library')
def library():
papers = papers_from_library()
ret = encode_json(papers, 500)
if g.user:
msg = ('%d papers in your library:' % (len(ret),))
else:
msg = 'You must be logged in. Once you are, you can save papers to your library (with the save icon on the right of each paper) and they will sh... | null | null | null | render user\'s library | pcsd | @app route '/library' def library papers = papers from library ret = encode json papers 500 if g user msg = '%d papers in your library ' % len ret else msg = 'You must be logged in Once you are you can save papers to your library with the save icon on the right of each paper and they will show up here ' ctx = default c... | 5968 | @app.route('/library')
def library():
papers = papers_from_library()
ret = encode_json(papers, 500)
if g.user:
msg = ('%d papers in your library:' % (len(ret),))
else:
msg = 'You must be logged in. Once you are, you can save papers to your library (with the save icon on the right of each paper) and they will sh... | render user\'s library | render users library | Question:
What does this function do?
Code:
@app.route('/library')
def library():
papers = papers_from_library()
ret = encode_json(papers, 500)
if g.user:
msg = ('%d papers in your library:' % (len(ret),))
else:
msg = 'You must be logged in. Once you are, you can save papers to your library (with the save ic... |
null | null | null | What does this function do? | def _get_options(ret):
attrs = {'host': 'host', 'port': 'port', 'skip': 'skip_on_error', 'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__)
return _options
| null | null | null | Returns options used for the carbon returner. | pcsd | def get options ret attrs = {'host' 'host' 'port' 'port' 'skip' 'skip on error' 'mode' 'mode'} options = salt returners get returner options virtualname ret attrs salt = salt opts = opts return options | 5970 | def _get_options(ret):
attrs = {'host': 'host', 'port': 'port', 'skip': 'skip_on_error', 'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__)
return _options
| Returns options used for the carbon returner. | returns options used for the carbon returner . | Question:
What does this function do?
Code:
def _get_options(ret):
attrs = {'host': 'host', 'port': 'port', 'skip': 'skip_on_error', 'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__)
return _options
|
null | null | null | What does this function do? | def get_conn(host=None, username=None, password=None):
if (not HAS_IMPACKET):
return False
conn = impacket.smbconnection.SMBConnection(remoteName='*SMBSERVER', remoteHost=host)
conn.login(user=username, password=password)
return conn
| null | null | null | Get an SMB connection | pcsd | def get conn host=None username=None password=None if not HAS IMPACKET return False conn = impacket smbconnection SMB Connection remote Name='*SMBSERVER' remote Host=host conn login user=username password=password return conn | 5974 | def get_conn(host=None, username=None, password=None):
if (not HAS_IMPACKET):
return False
conn = impacket.smbconnection.SMBConnection(remoteName='*SMBSERVER', remoteHost=host)
conn.login(user=username, password=password)
return conn
| Get an SMB connection | get an smb connection | Question:
What does this function do?
Code:
def get_conn(host=None, username=None, password=None):
if (not HAS_IMPACKET):
return False
conn = impacket.smbconnection.SMBConnection(remoteName='*SMBSERVER', remoteHost=host)
conn.login(user=username, password=password)
return conn
|
null | null | null | What does this function do? | @click.command(name='import')
@click.argument('src', type=click.File('rb'))
@configuration
def import_(src):
from django.core import serializers
for obj in serializers.deserialize('json', src, stream=True, use_natural_keys=True):
obj.save()
| null | null | null | Imports data from a Sentry export. | pcsd | @click command name='import' @click argument 'src' type=click File 'rb' @configuration def import src from django core import serializers for obj in serializers deserialize 'json' src stream=True use natural keys=True obj save | 5975 | @click.command(name='import')
@click.argument('src', type=click.File('rb'))
@configuration
def import_(src):
from django.core import serializers
for obj in serializers.deserialize('json', src, stream=True, use_natural_keys=True):
obj.save()
| Imports data from a Sentry export. | imports data from a sentry export . | Question:
What does this function do?
Code:
@click.command(name='import')
@click.argument('src', type=click.File('rb'))
@configuration
def import_(src):
from django.core import serializers
for obj in serializers.deserialize('json', src, stream=True, use_natural_keys=True):
obj.save()
|
null | null | null | What does this function do? | def create_document_editor_user():
User = get_user_model()
(user, user_created) = User.objects.get_or_create(username='conantheeditor', defaults=dict(email='user_%s@example.com', is_active=True, is_staff=False, is_superuser=False))
if user_created:
user.set_password('testpass')
user.groups = [create_document_edi... | null | null | null | Get or create a user empowered with document editing. | pcsd | def create document editor user User = get user model user user created = User objects get or create username='conantheeditor' defaults=dict email='user %s@example com' is active=True is staff=False is superuser=False if user created user set password 'testpass' user groups = [create document editor group ] user save r... | 5977 | def create_document_editor_user():
User = get_user_model()
(user, user_created) = User.objects.get_or_create(username='conantheeditor', defaults=dict(email='user_%s@example.com', is_active=True, is_staff=False, is_superuser=False))
if user_created:
user.set_password('testpass')
user.groups = [create_document_edi... | Get or create a user empowered with document editing. | get or create a user empowered with document editing . | Question:
What does this function do?
Code:
def create_document_editor_user():
User = get_user_model()
(user, user_created) = User.objects.get_or_create(username='conantheeditor', defaults=dict(email='user_%s@example.com', is_active=True, is_staff=False, is_superuser=False))
if user_created:
user.set_password('... |
null | null | null | What does this function do? | def recompose_xfm(in_bval, in_xfms):
import numpy as np
import os.path as op
bvals = np.loadtxt(in_bval)
out_matrix = np.array(([np.eye(4)] * len(bvals)))
xfms = iter([np.loadtxt(xfm) for xfm in in_xfms])
out_files = []
for (i, b) in enumerate(bvals):
if (b == 0.0):
mat = np.eye(4)
else:
mat = next(xfm... | null | null | null | Insert identity transformation matrices in b0 volumes to build up a list | pcsd | def recompose xfm in bval in xfms import numpy as np import os path as op bvals = np loadtxt in bval out matrix = np array [np eye 4 ] * len bvals xfms = iter [np loadtxt xfm for xfm in in xfms] out files = [] for i b in enumerate bvals if b == 0 0 mat = np eye 4 else mat = next xfms out name = op abspath u'eccor %04d ... | 5979 | def recompose_xfm(in_bval, in_xfms):
import numpy as np
import os.path as op
bvals = np.loadtxt(in_bval)
out_matrix = np.array(([np.eye(4)] * len(bvals)))
xfms = iter([np.loadtxt(xfm) for xfm in in_xfms])
out_files = []
for (i, b) in enumerate(bvals):
if (b == 0.0):
mat = np.eye(4)
else:
mat = next(xfm... | Insert identity transformation matrices in b0 volumes to build up a list | insert identity transformation matrices in b0 volumes to build up a list | Question:
What does this function do?
Code:
def recompose_xfm(in_bval, in_xfms):
import numpy as np
import os.path as op
bvals = np.loadtxt(in_bval)
out_matrix = np.array(([np.eye(4)] * len(bvals)))
xfms = iter([np.loadtxt(xfm) for xfm in in_xfms])
out_files = []
for (i, b) in enumerate(bvals):
if (b == 0.0... |
null | null | null | What does this function do? | def teardown_module():
os.remove(FAKEFILE)
| null | null | null | Tear down the module. | pcsd | def teardown module os remove FAKEFILE | 5980 | def teardown_module():
os.remove(FAKEFILE)
| Tear down the module. | tear down the module . | Question:
What does this function do?
Code:
def teardown_module():
os.remove(FAKEFILE)
|
null | null | null | What does this function do? | def to_int(val):
try:
return int(str(val), 0)
except:
return None
| null | null | null | Convert a string to int number | pcsd | def to int val try return int str val 0 except return None | 5982 | def to_int(val):
try:
return int(str(val), 0)
except:
return None
| Convert a string to int number | convert a string to int number | Question:
What does this function do?
Code:
def to_int(val):
try:
return int(str(val), 0)
except:
return None
|
null | null | null | What does this function do? | def reshape(x, shape):
return tf.reshape(x, shape)
| null | null | null | Reshapes a tensor to the specified shape.
# Returns
A tensor. | pcsd | def reshape x shape return tf reshape x shape | 5989 | def reshape(x, shape):
return tf.reshape(x, shape)
| Reshapes a tensor to the specified shape.
# Returns
A tensor. | reshapes a tensor to the specified shape . | Question:
What does this function do?
Code:
def reshape(x, shape):
return tf.reshape(x, shape)
|
null | null | null | What does this function do? | def _check_to_bytes(self, in_string, encoding, expected):
self.assertEqual(to_bytes(in_string, encoding), expected)
| null | null | null | test happy path of encoding to bytes | pcsd | def check to bytes self in string encoding expected self assert Equal to bytes in string encoding expected | 5994 | def _check_to_bytes(self, in_string, encoding, expected):
self.assertEqual(to_bytes(in_string, encoding), expected)
| test happy path of encoding to bytes | test happy path of encoding to bytes | Question:
What does this function do?
Code:
def _check_to_bytes(self, in_string, encoding, expected):
self.assertEqual(to_bytes(in_string, encoding), expected)
|
null | null | null | What does this function do? | def get_ref_to_doc(refname, title=''):
ref = addnodes.pending_xref(reftype='ref', reftarget=refname, refexplicit=(title != ''), refdomain='std')
ref += nodes.literal(title, title, classes=['xref'])
return ref
| null | null | null | Returns a node that links to a document with the given ref name. | pcsd | def get ref to doc refname title='' ref = addnodes pending xref reftype='ref' reftarget=refname refexplicit= title != '' refdomain='std' ref += nodes literal title title classes=['xref'] return ref | 6006 | def get_ref_to_doc(refname, title=''):
ref = addnodes.pending_xref(reftype='ref', reftarget=refname, refexplicit=(title != ''), refdomain='std')
ref += nodes.literal(title, title, classes=['xref'])
return ref
| Returns a node that links to a document with the given ref name. | returns a node that links to a document with the given ref name . | Question:
What does this function do?
Code:
def get_ref_to_doc(refname, title=''):
ref = addnodes.pending_xref(reftype='ref', reftarget=refname, refexplicit=(title != ''), refdomain='std')
ref += nodes.literal(title, title, classes=['xref'])
return ref
|
null | null | null | What does this function do? | @pytest.mark.parametrize('parallel', [True, False])
def test_no_header_supplied_names(parallel, read_basic, read_no_header):
table = read_no_header('A B C\n1 2 3\n4 5 6', names=('X', 'Y', 'Z'), parallel=parallel)
expected = Table([['A', '1', '4'], ['B', '2', '5'], ['C', '3', '6']], names=('X', 'Y', 'Z'))
assert_tabl... | null | null | null | If header_start=None and names is passed as a parameter, header
data should not be read and names should be used instead. | pcsd | @pytest mark parametrize 'parallel' [True False] def test no header supplied names parallel read basic read no header table = read no header 'A B C 1 2 3 4 5 6' names= 'X' 'Y' 'Z' parallel=parallel expected = Table [['A' '1' '4'] ['B' '2' '5'] ['C' '3' '6']] names= 'X' 'Y' 'Z' assert table equal table expected | 6007 | @pytest.mark.parametrize('parallel', [True, False])
def test_no_header_supplied_names(parallel, read_basic, read_no_header):
table = read_no_header('A B C\n1 2 3\n4 5 6', names=('X', 'Y', 'Z'), parallel=parallel)
expected = Table([['A', '1', '4'], ['B', '2', '5'], ['C', '3', '6']], names=('X', 'Y', 'Z'))
assert_tabl... | If header_start=None and names is passed as a parameter, header
data should not be read and names should be used instead. | if header _ start = none and names is passed as a parameter , header data should not be read and names should be used instead . | Question:
What does this function do?
Code:
@pytest.mark.parametrize('parallel', [True, False])
def test_no_header_supplied_names(parallel, read_basic, read_no_header):
table = read_no_header('A B C\n1 2 3\n4 5 6', names=('X', 'Y', 'Z'), parallel=parallel)
expected = Table([['A', '1', '4'], ['B', '2', '5'], ['C', ... |
null | null | null | What does this function do? | def _CanBreakBefore(prev_token, cur_token):
pval = prev_token.value
cval = cur_token.value
if py3compat.PY3:
if ((pval == 'yield') and (cval == 'from')):
return False
if ((pval in {'async', 'await'}) and (cval in {'def', 'with', 'for'})):
return False
if (cur_token.split_penalty >= split_penalty.UNBREAKAB... | null | null | null | Return True if a line break may occur before the current token. | pcsd | def Can Break Before prev token cur token pval = prev token value cval = cur token value if py3compat PY3 if pval == 'yield' and cval == 'from' return False if pval in {'async' 'await'} and cval in {'def' 'with' 'for'} return False if cur token split penalty >= split penalty UNBREAKABLE return False if pval == '@' retu... | 6015 | def _CanBreakBefore(prev_token, cur_token):
pval = prev_token.value
cval = cur_token.value
if py3compat.PY3:
if ((pval == 'yield') and (cval == 'from')):
return False
if ((pval in {'async', 'await'}) and (cval in {'def', 'with', 'for'})):
return False
if (cur_token.split_penalty >= split_penalty.UNBREAKAB... | Return True if a line break may occur before the current token. | return true if a line break may occur before the current token . | Question:
What does this function do?
Code:
def _CanBreakBefore(prev_token, cur_token):
pval = prev_token.value
cval = cur_token.value
if py3compat.PY3:
if ((pval == 'yield') and (cval == 'from')):
return False
if ((pval in {'async', 'await'}) and (cval in {'def', 'with', 'for'})):
return False
if (cur... |
null | null | null | What does this function do? | def donor():
tablename = 'org_donor'
table = s3db[tablename]
tablename = 'org_donor'
s3.crud_strings[tablename] = Storage(label_create=ADD_DONOR, title_display=T('Donor Details'), title_list=T('Donors Report'), title_update=T('Edit Donor'), label_list_button=T('List Donors'), label_delete_button=T('Delete Donor'), ... | null | null | null | RESTful CRUD controller | pcsd | def donor tablename = 'org donor' table = s3db[tablename] tablename = 'org donor' s3 crud strings[tablename] = Storage label create=ADD DONOR title display=T 'Donor Details' title list=T 'Donors Report' title update=T 'Edit Donor' label list button=T 'List Donors' label delete button=T 'Delete Donor' msg record created... | 6021 | def donor():
tablename = 'org_donor'
table = s3db[tablename]
tablename = 'org_donor'
s3.crud_strings[tablename] = Storage(label_create=ADD_DONOR, title_display=T('Donor Details'), title_list=T('Donors Report'), title_update=T('Edit Donor'), label_list_button=T('List Donors'), label_delete_button=T('Delete Donor'), ... | RESTful CRUD controller | restful crud controller | Question:
What does this function do?
Code:
def donor():
tablename = 'org_donor'
table = s3db[tablename]
tablename = 'org_donor'
s3.crud_strings[tablename] = Storage(label_create=ADD_DONOR, title_display=T('Donor Details'), title_list=T('Donors Report'), title_update=T('Edit Donor'), label_list_button=T('List Do... |
null | null | null | What does this function do? | def p_specifier_qualifier_list_4(t):
pass
| null | null | null | specifier_qualifier_list : type_qualifier | pcsd | def p specifier qualifier list 4 t pass | 6028 | def p_specifier_qualifier_list_4(t):
pass
| specifier_qualifier_list : type_qualifier | specifier _ qualifier _ list : type _ qualifier | Question:
What does this function do?
Code:
def p_specifier_qualifier_list_4(t):
pass
|
null | null | null | What does this function do? | def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None):
apiid = __opts__.get('stormpath', {}).get('apiid', None)
apikey = __opts__.get('stormpath', {}).get('apikey', None)
path = 'https://api.stormpath.com/v1/'
if action:
path += action
if command:
path += '/{0}'.format(com... | null | null | null | Make a web call to Stormpath. | pcsd | def query action=None command=None args=None method='GET' header dict=None data=None apiid = opts get 'stormpath' {} get 'apiid' None apikey = opts get 'stormpath' {} get 'apikey' None path = 'https //api stormpath com/v1/' if action path += action if command path += '/{0}' format command log debug 'Stormpath URL {0}' ... | 6042 | def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None):
apiid = __opts__.get('stormpath', {}).get('apiid', None)
apikey = __opts__.get('stormpath', {}).get('apikey', None)
path = 'https://api.stormpath.com/v1/'
if action:
path += action
if command:
path += '/{0}'.format(com... | Make a web call to Stormpath. | make a web call to stormpath . | Question:
What does this function do?
Code:
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None):
apiid = __opts__.get('stormpath', {}).get('apiid', None)
apikey = __opts__.get('stormpath', {}).get('apikey', None)
path = 'https://api.stormpath.com/v1/'
if action:
path += ... |
null | null | null | What does this function do? | @contextfunction
def show_hint(context, hint=None, object=None):
request = context['request']
response_format = 'html'
user = None
if request.user.username:
try:
user = request.user.profile
except Exception:
pass
return Markup(render_to_string(('core/hints/' + hint), {'user': user, 'object': object}, res... | null | null | null | Generic hint framework | pcsd | @contextfunction def show hint context hint=None object=None request = context['request'] response format = 'html' user = None if request user username try user = request user profile except Exception pass return Markup render to string 'core/hints/' + hint {'user' user 'object' object} response format=response format | 6043 | @contextfunction
def show_hint(context, hint=None, object=None):
request = context['request']
response_format = 'html'
user = None
if request.user.username:
try:
user = request.user.profile
except Exception:
pass
return Markup(render_to_string(('core/hints/' + hint), {'user': user, 'object': object}, res... | Generic hint framework | generic hint framework | Question:
What does this function do?
Code:
@contextfunction
def show_hint(context, hint=None, object=None):
request = context['request']
response_format = 'html'
user = None
if request.user.username:
try:
user = request.user.profile
except Exception:
pass
return Markup(render_to_string(('core/hints/'... |
null | null | null | What does this function do? | def getEvaluatedBooleanDefault(defaultBoolean, key, xmlElement=None):
if (xmlElement == None):
return None
if (key in xmlElement.attributeDictionary):
return euclidean.getBooleanFromValue(getEvaluatedValueObliviously(key, xmlElement))
return defaultBoolean
| null | null | null | Get the evaluated boolean as a float. | pcsd | def get Evaluated Boolean Default default Boolean key xml Element=None if xml Element == None return None if key in xml Element attribute Dictionary return euclidean get Boolean From Value get Evaluated Value Obliviously key xml Element return default Boolean | 6049 | def getEvaluatedBooleanDefault(defaultBoolean, key, xmlElement=None):
if (xmlElement == None):
return None
if (key in xmlElement.attributeDictionary):
return euclidean.getBooleanFromValue(getEvaluatedValueObliviously(key, xmlElement))
return defaultBoolean
| Get the evaluated boolean as a float. | get the evaluated boolean as a float . | Question:
What does this function do?
Code:
def getEvaluatedBooleanDefault(defaultBoolean, key, xmlElement=None):
if (xmlElement == None):
return None
if (key in xmlElement.attributeDictionary):
return euclidean.getBooleanFromValue(getEvaluatedValueObliviously(key, xmlElement))
return defaultBoolean
|
null | null | null | What does this function do? | def MakeID3v1(id3):
v1 = {}
for (v2id, name) in {'TIT2': 'title', 'TPE1': 'artist', 'TALB': 'album'}.items():
if (v2id in id3):
text = id3[v2id].text[0].encode('latin1', 'replace')[:30]
else:
text = ''
v1[name] = (text + ('\x00' * (30 - len(text))))
if ('COMM' in id3):
cmnt = id3['COMM'].text[0].encode... | null | null | null | Return an ID3v1.1 tag string from a dict of ID3v2.4 frames. | pcsd | def Make ID3v1 id3 v1 = {} for v2id name in {'TIT2' 'title' 'TPE1' 'artist' 'TALB' 'album'} items if v2id in id3 text = id3[v2id] text[0] encode 'latin1' 'replace' [ 30] else text = '' v1[name] = text + '\x00' * 30 - len text if 'COMM' in id3 cmnt = id3['COMM'] text[0] encode 'latin1' 'replace' [ 28] else cmnt = '' v1[... | 6057 | def MakeID3v1(id3):
v1 = {}
for (v2id, name) in {'TIT2': 'title', 'TPE1': 'artist', 'TALB': 'album'}.items():
if (v2id in id3):
text = id3[v2id].text[0].encode('latin1', 'replace')[:30]
else:
text = ''
v1[name] = (text + ('\x00' * (30 - len(text))))
if ('COMM' in id3):
cmnt = id3['COMM'].text[0].encode... | Return an ID3v1.1 tag string from a dict of ID3v2.4 frames. | return an id3v1 . 1 tag string from a dict of id3v2 . 4 frames . | Question:
What does this function do?
Code:
def MakeID3v1(id3):
v1 = {}
for (v2id, name) in {'TIT2': 'title', 'TPE1': 'artist', 'TALB': 'album'}.items():
if (v2id in id3):
text = id3[v2id].text[0].encode('latin1', 'replace')[:30]
else:
text = ''
v1[name] = (text + ('\x00' * (30 - len(text))))
if ('COM... |
null | null | null | What does this function do? | def get_connection(using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
return connections[using]
| null | null | null | Get a database connection by name, or the default database connection
if no name is provided. | pcsd | def get connection using=None if using is None using = DEFAULT DB ALIAS return connections[using] | 6059 | def get_connection(using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
return connections[using]
| Get a database connection by name, or the default database connection
if no name is provided. | get a database connection by name , or the default database connection if no name is provided . | Question:
What does this function do?
Code:
def get_connection(using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
return connections[using]
|
null | null | null | What does this function do? | def owner(path, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
with settings(hide('running', 'stdout'), warn_only=True):
result = func(('stat -c %%U "%(path)s"' % locals()))
if (result.failed and ('stat: illegal option' in result)):
return func(('stat -f %%Su "%(path)s"' % locals()))
else:
re... | null | null | null | Get the owner name of a file or directory. | pcsd | def owner path use sudo=False func = use sudo and run as root or run with settings hide 'running' 'stdout' warn only=True result = func 'stat -c %%U "% path s"' % locals if result failed and 'stat illegal option' in result return func 'stat -f %%Su "% path s"' % locals else return result | 6071 | def owner(path, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
with settings(hide('running', 'stdout'), warn_only=True):
result = func(('stat -c %%U "%(path)s"' % locals()))
if (result.failed and ('stat: illegal option' in result)):
return func(('stat -f %%Su "%(path)s"' % locals()))
else:
re... | Get the owner name of a file or directory. | get the owner name of a file or directory . | Question:
What does this function do?
Code:
def owner(path, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
with settings(hide('running', 'stdout'), warn_only=True):
result = func(('stat -c %%U "%(path)s"' % locals()))
if (result.failed and ('stat: illegal option' in result)):
return func(('stat... |
null | null | null | What does this function do? | def cbranch_or_continue(builder, cond, bbtrue):
bbcont = builder.append_basic_block('.continue')
builder.cbranch(cond, bbtrue, bbcont)
builder.position_at_end(bbcont)
return bbcont
| null | null | null | Branch conditionally or continue.
Note: a new block is created and builder is moved to the end of the new
block. | pcsd | def cbranch or continue builder cond bbtrue bbcont = builder append basic block ' continue' builder cbranch cond bbtrue bbcont builder position at end bbcont return bbcont | 6075 | def cbranch_or_continue(builder, cond, bbtrue):
bbcont = builder.append_basic_block('.continue')
builder.cbranch(cond, bbtrue, bbcont)
builder.position_at_end(bbcont)
return bbcont
| Branch conditionally or continue.
Note: a new block is created and builder is moved to the end of the new
block. | branch conditionally or continue . | Question:
What does this function do?
Code:
def cbranch_or_continue(builder, cond, bbtrue):
bbcont = builder.append_basic_block('.continue')
builder.cbranch(cond, bbtrue, bbcont)
builder.position_at_end(bbcont)
return bbcont
|
null | null | null | What does this function do? | def default_catalogue_backend():
msg = ("There is no '%s' backend in CATALOGUE" % DEFAULT_CATALOGUE_ALIAS)
assert (DEFAULT_CATALOGUE_ALIAS in settings.CATALOGUE), msg
return settings.CATALOGUE[DEFAULT_CATALOGUE_ALIAS]
| null | null | null | Get the default backend | pcsd | def default catalogue backend msg = "There is no '%s' backend in CATALOGUE" % DEFAULT CATALOGUE ALIAS assert DEFAULT CATALOGUE ALIAS in settings CATALOGUE msg return settings CATALOGUE[DEFAULT CATALOGUE ALIAS] | 6076 | def default_catalogue_backend():
msg = ("There is no '%s' backend in CATALOGUE" % DEFAULT_CATALOGUE_ALIAS)
assert (DEFAULT_CATALOGUE_ALIAS in settings.CATALOGUE), msg
return settings.CATALOGUE[DEFAULT_CATALOGUE_ALIAS]
| Get the default backend | get the default backend | Question:
What does this function do?
Code:
def default_catalogue_backend():
msg = ("There is no '%s' backend in CATALOGUE" % DEFAULT_CATALOGUE_ALIAS)
assert (DEFAULT_CATALOGUE_ALIAS in settings.CATALOGUE), msg
return settings.CATALOGUE[DEFAULT_CATALOGUE_ALIAS]
|
null | null | null | What does this function do? | def create():
redirect(URL(f='new_assessment.iframe', vars={'viewing': ('survey_series.%s' % request.args[0])}))
| null | null | null | Enter a new assessment.
- provides a simpler URL to access from mobile devices... | pcsd | def create redirect URL f='new assessment iframe' vars={'viewing' 'survey series %s' % request args[0] } | 6079 | def create():
redirect(URL(f='new_assessment.iframe', vars={'viewing': ('survey_series.%s' % request.args[0])}))
| Enter a new assessment.
- provides a simpler URL to access from mobile devices... | enter a new assessment . | Question:
What does this function do?
Code:
def create():
redirect(URL(f='new_assessment.iframe', vars={'viewing': ('survey_series.%s' % request.args[0])}))
|
null | null | null | What does this function do? | def IsPythonVersionCorrect(path):
from ycmd import utils
if (not EndsWithPython(path)):
return False
command = [path, u'-S', u'-c', u'import sys;major, minor = sys.version_info[ :2 ];good_python = ( major == 2 and minor >= 6 ) or ( major == 3 and minor >= 3 ) or major > 3;sys.exit( not good_python )']
return (uti... | null | null | null | Check if given path is the Python interpreter version 2.6+ or 3.3+. | pcsd | def Is Python Version Correct path from ycmd import utils if not Ends With Python path return False command = [path u'-S' u'-c' u'import sys major minor = sys version info[ 2 ] good python = major == 2 and minor >= 6 or major == 3 and minor >= 3 or major > 3 sys exit not good python '] return utils Safe Popen command w... | 6084 | def IsPythonVersionCorrect(path):
from ycmd import utils
if (not EndsWithPython(path)):
return False
command = [path, u'-S', u'-c', u'import sys;major, minor = sys.version_info[ :2 ];good_python = ( major == 2 and minor >= 6 ) or ( major == 3 and minor >= 3 ) or major > 3;sys.exit( not good_python )']
return (uti... | Check if given path is the Python interpreter version 2.6+ or 3.3+. | check if given path is the python interpreter version 2 . 6 + or 3 . 3 + . | Question:
What does this function do?
Code:
def IsPythonVersionCorrect(path):
from ycmd import utils
if (not EndsWithPython(path)):
return False
command = [path, u'-S', u'-c', u'import sys;major, minor = sys.version_info[ :2 ];good_python = ( major == 2 and minor >= 6 ) or ( major == 3 and minor >= 3 ) or major... |
null | null | null | What does this function do? | def p_relational_expression_3(t):
pass
| null | null | null | relational_expression : relational_expression GT shift_expression | pcsd | def p relational expression 3 t pass | 6088 | def p_relational_expression_3(t):
pass
| relational_expression : relational_expression GT shift_expression | relational _ expression : relational _ expression gt shift _ expression | Question:
What does this function do?
Code:
def p_relational_expression_3(t):
pass
|
null | null | null | What does this function do? | def remote_interpreter(conn, namespace=None):
if (namespace is None):
namespace = {'conn': conn}
std = RedirectedStd(conn)
try:
std.redirect()
conn.modules[__name__]._remote_interpreter_server_side(**namespace)
finally:
std.restore()
| null | null | null | starts an interactive interpreter on the server | pcsd | def remote interpreter conn namespace=None if namespace is None namespace = {'conn' conn} std = Redirected Std conn try std redirect conn modules[ name ] remote interpreter server side **namespace finally std restore | 6089 | def remote_interpreter(conn, namespace=None):
if (namespace is None):
namespace = {'conn': conn}
std = RedirectedStd(conn)
try:
std.redirect()
conn.modules[__name__]._remote_interpreter_server_side(**namespace)
finally:
std.restore()
| starts an interactive interpreter on the server | starts an interactive interpreter on the server | Question:
What does this function do?
Code:
def remote_interpreter(conn, namespace=None):
if (namespace is None):
namespace = {'conn': conn}
std = RedirectedStd(conn)
try:
std.redirect()
conn.modules[__name__]._remote_interpreter_server_side(**namespace)
finally:
std.restore()
|
null | null | null | What does this function do? | def check_space(in_files, force, _testhook_free_space=None):
in_file = in_files[0]
dir_path = os.path.dirname(os.path.realpath(in_file))
target = os.statvfs(dir_path)
if (_testhook_free_space is None):
free_space = (target.f_frsize * target.f_bavail)
else:
free_space = _testhook_free_space
valid_files = [f fo... | null | null | null | Check for available disk space.
Estimate size of input files passed, then calculate disk space
available and exit if disk space is insufficient. | pcsd | def check space in files force testhook free space=None in file = in files[0] dir path = os path dirname os path realpath in file target = os statvfs dir path if testhook free space is None free space = target f frsize * target f bavail else free space = testhook free space valid files = [f for f in in files if os path... | 6094 | def check_space(in_files, force, _testhook_free_space=None):
in_file = in_files[0]
dir_path = os.path.dirname(os.path.realpath(in_file))
target = os.statvfs(dir_path)
if (_testhook_free_space is None):
free_space = (target.f_frsize * target.f_bavail)
else:
free_space = _testhook_free_space
valid_files = [f fo... | Check for available disk space.
Estimate size of input files passed, then calculate disk space
available and exit if disk space is insufficient. | check for available disk space . | Question:
What does this function do?
Code:
def check_space(in_files, force, _testhook_free_space=None):
in_file = in_files[0]
dir_path = os.path.dirname(os.path.realpath(in_file))
target = os.statvfs(dir_path)
if (_testhook_free_space is None):
free_space = (target.f_frsize * target.f_bavail)
else:
free_sp... |
null | null | null | What does this function do? | def get_printout(out, opts=None, **kwargs):
if (opts is None):
opts = {}
if (('output' in opts) and (opts['output'] != 'highstate')):
out = opts['output']
if (out == 'text'):
out = 'txt'
elif ((out is None) or (out == '')):
out = 'nested'
if opts.get('progress', False):
out = 'progress'
opts.update(kwar... | null | null | null | Return a printer function | pcsd | def get printout out opts=None **kwargs if opts is None opts = {} if 'output' in opts and opts['output'] != 'highstate' out = opts['output'] if out == 'text' out = 'txt' elif out is None or out == '' out = 'nested' if opts get 'progress' False out = 'progress' opts update kwargs if 'color' not in opts def is pipe ' Che... | 6104 | def get_printout(out, opts=None, **kwargs):
if (opts is None):
opts = {}
if (('output' in opts) and (opts['output'] != 'highstate')):
out = opts['output']
if (out == 'text'):
out = 'txt'
elif ((out is None) or (out == '')):
out = 'nested'
if opts.get('progress', False):
out = 'progress'
opts.update(kwar... | Return a printer function | return a printer function | Question:
What does this function do?
Code:
def get_printout(out, opts=None, **kwargs):
if (opts is None):
opts = {}
if (('output' in opts) and (opts['output'] != 'highstate')):
out = opts['output']
if (out == 'text'):
out = 'txt'
elif ((out is None) or (out == '')):
out = 'nested'
if opts.get('progress... |
null | null | null | What does this function do? | def scan_used_functions(example_file, gallery_conf):
example_code_obj = identify_names(open(example_file).read())
if example_code_obj:
codeobj_fname = (example_file[:(-3)] + '_codeobj.pickle')
with open(codeobj_fname, 'wb') as fid:
pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL)
backrefs = set(('{... | null | null | null | save variables so we can later add links to the documentation | pcsd | def scan used functions example file gallery conf example code obj = identify names open example file read if example code obj codeobj fname = example file[ -3 ] + ' codeobj pickle' with open codeobj fname 'wb' as fid pickle dump example code obj fid pickle HIGHEST PROTOCOL backrefs = set '{module short} {name}' format... | 6105 | def scan_used_functions(example_file, gallery_conf):
example_code_obj = identify_names(open(example_file).read())
if example_code_obj:
codeobj_fname = (example_file[:(-3)] + '_codeobj.pickle')
with open(codeobj_fname, 'wb') as fid:
pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL)
backrefs = set(('{... | save variables so we can later add links to the documentation | save variables so we can later add links to the documentation | Question:
What does this function do?
Code:
def scan_used_functions(example_file, gallery_conf):
example_code_obj = identify_names(open(example_file).read())
if example_code_obj:
codeobj_fname = (example_file[:(-3)] + '_codeobj.pickle')
with open(codeobj_fname, 'wb') as fid:
pickle.dump(example_code_obj, fi... |
null | null | null | What does this function do? | def file_upload_echo_content(request):
r = dict([(k, f.read()) for (k, f) in request.FILES.items()])
return HttpResponse(simplejson.dumps(r))
| null | null | null | Simple view to echo back the content of uploaded files for tests. | pcsd | def file upload echo content request r = dict [ k f read for k f in request FILES items ] return Http Response simplejson dumps r | 6106 | def file_upload_echo_content(request):
r = dict([(k, f.read()) for (k, f) in request.FILES.items()])
return HttpResponse(simplejson.dumps(r))
| Simple view to echo back the content of uploaded files for tests. | simple view to echo back the content of uploaded files for tests . | Question:
What does this function do?
Code:
def file_upload_echo_content(request):
r = dict([(k, f.read()) for (k, f) in request.FILES.items()])
return HttpResponse(simplejson.dumps(r))
|
null | null | null | What does this function do? | def _playback_progress(idx, allsongs, repeat=False):
cw = util.getxy().width
out = ' %s%-XXs%s%s\n'.replace('XX', str((cw - 9)))
out = (out % (c.ul, 'Title', 'Time', c.w))
show_key_help = (util.is_known_player(config.PLAYER.get) and config.SHOW_MPLAYER_KEYS.get)
multi = (len(allsongs) > 1)
for (n, song) in enume... | null | null | null | Generate string to show selected tracks, indicate current track. | pcsd | def playback progress idx allsongs repeat=False cw = util getxy width out = ' %s%-X Xs%s%s ' replace 'XX' str cw - 9 out = out % c ul 'Title' 'Time' c w show key help = util is known player config PLAYER get and config SHOW MPLAYER KEYS get multi = len allsongs > 1 for n song in enumerate allsongs length orig = util fm... | 6109 | def _playback_progress(idx, allsongs, repeat=False):
cw = util.getxy().width
out = ' %s%-XXs%s%s\n'.replace('XX', str((cw - 9)))
out = (out % (c.ul, 'Title', 'Time', c.w))
show_key_help = (util.is_known_player(config.PLAYER.get) and config.SHOW_MPLAYER_KEYS.get)
multi = (len(allsongs) > 1)
for (n, song) in enume... | Generate string to show selected tracks, indicate current track. | generate string to show selected tracks , indicate current track . | Question:
What does this function do?
Code:
def _playback_progress(idx, allsongs, repeat=False):
cw = util.getxy().width
out = ' %s%-XXs%s%s\n'.replace('XX', str((cw - 9)))
out = (out % (c.ul, 'Title', 'Time', c.w))
show_key_help = (util.is_known_player(config.PLAYER.get) and config.SHOW_MPLAYER_KEYS.get)
mult... |
null | null | null | What does this function do? | def dumpNetConnections(net):
nodes = ((net.controllers + net.switches) + net.hosts)
dumpNodeConnections(nodes)
| null | null | null | Dump connections in network | pcsd | def dump Net Connections net nodes = net controllers + net switches + net hosts dump Node Connections nodes | 6110 | def dumpNetConnections(net):
nodes = ((net.controllers + net.switches) + net.hosts)
dumpNodeConnections(nodes)
| Dump connections in network | dump connections in network | Question:
What does this function do?
Code:
def dumpNetConnections(net):
nodes = ((net.controllers + net.switches) + net.hosts)
dumpNodeConnections(nodes)
|
null | null | null | What does this function do? | def sample_distribution(distribution):
r = random.uniform(0, 1)
s = 0
for i in range(len(distribution)):
s += distribution[i]
if (s >= r):
return i
return (len(distribution) - 1)
| null | null | null | Sample one element from a distribution assumed to be an array of normalized
probabilities. | pcsd | def sample distribution distribution r = random uniform 0 1 s = 0 for i in range len distribution s += distribution[i] if s >= r return i return len distribution - 1 | 6118 | def sample_distribution(distribution):
r = random.uniform(0, 1)
s = 0
for i in range(len(distribution)):
s += distribution[i]
if (s >= r):
return i
return (len(distribution) - 1)
| Sample one element from a distribution assumed to be an array of normalized
probabilities. | sample one element from a distribution assumed to be an array of normalized probabilities . | Question:
What does this function do?
Code:
def sample_distribution(distribution):
r = random.uniform(0, 1)
s = 0
for i in range(len(distribution)):
s += distribution[i]
if (s >= r):
return i
return (len(distribution) - 1)
|
null | null | null | What does this function do? | def _make_unique(l):
return sorted(set(l))
| null | null | null | Check that all values in list are unique and return a pruned and sorted list. | pcsd | def make unique l return sorted set l | 6121 | def _make_unique(l):
return sorted(set(l))
| Check that all values in list are unique and return a pruned and sorted list. | check that all values in list are unique and return a pruned and sorted list . | Question:
What does this function do?
Code:
def _make_unique(l):
return sorted(set(l))
|
null | null | null | What does this function do? | def parse_positional_flags(source, info, flags_on, flags_off):
version = ((info.flags & _ALL_VERSIONS) or DEFAULT_VERSION)
if (version == VERSION0):
if flags_off:
raise error('bad inline flags: cannot turn flags off', source.string, source.pos)
new_global_flags = (flags_on & (~ info.global_flags))
if new_glo... | null | null | null | Parses positional flags. | pcsd | def parse positional flags source info flags on flags off version = info flags & ALL VERSIONS or DEFAULT VERSION if version == VERSION0 if flags off raise error 'bad inline flags cannot turn flags off' source string source pos new global flags = flags on & ~ info global flags if new global flags info global flags |= ne... | 6128 | def parse_positional_flags(source, info, flags_on, flags_off):
version = ((info.flags & _ALL_VERSIONS) or DEFAULT_VERSION)
if (version == VERSION0):
if flags_off:
raise error('bad inline flags: cannot turn flags off', source.string, source.pos)
new_global_flags = (flags_on & (~ info.global_flags))
if new_glo... | Parses positional flags. | parses positional flags . | Question:
What does this function do?
Code:
def parse_positional_flags(source, info, flags_on, flags_off):
version = ((info.flags & _ALL_VERSIONS) or DEFAULT_VERSION)
if (version == VERSION0):
if flags_off:
raise error('bad inline flags: cannot turn flags off', source.string, source.pos)
new_global_flags = ... |
null | null | null | What does this function do? | def create_txn(asset, dt, price, amount):
if (not isinstance(asset, Asset)):
raise ValueError('pass an asset to create_txn')
mock_order = Order(dt, asset, amount, id=None)
return create_transaction(mock_order, dt, price, amount)
| null | null | null | Create a fake transaction to be filled and processed prior to the execution
of a given trade event. | pcsd | def create txn asset dt price amount if not isinstance asset Asset raise Value Error 'pass an asset to create txn' mock order = Order dt asset amount id=None return create transaction mock order dt price amount | 6132 | def create_txn(asset, dt, price, amount):
if (not isinstance(asset, Asset)):
raise ValueError('pass an asset to create_txn')
mock_order = Order(dt, asset, amount, id=None)
return create_transaction(mock_order, dt, price, amount)
| Create a fake transaction to be filled and processed prior to the execution
of a given trade event. | create a fake transaction to be filled and processed prior to the execution of a given trade event . | Question:
What does this function do?
Code:
def create_txn(asset, dt, price, amount):
if (not isinstance(asset, Asset)):
raise ValueError('pass an asset to create_txn')
mock_order = Order(dt, asset, amount, id=None)
return create_transaction(mock_order, dt, price, amount)
|
null | null | null | What does this function do? | def detect_distro_type():
if os.path.exists('/etc/redhat-release'):
return 'redhat'
elif os.path.exists('/etc/debian_version'):
return 'debian'
elif os.path.exists('/etc/SuSE-release'):
return 'suse'
else:
return None
| null | null | null | Simple distro detection based on release/version files | pcsd | def detect distro type if os path exists '/etc/redhat-release' return 'redhat' elif os path exists '/etc/debian version' return 'debian' elif os path exists '/etc/Su SE-release' return 'suse' else return None | 6140 | def detect_distro_type():
if os.path.exists('/etc/redhat-release'):
return 'redhat'
elif os.path.exists('/etc/debian_version'):
return 'debian'
elif os.path.exists('/etc/SuSE-release'):
return 'suse'
else:
return None
| Simple distro detection based on release/version files | simple distro detection based on release / version files | Question:
What does this function do?
Code:
def detect_distro_type():
if os.path.exists('/etc/redhat-release'):
return 'redhat'
elif os.path.exists('/etc/debian_version'):
return 'debian'
elif os.path.exists('/etc/SuSE-release'):
return 'suse'
else:
return None
|
null | null | null | What does this function do? | @pytest.mark.parametrize('url, expected', (('http://192.168.0.1:5000/', True), ('http://192.168.0.1/', True), ('http://172.16.1.1/', True), ('http://172.16.1.1:5000/', True), ('http://localhost.localdomain:5000/v1.0/', True), ('http://172.16.1.12/', False), ('http://172.16.1.12:5000/', False), ('http://google.com:5000/... | null | null | null | Tests for function should_bypass_proxies to check if proxy
can be bypassed or not | pcsd | @pytest mark parametrize 'url expected' 'http //192 168 0 1 5000/' True 'http //192 168 0 1/' True 'http //172 16 1 1/' True 'http //172 16 1 1 5000/' True 'http //localhost localdomain 5000/v1 0/' True 'http //172 16 1 12/' False 'http //172 16 1 12 5000/' False 'http //google com 5000/v1 0/' False def test should byp... | 6144 | @pytest.mark.parametrize('url, expected', (('http://192.168.0.1:5000/', True), ('http://192.168.0.1/', True), ('http://172.16.1.1/', True), ('http://172.16.1.1:5000/', True), ('http://localhost.localdomain:5000/v1.0/', True), ('http://172.16.1.12/', False), ('http://172.16.1.12:5000/', False), ('http://google.com:5000/... | Tests for function should_bypass_proxies to check if proxy
can be bypassed or not | tests for function should _ bypass _ proxies to check if proxy can be bypassed or not | Question:
What does this function do?
Code:
@pytest.mark.parametrize('url, expected', (('http://192.168.0.1:5000/', True), ('http://192.168.0.1/', True), ('http://172.16.1.1/', True), ('http://172.16.1.1:5000/', True), ('http://localhost.localdomain:5000/v1.0/', True), ('http://172.16.1.12/', False), ('http://172.16... |
null | null | null | What does this function do? | def numel(x, **kwargs):
return chunk.sum(np.ones_like(x), **kwargs)
| null | null | null | A reduction to count the number of elements | pcsd | def numel x **kwargs return chunk sum np ones like x **kwargs | 6148 | def numel(x, **kwargs):
return chunk.sum(np.ones_like(x), **kwargs)
| A reduction to count the number of elements | a reduction to count the number of elements | Question:
What does this function do?
Code:
def numel(x, **kwargs):
return chunk.sum(np.ones_like(x), **kwargs)
|
null | null | null | What does this function do? | def _resolve_name(name, package, level):
level -= 1
try:
if (package.count('.') < level):
raise ValueError('attempted relative import beyond top-level package')
except AttributeError:
raise ValueError("'package' not set to a string")
try:
dot_rindex = package.rindex('.', level)[0]
base = package[:dot_rin... | null | null | null | Return the absolute name of the module to be imported. | pcsd | def resolve name name package level level -= 1 try if package count ' ' < level raise Value Error 'attempted relative import beyond top-level package' except Attribute Error raise Value Error "'package' not set to a string" try dot rindex = package rindex ' ' level [0] base = package[ dot rindex] except Value Error bas... | 6154 | def _resolve_name(name, package, level):
level -= 1
try:
if (package.count('.') < level):
raise ValueError('attempted relative import beyond top-level package')
except AttributeError:
raise ValueError("'package' not set to a string")
try:
dot_rindex = package.rindex('.', level)[0]
base = package[:dot_rin... | Return the absolute name of the module to be imported. | return the absolute name of the module to be imported . | Question:
What does this function do?
Code:
def _resolve_name(name, package, level):
level -= 1
try:
if (package.count('.') < level):
raise ValueError('attempted relative import beyond top-level package')
except AttributeError:
raise ValueError("'package' not set to a string")
try:
dot_rindex = package.... |
null | null | null | What does this function do? | def todolist():
app = (request.vars.app or '')
app_path = apath(('%(app)s' % {'app': app}), r=request)
dirs = ['models', 'controllers', 'modules', 'private']
def listfiles(app, dir, regexp='.*\\.py$'):
files = sorted(listdir(apath(('%(app)s/%(dir)s/' % {'app': app, 'dir': dir}), r=request), regexp))
files = [x.... | null | null | null | Returns all TODO of the requested app | pcsd | def todolist app = request vars app or '' app path = apath '% app s' % {'app' app} r=request dirs = ['models' 'controllers' 'modules' 'private'] def listfiles app dir regexp=' *\\ py$' files = sorted listdir apath '% app s/% dir s/' % {'app' app 'dir' dir} r=request regexp files = [x replace os path sep '/' for x in fi... | 6159 | def todolist():
app = (request.vars.app or '')
app_path = apath(('%(app)s' % {'app': app}), r=request)
dirs = ['models', 'controllers', 'modules', 'private']
def listfiles(app, dir, regexp='.*\\.py$'):
files = sorted(listdir(apath(('%(app)s/%(dir)s/' % {'app': app, 'dir': dir}), r=request), regexp))
files = [x.... | Returns all TODO of the requested app | returns all todo of the requested app | Question:
What does this function do?
Code:
def todolist():
app = (request.vars.app or '')
app_path = apath(('%(app)s' % {'app': app}), r=request)
dirs = ['models', 'controllers', 'modules', 'private']
def listfiles(app, dir, regexp='.*\\.py$'):
files = sorted(listdir(apath(('%(app)s/%(dir)s/' % {'app': app, '... |
null | null | null | What does this function do? | def base_repr(number, base=2, padding=0):
chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if (number < base):
return (((padding - 1) * chars[0]) + chars[int(number)])
max_exponent = int((math.log(number) / math.log(base)))
max_power = (long(base) ** max_exponent)
lead_digit = int((number / max_power))
return (c... | null | null | null | Return the representation of a *number* in any given *base*. | pcsd | def base repr number base=2 padding=0 chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if number < base return padding - 1 * chars[0] + chars[int number ] max exponent = int math log number / math log base max power = long base ** max exponent lead digit = int number / max power return chars[lead digit] + base repr numb... | 6161 | def base_repr(number, base=2, padding=0):
chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if (number < base):
return (((padding - 1) * chars[0]) + chars[int(number)])
max_exponent = int((math.log(number) / math.log(base)))
max_power = (long(base) ** max_exponent)
lead_digit = int((number / max_power))
return (c... | Return the representation of a *number* in any given *base*. | return the representation of a * number * in any given * base * . | Question:
What does this function do?
Code:
def base_repr(number, base=2, padding=0):
chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if (number < base):
return (((padding - 1) * chars[0]) + chars[int(number)])
max_exponent = int((math.log(number) / math.log(base)))
max_power = (long(base) ** max_exponent)
le... |
null | null | null | What does this function do? | def floor(mat, target=None):
if (not target):
target = mat
err_code = _eigenmat.apply_floor(mat.p_mat, target.p_mat)
if err_code:
raise generate_exception(err_code)
return target
| null | null | null | Apply the floor function to each element of the matrix mat. | pcsd | def floor mat target=None if not target target = mat err code = eigenmat apply floor mat p mat target p mat if err code raise generate exception err code return target | 6162 | def floor(mat, target=None):
if (not target):
target = mat
err_code = _eigenmat.apply_floor(mat.p_mat, target.p_mat)
if err_code:
raise generate_exception(err_code)
return target
| Apply the floor function to each element of the matrix mat. | apply the floor function to each element of the matrix mat . | Question:
What does this function do?
Code:
def floor(mat, target=None):
if (not target):
target = mat
err_code = _eigenmat.apply_floor(mat.p_mat, target.p_mat)
if err_code:
raise generate_exception(err_code)
return target
|
null | null | null | What does this function do? | def get_rdm_disk(hardware_devices, uuid):
if (hardware_devices.__class__.__name__ == 'ArrayOfVirtualDevice'):
hardware_devices = hardware_devices.VirtualDevice
for device in hardware_devices:
if ((device.__class__.__name__ == 'VirtualDisk') and (device.backing.__class__.__name__ == 'VirtualDiskRawDiskMappingVer1B... | null | null | null | Gets the RDM disk key. | pcsd | def get rdm disk hardware devices uuid if hardware devices class name == 'Array Of Virtual Device' hardware devices = hardware devices Virtual Device for device in hardware devices if device class name == 'Virtual Disk' and device backing class name == 'Virtual Disk Raw Disk Mapping Ver1Backing Info' and device backing... | 6172 | def get_rdm_disk(hardware_devices, uuid):
if (hardware_devices.__class__.__name__ == 'ArrayOfVirtualDevice'):
hardware_devices = hardware_devices.VirtualDevice
for device in hardware_devices:
if ((device.__class__.__name__ == 'VirtualDisk') and (device.backing.__class__.__name__ == 'VirtualDiskRawDiskMappingVer1B... | Gets the RDM disk key. | gets the rdm disk key . | Question:
What does this function do?
Code:
def get_rdm_disk(hardware_devices, uuid):
if (hardware_devices.__class__.__name__ == 'ArrayOfVirtualDevice'):
hardware_devices = hardware_devices.VirtualDevice
for device in hardware_devices:
if ((device.__class__.__name__ == 'VirtualDisk') and (device.backing.__clas... |
null | null | null | What does this function do? | def get_session_config():
return copy.deepcopy(_session['config'])
| null | null | null | Returns either module config or file config. | pcsd | def get session config return copy deepcopy session['config'] | 6175 | def get_session_config():
return copy.deepcopy(_session['config'])
| Returns either module config or file config. | returns either module config or file config . | Question:
What does this function do?
Code:
def get_session_config():
return copy.deepcopy(_session['config'])
|
null | null | null | What does this function do? | @utils.arg('host', metavar='<hostname>', help=_('Name of host.'))
@utils.arg('--action', metavar='<action>', dest='action', choices=['startup', 'shutdown', 'reboot'], help=_('A power action: startup, reboot, or shutdown.'))
def do_host_action(cs, args):
result = cs.hosts.host_action(args.host, args.action)
utils.prin... | null | null | null | Perform a power action on a host. | pcsd | @utils arg 'host' metavar='<hostname>' help= 'Name of host ' @utils arg '--action' metavar='<action>' dest='action' choices=['startup' 'shutdown' 'reboot'] help= 'A power action startup reboot or shutdown ' def do host action cs args result = cs hosts host action args host args action utils print list [result] ['HOST' ... | 6181 | @utils.arg('host', metavar='<hostname>', help=_('Name of host.'))
@utils.arg('--action', metavar='<action>', dest='action', choices=['startup', 'shutdown', 'reboot'], help=_('A power action: startup, reboot, or shutdown.'))
def do_host_action(cs, args):
result = cs.hosts.host_action(args.host, args.action)
utils.prin... | Perform a power action on a host. | perform a power action on a host . | Question:
What does this function do?
Code:
@utils.arg('host', metavar='<hostname>', help=_('Name of host.'))
@utils.arg('--action', metavar='<action>', dest='action', choices=['startup', 'shutdown', 'reboot'], help=_('A power action: startup, reboot, or shutdown.'))
def do_host_action(cs, args):
result = cs.hosts.... |
null | null | null | What does this function do? | def urlnormalize(href):
try:
parts = urlparse(href)
except ValueError as e:
raise ValueError(('Failed to parse the URL: %r with underlying error: %s' % (href, as_unicode(e))))
if ((not parts.scheme) or (parts.scheme == 'file')):
(path, frag) = urldefrag(href)
parts = ('', '', path, '', '', frag)
parts = (pa... | null | null | null | Convert a URL into normalized form, with all and only URL-unsafe
characters URL quoted. | pcsd | def urlnormalize href try parts = urlparse href except Value Error as e raise Value Error 'Failed to parse the URL %r with underlying error %s' % href as unicode e if not parts scheme or parts scheme == 'file' path frag = urldefrag href parts = '' '' path '' '' frag parts = part replace '\\' '/' for part in parts parts... | 6187 | def urlnormalize(href):
try:
parts = urlparse(href)
except ValueError as e:
raise ValueError(('Failed to parse the URL: %r with underlying error: %s' % (href, as_unicode(e))))
if ((not parts.scheme) or (parts.scheme == 'file')):
(path, frag) = urldefrag(href)
parts = ('', '', path, '', '', frag)
parts = (pa... | Convert a URL into normalized form, with all and only URL-unsafe
characters URL quoted. | convert a url into normalized form , with all and only url - unsafe characters url quoted . | Question:
What does this function do?
Code:
def urlnormalize(href):
try:
parts = urlparse(href)
except ValueError as e:
raise ValueError(('Failed to parse the URL: %r with underlying error: %s' % (href, as_unicode(e))))
if ((not parts.scheme) or (parts.scheme == 'file')):
(path, frag) = urldefrag(href)
pa... |
null | null | null | What does this function do? | def roster(opts, runner, whitelist=None):
return LazyLoader(_module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={'__runner__': runner})
| null | null | null | Returns the roster modules | pcsd | def roster opts runner whitelist=None return Lazy Loader module dirs opts 'roster' opts tag='roster' whitelist=whitelist pack={' runner ' runner} | 6189 | def roster(opts, runner, whitelist=None):
return LazyLoader(_module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={'__runner__': runner})
| Returns the roster modules | returns the roster modules | Question:
What does this function do?
Code:
def roster(opts, runner, whitelist=None):
return LazyLoader(_module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={'__runner__': runner})
|
null | null | null | What does this function do? | def create_or_update_tool_dependency(app, tool_shed_repository, name, version, type, status, set_status=True):
context = app.install_model.context
if version:
tool_dependency = get_tool_dependency_by_name_version_type_repository(app, tool_shed_repository, name, version, type)
else:
tool_dependency = get_tool_dep... | null | null | null | Create or update a tool_dependency record in the Galaxy database. | pcsd | def create or update tool dependency app tool shed repository name version type status set status=True context = app install model context if version tool dependency = get tool dependency by name version type repository app tool shed repository name version type else tool dependency = get tool dependency by name type r... | 6192 | def create_or_update_tool_dependency(app, tool_shed_repository, name, version, type, status, set_status=True):
context = app.install_model.context
if version:
tool_dependency = get_tool_dependency_by_name_version_type_repository(app, tool_shed_repository, name, version, type)
else:
tool_dependency = get_tool_dep... | Create or update a tool_dependency record in the Galaxy database. | create or update a tool _ dependency record in the galaxy database . | Question:
What does this function do?
Code:
def create_or_update_tool_dependency(app, tool_shed_repository, name, version, type, status, set_status=True):
context = app.install_model.context
if version:
tool_dependency = get_tool_dependency_by_name_version_type_repository(app, tool_shed_repository, name, version... |
null | null | null | What does this function do? | def evalRnnOnSeqDataset(net, DS, verbose=False, silent=False):
r = 0.0
samples = 0.0
for seq in DS:
net.reset()
for (i, t) in seq:
res = net.activate(i)
if verbose:
print(t, res)
r += sum(((t - res) ** 2))
samples += 1
if verbose:
print(('-' * 20))
r /= samples
if (not silent):
print('MS... | null | null | null | evaluate the network on all the sequences of a dataset. | pcsd | def eval Rnn On Seq Dataset net DS verbose=False silent=False r = 0 0 samples = 0 0 for seq in DS net reset for i t in seq res = net activate i if verbose print t res r += sum t - res ** 2 samples += 1 if verbose print '-' * 20 r /= samples if not silent print 'MSE ' r return r | 6193 | def evalRnnOnSeqDataset(net, DS, verbose=False, silent=False):
r = 0.0
samples = 0.0
for seq in DS:
net.reset()
for (i, t) in seq:
res = net.activate(i)
if verbose:
print(t, res)
r += sum(((t - res) ** 2))
samples += 1
if verbose:
print(('-' * 20))
r /= samples
if (not silent):
print('MS... | evaluate the network on all the sequences of a dataset. | evaluate the network on all the sequences of a dataset . | Question:
What does this function do?
Code:
def evalRnnOnSeqDataset(net, DS, verbose=False, silent=False):
r = 0.0
samples = 0.0
for seq in DS:
net.reset()
for (i, t) in seq:
res = net.activate(i)
if verbose:
print(t, res)
r += sum(((t - res) ** 2))
samples += 1
if verbose:
print(('-' * 2... |
null | null | null | What does this function do? | def remove_old_versions(db):
start = ('%s.%s.0' % (major, minor))
migrate_features = 1
if snapshot:
add_data(db, 'Upgrade', [(upgrade_code_snapshot, start, current_version, None, migrate_features, None, 'REMOVEOLDSNAPSHOT')])
props = 'REMOVEOLDSNAPSHOT'
else:
add_data(db, 'Upgrade', [(upgrade_code, start, cur... | null | null | null | Fill the upgrade table. | pcsd | def remove old versions db start = '%s %s 0' % major minor migrate features = 1 if snapshot add data db 'Upgrade' [ upgrade code snapshot start current version None migrate features None 'REMOVEOLDSNAPSHOT' ] props = 'REMOVEOLDSNAPSHOT' else add data db 'Upgrade' [ upgrade code start current version None migrate featur... | 6195 | def remove_old_versions(db):
start = ('%s.%s.0' % (major, minor))
migrate_features = 1
if snapshot:
add_data(db, 'Upgrade', [(upgrade_code_snapshot, start, current_version, None, migrate_features, None, 'REMOVEOLDSNAPSHOT')])
props = 'REMOVEOLDSNAPSHOT'
else:
add_data(db, 'Upgrade', [(upgrade_code, start, cur... | Fill the upgrade table. | fill the upgrade table . | Question:
What does this function do?
Code:
def remove_old_versions(db):
start = ('%s.%s.0' % (major, minor))
migrate_features = 1
if snapshot:
add_data(db, 'Upgrade', [(upgrade_code_snapshot, start, current_version, None, migrate_features, None, 'REMOVEOLDSNAPSHOT')])
props = 'REMOVEOLDSNAPSHOT'
else:
add... |
null | null | null | What does this function do? | @bdd.then(bdd.parsers.parse('The unordered requests should be:\n{pages}'))
def list_of_requests_unordered(httpbin, pages):
expected_requests = [httpbin.ExpectedRequest('GET', ('/' + path.strip())) for path in pages.split('\n')]
actual_requests = httpbin.get_requests()
actual_requests = [httpbin.ExpectedRequest.from_... | null | null | null | Make sure the given requests were done (in no particular order). | pcsd | @bdd then bdd parsers parse 'The unordered requests should be {pages}' def list of requests unordered httpbin pages expected requests = [httpbin Expected Request 'GET' '/' + path strip for path in pages split ' ' ] actual requests = httpbin get requests actual requests = [httpbin Expected Request from request req for r... | 6197 | @bdd.then(bdd.parsers.parse('The unordered requests should be:\n{pages}'))
def list_of_requests_unordered(httpbin, pages):
expected_requests = [httpbin.ExpectedRequest('GET', ('/' + path.strip())) for path in pages.split('\n')]
actual_requests = httpbin.get_requests()
actual_requests = [httpbin.ExpectedRequest.from_... | Make sure the given requests were done (in no particular order). | make sure the given requests were done . | Question:
What does this function do?
Code:
@bdd.then(bdd.parsers.parse('The unordered requests should be:\n{pages}'))
def list_of_requests_unordered(httpbin, pages):
expected_requests = [httpbin.ExpectedRequest('GET', ('/' + path.strip())) for path in pages.split('\n')]
actual_requests = httpbin.get_requests()
a... |
null | null | null | What does this function do? | def add_to_deleted_document(doc):
if ((doc.doctype != u'Deleted Document') and (frappe.flags.in_install != u'frappe')):
frappe.get_doc(dict(doctype=u'Deleted Document', deleted_doctype=doc.doctype, deleted_name=doc.name, data=doc.as_json())).db_insert()
| null | null | null | Add this document to Deleted Document table. Called after delete | pcsd | def add to deleted document doc if doc doctype != u'Deleted Document' and frappe flags in install != u'frappe' frappe get doc dict doctype=u'Deleted Document' deleted doctype=doc doctype deleted name=doc name data=doc as json db insert | 6208 | def add_to_deleted_document(doc):
if ((doc.doctype != u'Deleted Document') and (frappe.flags.in_install != u'frappe')):
frappe.get_doc(dict(doctype=u'Deleted Document', deleted_doctype=doc.doctype, deleted_name=doc.name, data=doc.as_json())).db_insert()
| Add this document to Deleted Document table. Called after delete | add this document to deleted document table . | Question:
What does this function do?
Code:
def add_to_deleted_document(doc):
if ((doc.doctype != u'Deleted Document') and (frappe.flags.in_install != u'frappe')):
frappe.get_doc(dict(doctype=u'Deleted Document', deleted_doctype=doc.doctype, deleted_name=doc.name, data=doc.as_json())).db_insert()
|
null | null | null | What does this function do? | def _format_info(data):
return {'name': data.gr_name, 'gid': data.gr_gid, 'passwd': data.gr_passwd, 'members': data.gr_mem}
| null | null | null | Return formatted information in a pretty way. | pcsd | def format info data return {'name' data gr name 'gid' data gr gid 'passwd' data gr passwd 'members' data gr mem} | 6225 | def _format_info(data):
return {'name': data.gr_name, 'gid': data.gr_gid, 'passwd': data.gr_passwd, 'members': data.gr_mem}
| Return formatted information in a pretty way. | return formatted information in a pretty way . | Question:
What does this function do?
Code:
def _format_info(data):
return {'name': data.gr_name, 'gid': data.gr_gid, 'passwd': data.gr_passwd, 'members': data.gr_mem}
|
null | null | null | What does this function do? | def GetImages(region, owner_ids=None):
ec2 = _Connect(region)
if (not owner_ids):
return None
return ec2.get_all_images(owners=owner_ids)
| null | null | null | Return the list of images owned IDs from \'owner_ids\'. If None or empty, we return nothing. | pcsd | def Get Images region owner ids=None ec2 = Connect region if not owner ids return None return ec2 get all images owners=owner ids | 6233 | def GetImages(region, owner_ids=None):
ec2 = _Connect(region)
if (not owner_ids):
return None
return ec2.get_all_images(owners=owner_ids)
| Return the list of images owned IDs from \'owner_ids\'. If None or empty, we return nothing. | return the list of images owned ids from owner _ ids . | Question:
What does this function do?
Code:
def GetImages(region, owner_ids=None):
ec2 = _Connect(region)
if (not owner_ids):
return None
return ec2.get_all_images(owners=owner_ids)
|
null | null | null | What does this function do? | def try_import(import_str, default=None):
try:
return import_module(import_str)
except ImportError:
return default
| null | null | null | Try to import a module and if it fails return default. | pcsd | def try import import str default=None try return import module import str except Import Error return default | 6237 | def try_import(import_str, default=None):
try:
return import_module(import_str)
except ImportError:
return default
| Try to import a module and if it fails return default. | try to import a module and if it fails return default . | Question:
What does this function do?
Code:
def try_import(import_str, default=None):
try:
return import_module(import_str)
except ImportError:
return default
|
null | null | null | What does this function do? | @lru_cache()
def time_to_days(value):
if (value.tzinfo is not None):
value = value.astimezone(UTC)
return (((((value.hour * 3600) + (value.minute * 60)) + value.second) + (value.microsecond / (10 ** 6))) / SECS_PER_DAY)
| null | null | null | Convert a time value to fractions of day | pcsd | @lru cache def time to days value if value tzinfo is not None value = value astimezone UTC return value hour * 3600 + value minute * 60 + value second + value microsecond / 10 ** 6 / SECS PER DAY | 6242 | @lru_cache()
def time_to_days(value):
if (value.tzinfo is not None):
value = value.astimezone(UTC)
return (((((value.hour * 3600) + (value.minute * 60)) + value.second) + (value.microsecond / (10 ** 6))) / SECS_PER_DAY)
| Convert a time value to fractions of day | convert a time value to fractions of day | Question:
What does this function do?
Code:
@lru_cache()
def time_to_days(value):
if (value.tzinfo is not None):
value = value.astimezone(UTC)
return (((((value.hour * 3600) + (value.minute * 60)) + value.second) + (value.microsecond / (10 ** 6))) / SECS_PER_DAY)
|
null | null | null | What does this function do? | def S_IMODE(mode):
return (mode & 4095)
| null | null | null | Return the portion of the file\'s mode that can be set by
os.chmod(). | pcsd | def S IMODE mode return mode & 4095 | 6245 | def S_IMODE(mode):
return (mode & 4095)
| Return the portion of the file\'s mode that can be set by
os.chmod(). | return the portion of the files mode that can be set by os . chmod ( ) . | Question:
What does this function do?
Code:
def S_IMODE(mode):
return (mode & 4095)
|
null | null | null | What does this function do? | def get_template(template_name, globals=None):
try:
return get_env().get_template(template_name, globals=globals)
except TemplateNotFound as e:
raise TemplateDoesNotExist(str(e))
| null | null | null | Load a template. | pcsd | def get template template name globals=None try return get env get template template name globals=globals except Template Not Found as e raise Template Does Not Exist str e | 6246 | def get_template(template_name, globals=None):
try:
return get_env().get_template(template_name, globals=globals)
except TemplateNotFound as e:
raise TemplateDoesNotExist(str(e))
| Load a template. | load a template . | Question:
What does this function do?
Code:
def get_template(template_name, globals=None):
try:
return get_env().get_template(template_name, globals=globals)
except TemplateNotFound as e:
raise TemplateDoesNotExist(str(e))
|
null | null | null | What does this function do? | def get_effective_router(appname):
if ((not routers) or (appname not in routers)):
return None
return Storage(routers[appname])
| null | null | null | Returns a private copy of the effective router for the specified application | pcsd | def get effective router appname if not routers or appname not in routers return None return Storage routers[appname] | 6252 | def get_effective_router(appname):
if ((not routers) or (appname not in routers)):
return None
return Storage(routers[appname])
| Returns a private copy of the effective router for the specified application | returns a private copy of the effective router for the specified application | Question:
What does this function do?
Code:
def get_effective_router(appname):
if ((not routers) or (appname not in routers)):
return None
return Storage(routers[appname])
|
null | null | null | What does this function do? | @pytest.mark.network
def test_download_setuptools(script):
result = script.pip('download', 'setuptools')
setuptools_prefix = str((Path('scratch') / 'setuptools'))
assert any((path.startswith(setuptools_prefix) for path in result.files_created))
| null | null | null | It should download (in the scratch path) and not install if requested. | pcsd | @pytest mark network def test download setuptools script result = script pip 'download' 'setuptools' setuptools prefix = str Path 'scratch' / 'setuptools' assert any path startswith setuptools prefix for path in result files created | 6256 | @pytest.mark.network
def test_download_setuptools(script):
result = script.pip('download', 'setuptools')
setuptools_prefix = str((Path('scratch') / 'setuptools'))
assert any((path.startswith(setuptools_prefix) for path in result.files_created))
| It should download (in the scratch path) and not install if requested. | it should download and not install if requested . | Question:
What does this function do?
Code:
@pytest.mark.network
def test_download_setuptools(script):
result = script.pip('download', 'setuptools')
setuptools_prefix = str((Path('scratch') / 'setuptools'))
assert any((path.startswith(setuptools_prefix) for path in result.files_created))
|
null | null | null | What does this function do? | def create_groups(update):
(guest_group, created) = Group.objects.get_or_create(name=u'Guests')
if (created or update or (guest_group.permissions.count() == 0)):
guest_group.permissions.add(Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_suggestion'))
(group, creat... | null | null | null | Creates standard groups and gives them permissions. | pcsd | def create groups update guest group created = Group objects get or create name=u'Guests' if created or update or guest group permissions count == 0 guest group permissions add Permission objects get codename=u'can see git repository' Permission objects get codename=u'add suggestion' group created = Group objects get o... | 6257 | def create_groups(update):
(guest_group, created) = Group.objects.get_or_create(name=u'Guests')
if (created or update or (guest_group.permissions.count() == 0)):
guest_group.permissions.add(Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_suggestion'))
(group, creat... | Creates standard groups and gives them permissions. | creates standard groups and gives them permissions . | Question:
What does this function do?
Code:
def create_groups(update):
(guest_group, created) = Group.objects.get_or_create(name=u'Guests')
if (created or update or (guest_group.permissions.count() == 0)):
guest_group.permissions.add(Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.... |
null | null | null | What does this function do? | def is_image_extendable(image):
LOG.debug('Checking if we can extend filesystem inside %(image)s.', {'image': image})
if ((not isinstance(image, imgmodel.LocalImage)) or (image.format != imgmodel.FORMAT_RAW)):
fs = None
try:
fs = vfs.VFS.instance_for_image(image, None)
fs.setup(mount=False)
if (fs.get_im... | null | null | null | Check whether we can extend the image. | pcsd | def is image extendable image LOG debug 'Checking if we can extend filesystem inside % image s ' {'image' image} if not isinstance image imgmodel Local Image or image format != imgmodel FORMAT RAW fs = None try fs = vfs VFS instance for image image None fs setup mount=False if fs get image fs in SUPPORTED FS TO EXTEND ... | 6259 | def is_image_extendable(image):
LOG.debug('Checking if we can extend filesystem inside %(image)s.', {'image': image})
if ((not isinstance(image, imgmodel.LocalImage)) or (image.format != imgmodel.FORMAT_RAW)):
fs = None
try:
fs = vfs.VFS.instance_for_image(image, None)
fs.setup(mount=False)
if (fs.get_im... | Check whether we can extend the image. | check whether we can extend the image . | Question:
What does this function do?
Code:
def is_image_extendable(image):
LOG.debug('Checking if we can extend filesystem inside %(image)s.', {'image': image})
if ((not isinstance(image, imgmodel.LocalImage)) or (image.format != imgmodel.FORMAT_RAW)):
fs = None
try:
fs = vfs.VFS.instance_for_image(image, ... |
null | null | null | What does this function do? | @login_required
def edit_answer(request, question_id, answer_id):
answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
answer_preview = None
if (not answer.allows_edit(request.user)):
raise PermissionDenied
upload_imageattachment(request, answer)
if (request.method == 'GET'):
form = AnswerFor... | null | null | null | Edit an answer. | pcsd | @login required def edit answer request question id answer id answer = get object or 404 Answer pk=answer id question=question id answer preview = None if not answer allows edit request user raise Permission Denied upload imageattachment request answer if request method == 'GET' form = Answer Form {'content' answer con... | 6262 | @login_required
def edit_answer(request, question_id, answer_id):
answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
answer_preview = None
if (not answer.allows_edit(request.user)):
raise PermissionDenied
upload_imageattachment(request, answer)
if (request.method == 'GET'):
form = AnswerFor... | Edit an answer. | edit an answer . | Question:
What does this function do?
Code:
@login_required
def edit_answer(request, question_id, answer_id):
answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
answer_preview = None
if (not answer.allows_edit(request.user)):
raise PermissionDenied
upload_imageattachment(request, answer)
i... |
null | null | null | What does this function do? | def load_filters(filters_path):
filterlist = []
for filterdir in filters_path:
if (not os.path.isdir(filterdir)):
continue
for filterfile in os.listdir(filterdir):
filterconfig = ConfigParser.RawConfigParser()
filterconfig.read(os.path.join(filterdir, filterfile))
for (name, value) in filterconfig.ite... | null | null | null | Load filters from a list of directories | pcsd | def load filters filters path filterlist = [] for filterdir in filters path if not os path isdir filterdir continue for filterfile in os listdir filterdir filterconfig = Config Parser Raw Config Parser filterconfig read os path join filterdir filterfile for name value in filterconfig items 'Filters' filterdefinition = ... | 6269 | def load_filters(filters_path):
filterlist = []
for filterdir in filters_path:
if (not os.path.isdir(filterdir)):
continue
for filterfile in os.listdir(filterdir):
filterconfig = ConfigParser.RawConfigParser()
filterconfig.read(os.path.join(filterdir, filterfile))
for (name, value) in filterconfig.ite... | Load filters from a list of directories | load filters from a list of directories | Question:
What does this function do?
Code:
def load_filters(filters_path):
filterlist = []
for filterdir in filters_path:
if (not os.path.isdir(filterdir)):
continue
for filterfile in os.listdir(filterdir):
filterconfig = ConfigParser.RawConfigParser()
filterconfig.read(os.path.join(filterdir, filter... |
null | null | null | What does this function do? | def tumblr2fields(api_key, blogname):
from time import strftime, localtime
try:
import json
except ImportError:
import simplejson as json
try:
import urllib.request as urllib_request
except ImportError:
import urllib2 as urllib_request
def get_tumblr_posts(api_key, blogname, offset=0):
url = (u'http://a... | null | null | null | Imports Tumblr posts (API v2) | pcsd | def tumblr2fields api key blogname from time import strftime localtime try import json except Import Error import simplejson as json try import urllib request as urllib request except Import Error import urllib2 as urllib request def get tumblr posts api key blogname offset=0 url = u'http //api tumblr com/v2/blog/%s tu... | 6274 | def tumblr2fields(api_key, blogname):
from time import strftime, localtime
try:
import json
except ImportError:
import simplejson as json
try:
import urllib.request as urllib_request
except ImportError:
import urllib2 as urllib_request
def get_tumblr_posts(api_key, blogname, offset=0):
url = (u'http://a... | Imports Tumblr posts (API v2) | imports tumblr posts | Question:
What does this function do?
Code:
def tumblr2fields(api_key, blogname):
from time import strftime, localtime
try:
import json
except ImportError:
import simplejson as json
try:
import urllib.request as urllib_request
except ImportError:
import urllib2 as urllib_request
def get_tumblr_posts(ap... |
null | null | null | What does this function do? | def get_volume_extra_specs(volume):
ctxt = context.get_admin_context()
type_id = volume.get('volume_type_id')
if (type_id is None):
return {}
volume_type = volume_types.get_volume_type(ctxt, type_id)
if (volume_type is None):
return {}
extra_specs = volume_type.get('extra_specs', {})
log_extra_spec_warnings(... | null | null | null | Provides extra specs associated with volume. | pcsd | def get volume extra specs volume ctxt = context get admin context type id = volume get 'volume type id' if type id is None return {} volume type = volume types get volume type ctxt type id if volume type is None return {} extra specs = volume type get 'extra specs' {} log extra spec warnings extra specs return extra s... | 6283 | def get_volume_extra_specs(volume):
ctxt = context.get_admin_context()
type_id = volume.get('volume_type_id')
if (type_id is None):
return {}
volume_type = volume_types.get_volume_type(ctxt, type_id)
if (volume_type is None):
return {}
extra_specs = volume_type.get('extra_specs', {})
log_extra_spec_warnings(... | Provides extra specs associated with volume. | provides extra specs associated with volume . | Question:
What does this function do?
Code:
def get_volume_extra_specs(volume):
ctxt = context.get_admin_context()
type_id = volume.get('volume_type_id')
if (type_id is None):
return {}
volume_type = volume_types.get_volume_type(ctxt, type_id)
if (volume_type is None):
return {}
extra_specs = volume_type.g... |
null | null | null | What does this function do? | def download_attachments(output_path, urls):
locations = []
for url in urls:
path = urlparse(url).path
path = path.split(u'/')
filename = path.pop((-1))
localpath = u''
for item in path:
if ((sys.platform != u'win32') or (u':' not in item)):
localpath = os.path.join(localpath, item)
full_path = os.... | null | null | null | Downloads WordPress attachments and returns a list of paths to
attachments that can be associated with a post (relative path to output
directory). Files that fail to download, will not be added to posts | pcsd | def download attachments output path urls locations = [] for url in urls path = urlparse url path path = path split u'/' filename = path pop -1 localpath = u'' for item in path if sys platform != u'win32' or u' ' not in item localpath = os path join localpath item full path = os path join output path localpath if not o... | 6289 | def download_attachments(output_path, urls):
locations = []
for url in urls:
path = urlparse(url).path
path = path.split(u'/')
filename = path.pop((-1))
localpath = u''
for item in path:
if ((sys.platform != u'win32') or (u':' not in item)):
localpath = os.path.join(localpath, item)
full_path = os.... | Downloads WordPress attachments and returns a list of paths to
attachments that can be associated with a post (relative path to output
directory). Files that fail to download, will not be added to posts | downloads wordpress attachments and returns a list of paths to attachments that can be associated with a post . | Question:
What does this function do?
Code:
def download_attachments(output_path, urls):
locations = []
for url in urls:
path = urlparse(url).path
path = path.split(u'/')
filename = path.pop((-1))
localpath = u''
for item in path:
if ((sys.platform != u'win32') or (u':' not in item)):
localpath = ... |
null | null | null | What does this function do? | def read_packet(sock, timeout=None):
sock.settimeout(timeout)
(dlen, data) = (None, None)
try:
if (os.name == 'nt'):
datalen = sock.recv(SZ)
(dlen,) = struct.unpack('l', datalen)
data = ''
while (len(data) < dlen):
data += sock.recv(dlen)
else:
datalen = temp_fail_retry(socket.error, sock.recv... | null | null | null | Read data from socket *sock*
Returns None if something went wrong | pcsd | def read packet sock timeout=None sock settimeout timeout dlen data = None None try if os name == 'nt' datalen = sock recv SZ dlen = struct unpack 'l' datalen data = '' while len data < dlen data += sock recv dlen else datalen = temp fail retry socket error sock recv SZ socket MSG WAITALL if len datalen == SZ dlen = st... | 6293 | def read_packet(sock, timeout=None):
sock.settimeout(timeout)
(dlen, data) = (None, None)
try:
if (os.name == 'nt'):
datalen = sock.recv(SZ)
(dlen,) = struct.unpack('l', datalen)
data = ''
while (len(data) < dlen):
data += sock.recv(dlen)
else:
datalen = temp_fail_retry(socket.error, sock.recv... | Read data from socket *sock*
Returns None if something went wrong | read data from socket * sock * | Question:
What does this function do?
Code:
def read_packet(sock, timeout=None):
sock.settimeout(timeout)
(dlen, data) = (None, None)
try:
if (os.name == 'nt'):
datalen = sock.recv(SZ)
(dlen,) = struct.unpack('l', datalen)
data = ''
while (len(data) < dlen):
data += sock.recv(dlen)
else:
da... |
null | null | null | What does this function do? | def delayed_fail():
time.sleep(5)
raise ValueError('Expected failure.')
| null | null | null | Delayed failure to make sure that processes are running before the error
is raised.
TODO handle more directly (without sleeping) | pcsd | def delayed fail time sleep 5 raise Value Error 'Expected failure ' | 6311 | def delayed_fail():
time.sleep(5)
raise ValueError('Expected failure.')
| Delayed failure to make sure that processes are running before the error
is raised.
TODO handle more directly (without sleeping) | delayed failure to make sure that processes are running before the error is raised . | Question:
What does this function do?
Code:
def delayed_fail():
time.sleep(5)
raise ValueError('Expected failure.')
|
null | null | null | What does this function do? | @register.simple_tag
def simple_one_default(one, two='hi'):
return ('simple_one_default - Expected result: %s, %s' % (one, two))
| null | null | null | Expected simple_one_default __doc__ | pcsd | @register simple tag def simple one default one two='hi' return 'simple one default - Expected result %s %s' % one two | 6321 | @register.simple_tag
def simple_one_default(one, two='hi'):
return ('simple_one_default - Expected result: %s, %s' % (one, two))
| Expected simple_one_default __doc__ | expected simple _ one _ default _ _ doc _ _ | Question:
What does this function do?
Code:
@register.simple_tag
def simple_one_default(one, two='hi'):
return ('simple_one_default - Expected result: %s, %s' % (one, two))
|
null | null | null | What does this function do? | def parse_args():
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int)
parser.add_argument('--solver', dest='solver', help='solver prototxt', default=None, type=str)
parser.add_argument('--iters',... | null | null | null | Parse input arguments | pcsd | def parse args parser = argparse Argument Parser description='Train a Fast R-CNN network' parser add argument '--gpu' dest='gpu id' help='GPU device id to use [0]' default=0 type=int parser add argument '--solver' dest='solver' help='solver prototxt' default=None type=str parser add argument '--iters' dest='max iters' ... | 6324 | def parse_args():
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int)
parser.add_argument('--solver', dest='solver', help='solver prototxt', default=None, type=str)
parser.add_argument('--iters',... | Parse input arguments | parse input arguments | Question:
What does this function do?
Code:
def parse_args():
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int)
parser.add_argument('--solver', dest='solver', help='solver prototxt', default=... |
null | null | null | What does this function do? | def get_default_secret_key():
secret_access_key_script = AWS_ACCOUNTS['default'].SECRET_ACCESS_KEY_SCRIPT.get()
return (secret_access_key_script or get_s3a_secret_key())
| null | null | null | Attempt to set AWS secret key from script, else core-site, else None | pcsd | def get default secret key secret access key script = AWS ACCOUNTS['default'] SECRET ACCESS KEY SCRIPT get return secret access key script or get s3a secret key | 6330 | def get_default_secret_key():
secret_access_key_script = AWS_ACCOUNTS['default'].SECRET_ACCESS_KEY_SCRIPT.get()
return (secret_access_key_script or get_s3a_secret_key())
| Attempt to set AWS secret key from script, else core-site, else None | attempt to set aws secret key from script , else core - site , else none | Question:
What does this function do?
Code:
def get_default_secret_key():
secret_access_key_script = AWS_ACCOUNTS['default'].SECRET_ACCESS_KEY_SCRIPT.get()
return (secret_access_key_script or get_s3a_secret_key())
|
null | null | null | What does this function do? | def baseline():
assess_tables()
return s3_rest_controller()
| null | null | null | RESTful CRUD controller | pcsd | def baseline assess tables return s3 rest controller | 6334 | def baseline():
assess_tables()
return s3_rest_controller()
| RESTful CRUD controller | restful crud controller | Question:
What does this function do?
Code:
def baseline():
assess_tables()
return s3_rest_controller()
|
null | null | null | What does this function do? | def getLocationFromSplitLine(oldLocation, splitLine):
if (oldLocation == None):
oldLocation = Vector3()
return Vector3(getDoubleFromCharacterSplitLineValue('X', splitLine, oldLocation.x), getDoubleFromCharacterSplitLineValue('Y', splitLine, oldLocation.y), getDoubleFromCharacterSplitLineValue('Z', splitLine, oldLoc... | null | null | null | Get the location from the split line. | pcsd | def get Location From Split Line old Location split Line if old Location == None old Location = Vector3 return Vector3 get Double From Character Split Line Value 'X' split Line old Location x get Double From Character Split Line Value 'Y' split Line old Location y get Double From Character Split Line Value 'Z' split Li... | 6335 | def getLocationFromSplitLine(oldLocation, splitLine):
if (oldLocation == None):
oldLocation = Vector3()
return Vector3(getDoubleFromCharacterSplitLineValue('X', splitLine, oldLocation.x), getDoubleFromCharacterSplitLineValue('Y', splitLine, oldLocation.y), getDoubleFromCharacterSplitLineValue('Z', splitLine, oldLoc... | Get the location from the split line. | get the location from the split line . | Question:
What does this function do?
Code:
def getLocationFromSplitLine(oldLocation, splitLine):
if (oldLocation == None):
oldLocation = Vector3()
return Vector3(getDoubleFromCharacterSplitLineValue('X', splitLine, oldLocation.x), getDoubleFromCharacterSplitLineValue('Y', splitLine, oldLocation.y), getDoubleFro... |
null | null | null | What does this function do? | def generate_x509_cert(user_id, project_id, bits=2048):
subject = _user_cert_subject(user_id, project_id)
with utils.tempdir() as tmpdir:
keyfile = os.path.abspath(os.path.join(tmpdir, 'temp.key'))
csrfile = os.path.abspath(os.path.join(tmpdir, 'temp.csr'))
utils.execute('openssl', 'genrsa', '-out', keyfile, st... | null | null | null | Generate and sign a cert for user in project. | pcsd | def generate x509 cert user id project id bits=2048 subject = user cert subject user id project id with utils tempdir as tmpdir keyfile = os path abspath os path join tmpdir 'temp key' csrfile = os path abspath os path join tmpdir 'temp csr' utils execute 'openssl' 'genrsa' '-out' keyfile str bits utils execute 'openss... | 6337 | def generate_x509_cert(user_id, project_id, bits=2048):
subject = _user_cert_subject(user_id, project_id)
with utils.tempdir() as tmpdir:
keyfile = os.path.abspath(os.path.join(tmpdir, 'temp.key'))
csrfile = os.path.abspath(os.path.join(tmpdir, 'temp.csr'))
utils.execute('openssl', 'genrsa', '-out', keyfile, st... | Generate and sign a cert for user in project. | generate and sign a cert for user in project . | Question:
What does this function do?
Code:
def generate_x509_cert(user_id, project_id, bits=2048):
subject = _user_cert_subject(user_id, project_id)
with utils.tempdir() as tmpdir:
keyfile = os.path.abspath(os.path.join(tmpdir, 'temp.key'))
csrfile = os.path.abspath(os.path.join(tmpdir, 'temp.csr'))
utils.e... |
null | null | null | What does this function do? | def randrange_fmt(mode, char, obj):
x = randrange(*fmtdict[mode][char])
if (char == 'c'):
x = bytes([x])
if ((obj == 'numpy') and (x == '\x00')):
x = '\x01'
if (char == '?'):
x = bool(x)
if ((char == 'f') or (char == 'd')):
x = struct.pack(char, x)
x = struct.unpack(char, x)[0]
return x
| null | null | null | Return random item for a type specified by a mode and a single
format character. | pcsd | def randrange fmt mode char obj x = randrange *fmtdict[mode][char] if char == 'c' x = bytes [x] if obj == 'numpy' and x == '\x00' x = '\x01' if char == '?' x = bool x if char == 'f' or char == 'd' x = struct pack char x x = struct unpack char x [0] return x | 6341 | def randrange_fmt(mode, char, obj):
x = randrange(*fmtdict[mode][char])
if (char == 'c'):
x = bytes([x])
if ((obj == 'numpy') and (x == '\x00')):
x = '\x01'
if (char == '?'):
x = bool(x)
if ((char == 'f') or (char == 'd')):
x = struct.pack(char, x)
x = struct.unpack(char, x)[0]
return x
| Return random item for a type specified by a mode and a single
format character. | return random item for a type specified by a mode and a single format character . | Question:
What does this function do?
Code:
def randrange_fmt(mode, char, obj):
x = randrange(*fmtdict[mode][char])
if (char == 'c'):
x = bytes([x])
if ((obj == 'numpy') and (x == '\x00')):
x = '\x01'
if (char == '?'):
x = bool(x)
if ((char == 'f') or (char == 'd')):
x = struct.pack(char, x)
x = str... |
null | null | null | What does this function do? | def remove_dir_if_empty(path, ignore_metadata_caches=False):
try:
os.rmdir(path)
except OSError as e:
if ((e.errno == errno.ENOTEMPTY) or (len(os.listdir(path)) > 0)):
if ignore_metadata_caches:
try:
found = False
for x in os.listdir(path):
if (x.lower() in {'.ds_store', 'thumbs.db'}):
... | null | null | null | Remove a directory if it is empty or contains only the folder metadata
caches from different OSes. To delete the folder if it contains only
metadata caches, set ignore_metadata_caches to True. | pcsd | def remove dir if empty path ignore metadata caches=False try os rmdir path except OS Error as e if e errno == errno ENOTEMPTY or len os listdir path > 0 if ignore metadata caches try found = False for x in os listdir path if x lower in {' ds store' 'thumbs db'} found = True x = os path join path x if os path isdir x i... | 6342 | def remove_dir_if_empty(path, ignore_metadata_caches=False):
try:
os.rmdir(path)
except OSError as e:
if ((e.errno == errno.ENOTEMPTY) or (len(os.listdir(path)) > 0)):
if ignore_metadata_caches:
try:
found = False
for x in os.listdir(path):
if (x.lower() in {'.ds_store', 'thumbs.db'}):
... | Remove a directory if it is empty or contains only the folder metadata
caches from different OSes. To delete the folder if it contains only
metadata caches, set ignore_metadata_caches to True. | remove a directory if it is empty or contains only the folder metadata caches from different oses . | Question:
What does this function do?
Code:
def remove_dir_if_empty(path, ignore_metadata_caches=False):
try:
os.rmdir(path)
except OSError as e:
if ((e.errno == errno.ENOTEMPTY) or (len(os.listdir(path)) > 0)):
if ignore_metadata_caches:
try:
found = False
for x in os.listdir(path):
if ... |
null | null | null | What does this function do? | def python_int_bitwidth():
return (struct.calcsize('l') * 8)
| null | null | null | Return the bit width of Python int (C long int).
Note that it can be different from the size of a memory pointer. | pcsd | def python int bitwidth return struct calcsize 'l' * 8 | 6361 | def python_int_bitwidth():
return (struct.calcsize('l') * 8)
| Return the bit width of Python int (C long int).
Note that it can be different from the size of a memory pointer. | return the bit width of python int . | Question:
What does this function do?
Code:
def python_int_bitwidth():
return (struct.calcsize('l') * 8)
|
null | null | null | What does this function do? | def start():
global __SCHED
if __SCHED:
logging.debug('Starting scheduler')
__SCHED.start()
| null | null | null | Start the scheduler | pcsd | def start global SCHED if SCHED logging debug 'Starting scheduler' SCHED start | 6364 | def start():
global __SCHED
if __SCHED:
logging.debug('Starting scheduler')
__SCHED.start()
| Start the scheduler | start the scheduler | Question:
What does this function do?
Code:
def start():
global __SCHED
if __SCHED:
logging.debug('Starting scheduler')
__SCHED.start()
|
null | null | null | What does this function do? | @pytest.fixture
def temporary_topic():
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(TOPIC_NAME)
if topic.exists():
topic.delete()
(yield)
if topic.exists():
topic.delete()
| null | null | null | Fixture that ensures the test dataset does not exist before or
after a test. | pcsd | @pytest fixture def temporary topic pubsub client = pubsub Client topic = pubsub client topic TOPIC NAME if topic exists topic delete yield if topic exists topic delete | 6370 | @pytest.fixture
def temporary_topic():
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(TOPIC_NAME)
if topic.exists():
topic.delete()
(yield)
if topic.exists():
topic.delete()
| Fixture that ensures the test dataset does not exist before or
after a test. | fixture that ensures the test dataset does not exist before or after a test . | Question:
What does this function do?
Code:
@pytest.fixture
def temporary_topic():
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(TOPIC_NAME)
if topic.exists():
topic.delete()
(yield)
if topic.exists():
topic.delete()
|
null | null | null | What does this function do? | @require_role('user')
def asset_list(request):
(header_title, path1, path2) = (u'\u67e5\u770b\u8d44\u4ea7', u'\u8d44\u4ea7\u7ba1\u7406', u'\u67e5\u770b\u8d44\u4ea7')
username = request.user.username
user_perm = request.session['role_id']
idc_all = IDC.objects.filter()
asset_group_all = AssetGroup.objects.all()
as... | null | null | null | asset list view | pcsd | @require role 'user' def asset list request header title path1 path2 = u'\u67e5\u770b\u8d44\u4ea7' u'\u8d44\u4ea7\u7ba1\u7406' u'\u67e5\u770b\u8d44\u4ea7' username = request user username user perm = request session['role id'] idc all = IDC objects filter asset group all = Asset Group objects all asset types = ASSET TY... | 6373 | @require_role('user')
def asset_list(request):
(header_title, path1, path2) = (u'\u67e5\u770b\u8d44\u4ea7', u'\u8d44\u4ea7\u7ba1\u7406', u'\u67e5\u770b\u8d44\u4ea7')
username = request.user.username
user_perm = request.session['role_id']
idc_all = IDC.objects.filter()
asset_group_all = AssetGroup.objects.all()
as... | asset list view | asset list view | Question:
What does this function do?
Code:
@require_role('user')
def asset_list(request):
(header_title, path1, path2) = (u'\u67e5\u770b\u8d44\u4ea7', u'\u8d44\u4ea7\u7ba1\u7406', u'\u67e5\u770b\u8d44\u4ea7')
username = request.user.username
user_perm = request.session['role_id']
idc_all = IDC.objects.filter()
... |
null | null | null | What does this function do? | @frappe.whitelist()
def get_opening_accounts(company):
accounts = frappe.db.sql_list(u"select\n DCTB DCTB DCTB name from tabAccount\n DCTB DCTB where\n DCTB DCTB DCTB is_group=0 and\n DCTB DCTB DCTB report_type='Balance Sheet' and\n DCTB DCTB DCTB ifnull(warehouse, '') = '' and\n DCTB DCTB DCTB company=%s\n... | null | null | null | get all balance sheet accounts for opening entry | pcsd | @frappe whitelist def get opening accounts company accounts = frappe db sql list u"select DCTB DCTB DCTB name from tab Account DCTB DCTB where DCTB DCTB DCTB is group=0 and DCTB DCTB DCTB report type='Balance Sheet' and DCTB DCTB DCTB ifnull warehouse '' = '' and DCTB DCTB DCTB company=%s DCTB DCTB order by name asc" c... | 6397 | @frappe.whitelist()
def get_opening_accounts(company):
accounts = frappe.db.sql_list(u"select\n DCTB DCTB DCTB name from tabAccount\n DCTB DCTB where\n DCTB DCTB DCTB is_group=0 and\n DCTB DCTB DCTB report_type='Balance Sheet' and\n DCTB DCTB DCTB ifnull(warehouse, '') = '' and\n DCTB DCTB DCTB company=%s\n... | get all balance sheet accounts for opening entry | get all balance sheet accounts for opening entry | Question:
What does this function do?
Code:
@frappe.whitelist()
def get_opening_accounts(company):
accounts = frappe.db.sql_list(u"select\n DCTB DCTB DCTB name from tabAccount\n DCTB DCTB where\n DCTB DCTB DCTB is_group=0 and\n DCTB DCTB DCTB report_type='Balance Sheet' and\n DCTB DCTB DCTB ifnull(warehous... |
null | null | null | What does this function do? | def index():
s3_redirect_default(URL(f='job', args=['datalist']))
| null | null | null | Module\'s Home Page | pcsd | def index s3 redirect default URL f='job' args=['datalist'] | 6400 | def index():
s3_redirect_default(URL(f='job', args=['datalist']))
| Module\'s Home Page | modules home page | Question:
What does this function do?
Code:
def index():
s3_redirect_default(URL(f='job', args=['datalist']))
|
null | null | null | What does this function do? | def _pretty_hex(hex_str):
if ((len(hex_str) % 2) != 0):
hex_str = ('0' + hex_str)
return ':'.join([hex_str[i:(i + 2)] for i in range(0, len(hex_str), 2)]).upper()
| null | null | null | Nicely formats hex strings | pcsd | def pretty hex hex str if len hex str % 2 != 0 hex str = '0' + hex str return ' ' join [hex str[i i + 2 ] for i in range 0 len hex str 2 ] upper | 6419 | def _pretty_hex(hex_str):
if ((len(hex_str) % 2) != 0):
hex_str = ('0' + hex_str)
return ':'.join([hex_str[i:(i + 2)] for i in range(0, len(hex_str), 2)]).upper()
| Nicely formats hex strings | nicely formats hex strings | Question:
What does this function do?
Code:
def _pretty_hex(hex_str):
if ((len(hex_str) % 2) != 0):
hex_str = ('0' + hex_str)
return ':'.join([hex_str[i:(i + 2)] for i in range(0, len(hex_str), 2)]).upper()
|
null | null | null | What does this function do? | def make_list(value):
return list(value)
| null | null | null | Returns the value turned into a list. For an integer, it\'s a list of
digits. For a string, it\'s a list of characters. | pcsd | def make list value return list value | 6422 | def make_list(value):
return list(value)
| Returns the value turned into a list. For an integer, it\'s a list of
digits. For a string, it\'s a list of characters. | returns the value turned into a list . | Question:
What does this function do?
Code:
def make_list(value):
return list(value)
|
null | null | null | What does this function do? | def probe(verbose=False):
import platform
from gsmmodem import GsmModem
import serial
baudrates = [115200, 9600, 19200]
ports = []
if (platform.system() == 'Linux'):
import scanlinux as portscanner
if (platform.system() == 'Windows'):
import scanwin32 as portscanner
if (platform.system() == 'Darwin'):
imp... | null | null | null | Searches for probable ports on the system | pcsd | def probe verbose=False import platform from gsmmodem import Gsm Modem import serial baudrates = [115200 9600 19200] ports = [] if platform system == 'Linux' import scanlinux as portscanner if platform system == 'Windows' import scanwin32 as portscanner if platform system == 'Darwin' import scanmac as portscanner try f... | 6428 | def probe(verbose=False):
import platform
from gsmmodem import GsmModem
import serial
baudrates = [115200, 9600, 19200]
ports = []
if (platform.system() == 'Linux'):
import scanlinux as portscanner
if (platform.system() == 'Windows'):
import scanwin32 as portscanner
if (platform.system() == 'Darwin'):
imp... | Searches for probable ports on the system | searches for probable ports on the system | Question:
What does this function do?
Code:
def probe(verbose=False):
import platform
from gsmmodem import GsmModem
import serial
baudrates = [115200, 9600, 19200]
ports = []
if (platform.system() == 'Linux'):
import scanlinux as portscanner
if (platform.system() == 'Windows'):
import scanwin32 as portsca... |
null | null | null | What does this function do? | def getSortedInjectionTests():
retVal = copy.deepcopy(conf.tests)
def priorityFunction(test):
retVal = SORT_ORDER.FIRST
if (test.stype == PAYLOAD.TECHNIQUE.UNION):
retVal = SORT_ORDER.LAST
elif (('details' in test) and ('dbms' in test.details)):
if intersect(test.details.dbms, Backend.getIdentifiedDbms())... | null | null | null | Returns prioritized test list by eventually detected DBMS from error
messages | pcsd | def get Sorted Injection Tests ret Val = copy deepcopy conf tests def priority Function test ret Val = SORT ORDER FIRST if test stype == PAYLOAD TECHNIQUE UNION ret Val = SORT ORDER LAST elif 'details' in test and 'dbms' in test details if intersect test details dbms Backend get Identified Dbms ret Val = SORT ORDER SEC... | 6431 | def getSortedInjectionTests():
retVal = copy.deepcopy(conf.tests)
def priorityFunction(test):
retVal = SORT_ORDER.FIRST
if (test.stype == PAYLOAD.TECHNIQUE.UNION):
retVal = SORT_ORDER.LAST
elif (('details' in test) and ('dbms' in test.details)):
if intersect(test.details.dbms, Backend.getIdentifiedDbms())... | Returns prioritized test list by eventually detected DBMS from error
messages | returns prioritized test list by eventually detected dbms from error messages | Question:
What does this function do?
Code:
def getSortedInjectionTests():
retVal = copy.deepcopy(conf.tests)
def priorityFunction(test):
retVal = SORT_ORDER.FIRST
if (test.stype == PAYLOAD.TECHNIQUE.UNION):
retVal = SORT_ORDER.LAST
elif (('details' in test) and ('dbms' in test.details)):
if intersect(... |
null | null | null | What does this function do? | def list_bundled_profiles():
path = os.path.join(get_ipython_package_dir(), u'core', u'profile')
files = os.listdir(path)
profiles = []
for profile in files:
full_path = os.path.join(path, profile)
if (os.path.isdir(full_path) and (profile != '__pycache__')):
profiles.append(profile)
return profiles
| null | null | null | list profiles that are bundled with IPython. | pcsd | def list bundled profiles path = os path join get ipython package dir u'core' u'profile' files = os listdir path profiles = [] for profile in files full path = os path join path profile if os path isdir full path and profile != ' pycache ' profiles append profile return profiles | 6438 | def list_bundled_profiles():
path = os.path.join(get_ipython_package_dir(), u'core', u'profile')
files = os.listdir(path)
profiles = []
for profile in files:
full_path = os.path.join(path, profile)
if (os.path.isdir(full_path) and (profile != '__pycache__')):
profiles.append(profile)
return profiles
| list profiles that are bundled with IPython. | list profiles that are bundled with ipython . | Question:
What does this function do?
Code:
def list_bundled_profiles():
path = os.path.join(get_ipython_package_dir(), u'core', u'profile')
files = os.listdir(path)
profiles = []
for profile in files:
full_path = os.path.join(path, profile)
if (os.path.isdir(full_path) and (profile != '__pycache__')):
pr... |
null | null | null | What does this function do? | @utils.arg('--flavor', default=None, metavar='<flavor>', help=_("Name or ID of flavor (see 'nova flavor-list')."))
@utils.arg('--image', default=None, metavar='<image>', help=_("Name or ID of image (see 'glance image-list'). "))
@utils.arg('--image-with', default=[], type=_key_value_pairing, action='append', metavar='<... | null | null | null | Boot a new server. | pcsd | @utils arg '--flavor' default=None metavar='<flavor>' help= "Name or ID of flavor see 'nova flavor-list' " @utils arg '--image' default=None metavar='<image>' help= "Name or ID of image see 'glance image-list' " @utils arg '--image-with' default=[] type= key value pairing action='append' metavar='<key=value>' help= "Im... | 6448 | @utils.arg('--flavor', default=None, metavar='<flavor>', help=_("Name or ID of flavor (see 'nova flavor-list')."))
@utils.arg('--image', default=None, metavar='<image>', help=_("Name or ID of image (see 'glance image-list'). "))
@utils.arg('--image-with', default=[], type=_key_value_pairing, action='append', metavar='<... | Boot a new server. | boot a new server . | Question:
What does this function do?
Code:
@utils.arg('--flavor', default=None, metavar='<flavor>', help=_("Name or ID of flavor (see 'nova flavor-list')."))
@utils.arg('--image', default=None, metavar='<image>', help=_("Name or ID of image (see 'glance image-list'). "))
@utils.arg('--image-with', default=[], type=... |
null | null | null | What does this function do? | def beneficiary_type():
return s3_rest_controller()
| null | null | null | Beneficiary Types: RESTful CRUD Controller | pcsd | def beneficiary type return s3 rest controller | 6453 | def beneficiary_type():
return s3_rest_controller()
| Beneficiary Types: RESTful CRUD Controller | beneficiary types : restful crud controller | Question:
What does this function do?
Code:
def beneficiary_type():
return s3_rest_controller()
|
null | null | null | What does this function do? | def show_image(kwargs, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The show_image action must be called with -f or --function.')
params = {'ImageId.1': kwargs['image'], 'Action': 'DescribeImages'}
result = aws.query(params, setname='tagSet', location=get_location(), provider=get_provider(), opt... | null | null | null | Show the details from EC2 concerning an AMI | pcsd | def show image kwargs call=None if call != 'function' raise Salt Cloud System Exit 'The show image action must be called with -f or --function ' params = {'Image Id 1' kwargs['image'] 'Action' 'Describe Images'} result = aws query params setname='tag Set' location=get location provider=get provider opts= opts sigver='4... | 6455 | def show_image(kwargs, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The show_image action must be called with -f or --function.')
params = {'ImageId.1': kwargs['image'], 'Action': 'DescribeImages'}
result = aws.query(params, setname='tagSet', location=get_location(), provider=get_provider(), opt... | Show the details from EC2 concerning an AMI | show the details from ec2 concerning an ami | Question:
What does this function do?
Code:
def show_image(kwargs, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The show_image action must be called with -f or --function.')
params = {'ImageId.1': kwargs['image'], 'Action': 'DescribeImages'}
result = aws.query(params, setname='tagSet', locati... |
null | null | null | What does this function do? | def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id):
return IMPL.block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id)
| null | null | null | Destroy the block device mapping. | pcsd | def block device mapping destroy by instance and volume context instance uuid volume id return IMPL block device mapping destroy by instance and volume context instance uuid volume id | 6457 | def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id):
return IMPL.block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id)
| Destroy the block device mapping. | destroy the block device mapping . | Question:
What does this function do?
Code:
def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id):
return IMPL.block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id)
|
null | null | null | What does this function do? | def reformat_dict_keys(keymap=None, inputdict=None):
keymap = (keymap or {})
inputdict = (inputdict or {})
return dict([(outk, inputdict[ink]) for (ink, outk) in keymap.items() if (ink in inputdict)])
| null | null | null | Utility function for mapping one dict format to another. | pcsd | def reformat dict keys keymap=None inputdict=None keymap = keymap or {} inputdict = inputdict or {} return dict [ outk inputdict[ink] for ink outk in keymap items if ink in inputdict ] | 6461 | def reformat_dict_keys(keymap=None, inputdict=None):
keymap = (keymap or {})
inputdict = (inputdict or {})
return dict([(outk, inputdict[ink]) for (ink, outk) in keymap.items() if (ink in inputdict)])
| Utility function for mapping one dict format to another. | utility function for mapping one dict format to another . | Question:
What does this function do?
Code:
def reformat_dict_keys(keymap=None, inputdict=None):
keymap = (keymap or {})
inputdict = (inputdict or {})
return dict([(outk, inputdict[ink]) for (ink, outk) in keymap.items() if (ink in inputdict)])
|
null | null | null | What does this function do? | def validate_boxes(boxes, width=0, height=0):
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
assert (x1 >= 0).all()
assert (y1 >= 0).all()
assert (x2 >= x1).all()
assert (y2 >= y1).all()
assert (x2 < width).all()
assert (y2 < height).all()
| null | null | null | Check that a set of boxes are valid. | pcsd | def validate boxes boxes width=0 height=0 x1 = boxes[ 0] y1 = boxes[ 1] x2 = boxes[ 2] y2 = boxes[ 3] assert x1 >= 0 all assert y1 >= 0 all assert x2 >= x1 all assert y2 >= y1 all assert x2 < width all assert y2 < height all | 6466 | def validate_boxes(boxes, width=0, height=0):
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
assert (x1 >= 0).all()
assert (y1 >= 0).all()
assert (x2 >= x1).all()
assert (y2 >= y1).all()
assert (x2 < width).all()
assert (y2 < height).all()
| Check that a set of boxes are valid. | check that a set of boxes are valid . | Question:
What does this function do?
Code:
def validate_boxes(boxes, width=0, height=0):
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
assert (x1 >= 0).all()
assert (y1 >= 0).all()
assert (x2 >= x1).all()
assert (y2 >= y1).all()
assert (x2 < width).all()
assert (y2 < height).all()
|
null | null | null | What does this function do? | def rename_blob(bucket_name, blob_name, new_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
new_blob = bucket.rename_blob(blob, new_name)
print 'Blob {} has been renamed to {}'.format(blob.name, new_blob.name)
| null | null | null | Renames a blob. | pcsd | def rename blob bucket name blob name new name storage client = storage Client bucket = storage client get bucket bucket name blob = bucket blob blob name new blob = bucket rename blob blob new name print 'Blob {} has been renamed to {}' format blob name new blob name | 6468 | def rename_blob(bucket_name, blob_name, new_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
new_blob = bucket.rename_blob(blob, new_name)
print 'Blob {} has been renamed to {}'.format(blob.name, new_blob.name)
| Renames a blob. | renames a blob . | Question:
What does this function do?
Code:
def rename_blob(bucket_name, blob_name, new_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
new_blob = bucket.rename_blob(blob, new_name)
print 'Blob {} has been renamed to {}'.format(blob.name, ne... |
null | null | null | What does this function do? | def render_to_response(template_name, context=None, context_instance=None, response_format='html'):
if (context is None):
context = {}
if (not response_format):
response_format = 'html'
if (response_format not in settings.HARDTREE_RESPONSE_FORMATS):
response_format = 'html'
content_type = settings.HARDTREE_RE... | null | null | null | Extended render_to_response to support different formats | pcsd | def render to response template name context=None context instance=None response format='html' if context is None context = {} if not response format response format = 'html' if response format not in settings HARDTREE RESPONSE FORMATS response format = 'html' content type = settings HARDTREE RESPONSE FORMATS[response ... | 6473 | def render_to_response(template_name, context=None, context_instance=None, response_format='html'):
if (context is None):
context = {}
if (not response_format):
response_format = 'html'
if (response_format not in settings.HARDTREE_RESPONSE_FORMATS):
response_format = 'html'
content_type = settings.HARDTREE_RE... | Extended render_to_response to support different formats | extended render _ to _ response to support different formats | Question:
What does this function do?
Code:
def render_to_response(template_name, context=None, context_instance=None, response_format='html'):
if (context is None):
context = {}
if (not response_format):
response_format = 'html'
if (response_format not in settings.HARDTREE_RESPONSE_FORMATS):
response_forma... |
null | null | null | What does this function do? | def PassphraseCallback(verify=False, prompt1='Enter passphrase:', prompt2='Verify passphrase:'):
while 1:
try:
p1 = getpass.getpass(prompt1)
if verify:
p2 = getpass.getpass(prompt2)
if (p1 == p2):
break
else:
break
except KeyboardInterrupt:
return None
return p1
| null | null | null | A utility function to read a passphrase from stdin. | pcsd | def Passphrase Callback verify=False prompt1='Enter passphrase ' prompt2='Verify passphrase ' while 1 try p1 = getpass getpass prompt1 if verify p2 = getpass getpass prompt2 if p1 == p2 break else break except Keyboard Interrupt return None return p1 | 6477 | def PassphraseCallback(verify=False, prompt1='Enter passphrase:', prompt2='Verify passphrase:'):
while 1:
try:
p1 = getpass.getpass(prompt1)
if verify:
p2 = getpass.getpass(prompt2)
if (p1 == p2):
break
else:
break
except KeyboardInterrupt:
return None
return p1
| A utility function to read a passphrase from stdin. | a utility function to read a passphrase from stdin . | Question:
What does this function do?
Code:
def PassphraseCallback(verify=False, prompt1='Enter passphrase:', prompt2='Verify passphrase:'):
while 1:
try:
p1 = getpass.getpass(prompt1)
if verify:
p2 = getpass.getpass(prompt2)
if (p1 == p2):
break
else:
break
except KeyboardInterrupt:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.