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 pluralize(word, pos=NOUN, custom={}):
return (word + 's')
| null | null | null | Returns the plural of a given word. | pcsd | def pluralize word pos=NOUN custom={} return word + 's' | 17663 | def pluralize(word, pos=NOUN, custom={}):
return (word + 's')
| Returns the plural of a given word. | returns the plural of a given word . | Question:
What does this function do?
Code:
def pluralize(word, pos=NOUN, custom={}):
return (word + 's')
|
null | null | null | What does this function do? | def generate_mac_address():
mac = [250, 22, 62, random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
return ':'.join(map((lambda x: ('%02x' % x)), mac))
| null | null | null | Generate an Ethernet MAC address. | pcsd | def generate mac address mac = [250 22 62 random randint 0 255 random randint 0 255 random randint 0 255 ] return ' ' join map lambda x '%02x' % x mac | 17665 | def generate_mac_address():
mac = [250, 22, 62, random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
return ':'.join(map((lambda x: ('%02x' % x)), mac))
| Generate an Ethernet MAC address. | generate an ethernet mac address . | Question:
What does this function do?
Code:
def generate_mac_address():
mac = [250, 22, 62, random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
return ':'.join(map((lambda x: ('%02x' % x)), mac))
|
null | null | null | What does this function do? | @bdd.when('the documentation is up to date')
def update_documentation():
base_path = os.path.dirname(os.path.abspath(qutebrowser.__file__))
doc_path = os.path.join(base_path, 'html', 'doc')
script_path = os.path.join(base_path, '..', 'scripts')
if (not os.path.exists(doc_path)):
return
if all((docutils.docs_up_t... | null | null | null | Update the docs before testing :help. | pcsd | @bdd when 'the documentation is up to date' def update documentation base path = os path dirname os path abspath qutebrowser file doc path = os path join base path 'html' 'doc' script path = os path join base path ' ' 'scripts' if not os path exists doc path return if all docutils docs up to date p for p in os listdir ... | 17668 | @bdd.when('the documentation is up to date')
def update_documentation():
base_path = os.path.dirname(os.path.abspath(qutebrowser.__file__))
doc_path = os.path.join(base_path, 'html', 'doc')
script_path = os.path.join(base_path, '..', 'scripts')
if (not os.path.exists(doc_path)):
return
if all((docutils.docs_up_t... | Update the docs before testing :help. | update the docs before testing : help . | Question:
What does this function do?
Code:
@bdd.when('the documentation is up to date')
def update_documentation():
base_path = os.path.dirname(os.path.abspath(qutebrowser.__file__))
doc_path = os.path.join(base_path, 'html', 'doc')
script_path = os.path.join(base_path, '..', 'scripts')
if (not os.path.exists(d... |
null | null | null | What does this function do? | def window_funcs(stdscr):
win = curses.newwin(10, 10)
win = curses.newwin(5, 5, 5, 5)
win2 = curses.newwin(15, 15, 5, 5)
for meth in [stdscr.addch, stdscr.addstr]:
for args in ['a', ('a', curses.A_BOLD), (4, 4, 'a'), (5, 5, 'a', curses.A_BOLD)]:
meth(*args)
for meth in [stdscr.box, stdscr.clear, stdscr.clrtob... | null | null | null | Test the methods of windows | pcsd | def window funcs stdscr win = curses newwin 10 10 win = curses newwin 5 5 5 5 win2 = curses newwin 15 15 5 5 for meth in [stdscr addch stdscr addstr] for args in ['a' 'a' curses A BOLD 4 4 'a' 5 5 'a' curses A BOLD ] meth *args for meth in [stdscr box stdscr clear stdscr clrtobot stdscr clrtoeol stdscr cursyncup stdscr... | 17671 | def window_funcs(stdscr):
win = curses.newwin(10, 10)
win = curses.newwin(5, 5, 5, 5)
win2 = curses.newwin(15, 15, 5, 5)
for meth in [stdscr.addch, stdscr.addstr]:
for args in ['a', ('a', curses.A_BOLD), (4, 4, 'a'), (5, 5, 'a', curses.A_BOLD)]:
meth(*args)
for meth in [stdscr.box, stdscr.clear, stdscr.clrtob... | Test the methods of windows | test the methods of windows | Question:
What does this function do?
Code:
def window_funcs(stdscr):
win = curses.newwin(10, 10)
win = curses.newwin(5, 5, 5, 5)
win2 = curses.newwin(15, 15, 5, 5)
for meth in [stdscr.addch, stdscr.addstr]:
for args in ['a', ('a', curses.A_BOLD), (4, 4, 'a'), (5, 5, 'a', curses.A_BOLD)]:
meth(*args)
for m... |
null | null | null | What does this function do? | def _validate_sr(radius):
if isinstance(radius, Quantity):
sr_angle = radius.to(u.degree)
else:
sr_angle = (radius * u.degree)
return sr_angle.value
| null | null | null | Validate search radius. | pcsd | def validate sr radius if isinstance radius Quantity sr angle = radius to u degree else sr angle = radius * u degree return sr angle value | 17677 | def _validate_sr(radius):
if isinstance(radius, Quantity):
sr_angle = radius.to(u.degree)
else:
sr_angle = (radius * u.degree)
return sr_angle.value
| Validate search radius. | validate search radius . | Question:
What does this function do?
Code:
def _validate_sr(radius):
if isinstance(radius, Quantity):
sr_angle = radius.to(u.degree)
else:
sr_angle = (radius * u.degree)
return sr_angle.value
|
null | null | null | What does this function do? | def run_experiment():
return [(random.random() < 0.5) for _ in range(1000)]
| null | null | null | flip a fair coin 1000 times, True = heads, False = tails | pcsd | def run experiment return [ random random < 0 5 for in range 1000 ] | 17678 | def run_experiment():
return [(random.random() < 0.5) for _ in range(1000)]
| flip a fair coin 1000 times, True = heads, False = tails | flip a fair coin 1000 times , true = heads , false = tails | Question:
What does this function do?
Code:
def run_experiment():
return [(random.random() < 0.5) for _ in range(1000)]
|
null | null | null | What does this function do? | def get_soql_fields(soql):
soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE)
soql_fields = re.sub(' ', '', soql_fields.group())
soql_fields = re.sub(' DCTB ', '', soql_fields)
fields = re.split(',|\n|\r|', soql_fields)
fields = [field for field in fields if (field != '')]
return fields
| null | null | null | Gets queried columns names. | pcsd | def get soql fields soql soql fields = re search ' ?<=select ?s * ?=from ' soql re IGNORECASE soql fields = re sub ' ' '' soql fields group soql fields = re sub ' DCTB ' '' soql fields fields = re split ' | |\r|' soql fields fields = [field for field in fields if field != '' ] return fields | 17694 | def get_soql_fields(soql):
soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE)
soql_fields = re.sub(' ', '', soql_fields.group())
soql_fields = re.sub(' DCTB ', '', soql_fields)
fields = re.split(',|\n|\r|', soql_fields)
fields = [field for field in fields if (field != '')]
return fields
| Gets queried columns names. | gets queried columns names . | Question:
What does this function do?
Code:
def get_soql_fields(soql):
soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE)
soql_fields = re.sub(' ', '', soql_fields.group())
soql_fields = re.sub(' DCTB ', '', soql_fields)
fields = re.split(',|\n|\r|', soql_fields)
fields = [field for fie... |
null | null | null | What does this function do? | def multi_filter_str(flt):
assert hasattr(flt, 'filters'), 'Conditional filter required'
(yield name(flt))
| null | null | null | Yield readable conditional filter | pcsd | def multi filter str flt assert hasattr flt 'filters' 'Conditional filter required' yield name flt | 17696 | def multi_filter_str(flt):
assert hasattr(flt, 'filters'), 'Conditional filter required'
(yield name(flt))
| Yield readable conditional filter | yield readable conditional filter | Question:
What does this function do?
Code:
def multi_filter_str(flt):
assert hasattr(flt, 'filters'), 'Conditional filter required'
(yield name(flt))
|
null | null | null | What does this function do? | def update():
base_dir = os.path.join(salt.syspaths.CACHE_DIR, 'azure')
if (not os.path.isdir(base_dir)):
os.makedirs(base_dir)
try:
salt.fileserver.reap_fileserver_cache_dir(os.path.join(base_dir, 'hash'), find_file)
except (IOError, OSError):
pass
data_dict = {}
if os.listdir(base_dir):
all_files = []
... | null | null | null | When we are asked to update (regular interval) lets reap the cache | pcsd | def update base dir = os path join salt syspaths CACHE DIR 'azure' if not os path isdir base dir os makedirs base dir try salt fileserver reap fileserver cache dir os path join base dir 'hash' find file except IO Error OS Error pass data dict = {} if os listdir base dir all files = [] for root sub Folders files in os w... | 17698 | def update():
base_dir = os.path.join(salt.syspaths.CACHE_DIR, 'azure')
if (not os.path.isdir(base_dir)):
os.makedirs(base_dir)
try:
salt.fileserver.reap_fileserver_cache_dir(os.path.join(base_dir, 'hash'), find_file)
except (IOError, OSError):
pass
data_dict = {}
if os.listdir(base_dir):
all_files = []
... | When we are asked to update (regular interval) lets reap the cache | when we are asked to update lets reap the cache | Question:
What does this function do?
Code:
def update():
base_dir = os.path.join(salt.syspaths.CACHE_DIR, 'azure')
if (not os.path.isdir(base_dir)):
os.makedirs(base_dir)
try:
salt.fileserver.reap_fileserver_cache_dir(os.path.join(base_dir, 'hash'), find_file)
except (IOError, OSError):
pass
data_dict = ... |
null | null | null | What does this function do? | @gen.coroutine
def receiver():
pull = ctx.socket(zmq.PULL)
pull.connect(url)
poller = Poller()
poller.register(pull, zmq.POLLIN)
while True:
events = (yield poller.poll(timeout=500))
if (pull in dict(events)):
print ('recving', events)
msg = (yield pull.recv_multipart())
print ('recvd', msg)
else:
... | null | null | null | receive messages with poll and timeout | pcsd | @gen coroutine def receiver pull = ctx socket zmq PULL pull connect url poller = Poller poller register pull zmq POLLIN while True events = yield poller poll timeout=500 if pull in dict events print 'recving' events msg = yield pull recv multipart print 'recvd' msg else print 'nothing to recv' | 17702 | @gen.coroutine
def receiver():
pull = ctx.socket(zmq.PULL)
pull.connect(url)
poller = Poller()
poller.register(pull, zmq.POLLIN)
while True:
events = (yield poller.poll(timeout=500))
if (pull in dict(events)):
print ('recving', events)
msg = (yield pull.recv_multipart())
print ('recvd', msg)
else:
... | receive messages with poll and timeout | receive messages with poll and timeout | Question:
What does this function do?
Code:
@gen.coroutine
def receiver():
pull = ctx.socket(zmq.PULL)
pull.connect(url)
poller = Poller()
poller.register(pull, zmq.POLLIN)
while True:
events = (yield poller.poll(timeout=500))
if (pull in dict(events)):
print ('recving', events)
msg = (yield pull.recv... |
null | null | null | What does this function do? | def DumpSchema():
path = ('LDAP://%srootDSE' % server)
rootdse = ADsGetObject(path)
name = rootdse.Get('schemaNamingContext')
path = (('LDAP://' + server) + name)
print 'Binding to', path
ob = ADsGetObject(path)
nclasses = nattr = nsub = nunk = 0
for child in ob:
class_name = child.Class
if (class_name == '... | null | null | null | Dumps the default DSE schema | pcsd | def Dump Schema path = 'LDAP //%sroot DSE' % server rootdse = A Ds Get Object path name = rootdse Get 'schema Naming Context' path = 'LDAP //' + server + name print 'Binding to' path ob = A Ds Get Object path nclasses = nattr = nsub = nunk = 0 for child in ob class name = child Class if class name == 'class Schema' Dum... | 17717 | def DumpSchema():
path = ('LDAP://%srootDSE' % server)
rootdse = ADsGetObject(path)
name = rootdse.Get('schemaNamingContext')
path = (('LDAP://' + server) + name)
print 'Binding to', path
ob = ADsGetObject(path)
nclasses = nattr = nsub = nunk = 0
for child in ob:
class_name = child.Class
if (class_name == '... | Dumps the default DSE schema | dumps the default dse schema | Question:
What does this function do?
Code:
def DumpSchema():
path = ('LDAP://%srootDSE' % server)
rootdse = ADsGetObject(path)
name = rootdse.Get('schemaNamingContext')
path = (('LDAP://' + server) + name)
print 'Binding to', path
ob = ADsGetObject(path)
nclasses = nattr = nsub = nunk = 0
for child in ob:
... |
null | null | null | What does this function do? | def call_signing(file_obj, endpoint):
with tempfile.NamedTemporaryFile() as temp_file:
temp_filename = temp_file.name
jar = JarExtractor(path=storage.open(file_obj.file_path), outpath=temp_filename, omit_signature_sections=True, extra_newlines=True)
log.debug(u'File signature contents: {0}'.format(jar.signatures))... | null | null | null | Get the jar signature and send it to the signing server to be signed. | pcsd | def call signing file obj endpoint with tempfile Named Temporary File as temp file temp filename = temp file name jar = Jar Extractor path=storage open file obj file path outpath=temp filename omit signature sections=True extra newlines=True log debug u'File signature contents {0}' format jar signatures log debug u'Cal... | 17720 | def call_signing(file_obj, endpoint):
with tempfile.NamedTemporaryFile() as temp_file:
temp_filename = temp_file.name
jar = JarExtractor(path=storage.open(file_obj.file_path), outpath=temp_filename, omit_signature_sections=True, extra_newlines=True)
log.debug(u'File signature contents: {0}'.format(jar.signatures))... | Get the jar signature and send it to the signing server to be signed. | get the jar signature and send it to the signing server to be signed . | Question:
What does this function do?
Code:
def call_signing(file_obj, endpoint):
with tempfile.NamedTemporaryFile() as temp_file:
temp_filename = temp_file.name
jar = JarExtractor(path=storage.open(file_obj.file_path), outpath=temp_filename, omit_signature_sections=True, extra_newlines=True)
log.debug(u'File s... |
null | null | null | What does this function do? | def decode(receipt):
raise NotImplementedError
| null | null | null | Decode and verify that the receipt is sound from a crypto point of view.
Will raise errors if the receipt is not valid, returns receipt contents
if it is valid. | pcsd | def decode receipt raise Not Implemented Error | 17722 | def decode(receipt):
raise NotImplementedError
| Decode and verify that the receipt is sound from a crypto point of view.
Will raise errors if the receipt is not valid, returns receipt contents
if it is valid. | decode and verify that the receipt is sound from a crypto point of view . | Question:
What does this function do?
Code:
def decode(receipt):
raise NotImplementedError
|
null | null | null | What does this function do? | def new_canvas(*args, **kwargs):
allnums = _pylab_helpers.Gcf.figs.keys()
num = ((max(allnums) + 1) if allnums else 1)
FigureClass = kwargs.pop('FigureClass', Figure)
figure = FigureClass(*args, **kwargs)
canvas = FigureCanvas(figure)
fig_manager = FigureManagerQT(canvas, num)
return fig_manager.canvas
| null | null | null | Return a new figure canvas. | pcsd | def new canvas *args **kwargs allnums = pylab helpers Gcf figs keys num = max allnums + 1 if allnums else 1 Figure Class = kwargs pop 'Figure Class' Figure figure = Figure Class *args **kwargs canvas = Figure Canvas figure fig manager = Figure Manager QT canvas num return fig manager canvas | 17725 | def new_canvas(*args, **kwargs):
allnums = _pylab_helpers.Gcf.figs.keys()
num = ((max(allnums) + 1) if allnums else 1)
FigureClass = kwargs.pop('FigureClass', Figure)
figure = FigureClass(*args, **kwargs)
canvas = FigureCanvas(figure)
fig_manager = FigureManagerQT(canvas, num)
return fig_manager.canvas
| Return a new figure canvas. | return a new figure canvas . | Question:
What does this function do?
Code:
def new_canvas(*args, **kwargs):
allnums = _pylab_helpers.Gcf.figs.keys()
num = ((max(allnums) + 1) if allnums else 1)
FigureClass = kwargs.pop('FigureClass', Figure)
figure = FigureClass(*args, **kwargs)
canvas = FigureCanvas(figure)
fig_manager = FigureManagerQT(ca... |
null | null | null | What does this function do? | def _array_clip_val(val):
val = np.array(val)
if ((val.max() > 1) or (val.min() < 0)):
logger.warning('value will be clipped between 0 and 1')
val[...] = np.clip(val, 0, 1)
return val
| null | null | null | Helper to turn val into array and clip between 0 and 1 | pcsd | def array clip val val val = np array val if val max > 1 or val min < 0 logger warning 'value will be clipped between 0 and 1' val[ ] = np clip val 0 1 return val | 17733 | def _array_clip_val(val):
val = np.array(val)
if ((val.max() > 1) or (val.min() < 0)):
logger.warning('value will be clipped between 0 and 1')
val[...] = np.clip(val, 0, 1)
return val
| Helper to turn val into array and clip between 0 and 1 | helper to turn val into array and clip between 0 and 1 | Question:
What does this function do?
Code:
def _array_clip_val(val):
val = np.array(val)
if ((val.max() > 1) or (val.min() < 0)):
logger.warning('value will be clipped between 0 and 1')
val[...] = np.clip(val, 0, 1)
return val
|
null | null | null | What does this function do? | def show_term_protect(name=None, instance_id=None, call=None, quiet=False):
if (call != 'action'):
raise SaltCloudSystemExit('The show_term_protect action must be called with -a or --action.')
if (not instance_id):
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DescribeInstanceAttribute', 'Inst... | null | null | null | Show the details from EC2 concerning an AMI | pcsd | def show term protect name=None instance id=None call=None quiet=False if call != 'action' raise Salt Cloud System Exit 'The show term protect action must be called with -a or --action ' if not instance id instance id = get node name ['instance Id'] params = {'Action' 'Describe Instance Attribute' 'Instance Id' instanc... | 17746 | def show_term_protect(name=None, instance_id=None, call=None, quiet=False):
if (call != 'action'):
raise SaltCloudSystemExit('The show_term_protect action must be called with -a or --action.')
if (not instance_id):
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DescribeInstanceAttribute', 'Inst... | 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_term_protect(name=None, instance_id=None, call=None, quiet=False):
if (call != 'action'):
raise SaltCloudSystemExit('The show_term_protect action must be called with -a or --action.')
if (not instance_id):
instance_id = _get_node(name)['instanceId']
params ... |
null | null | null | What does this function do? | def get_context_loop_positions(context):
try:
loop_counter = context['forloop']['counter']
except KeyError:
return (0, 0)
try:
page = context['page_obj']
except KeyError:
return (loop_counter, loop_counter)
total_loop_counter = (((page.number - 1) * page.paginator.per_page) + loop_counter)
return (total_l... | null | null | null | Return the paginated current position within a loop,
and the non-paginated position. | pcsd | def get context loop positions context try loop counter = context['forloop']['counter'] except Key Error return 0 0 try page = context['page obj'] except Key Error return loop counter loop counter total loop counter = page number - 1 * page paginator per page + loop counter return total loop counter loop counter | 17749 | def get_context_loop_positions(context):
try:
loop_counter = context['forloop']['counter']
except KeyError:
return (0, 0)
try:
page = context['page_obj']
except KeyError:
return (loop_counter, loop_counter)
total_loop_counter = (((page.number - 1) * page.paginator.per_page) + loop_counter)
return (total_l... | Return the paginated current position within a loop,
and the non-paginated position. | return the paginated current position within a loop , and the non - paginated position . | Question:
What does this function do?
Code:
def get_context_loop_positions(context):
try:
loop_counter = context['forloop']['counter']
except KeyError:
return (0, 0)
try:
page = context['page_obj']
except KeyError:
return (loop_counter, loop_counter)
total_loop_counter = (((page.number - 1) * page.pagin... |
null | null | null | What does this function do? | def check_messages(*messages):
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages
| null | null | null | decorator to store messages that are handled by a checker method | pcsd | def check messages *messages def store messages func func checks msgs = messages return func return store messages | 17752 | def check_messages(*messages):
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages
| decorator to store messages that are handled by a checker method | decorator to store messages that are handled by a checker method | Question:
What does this function do?
Code:
def check_messages(*messages):
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages
|
null | null | null | What does this function do? | def event_type():
return s3_rest_controller()
| null | null | null | RESTful CRUD controller | pcsd | def event type return s3 rest controller | 17765 | def event_type():
return s3_rest_controller()
| RESTful CRUD controller | restful crud controller | Question:
What does this function do?
Code:
def event_type():
return s3_rest_controller()
|
null | null | null | What does this function do? | def maybe_get_subscriber_emails(stream, user_profile):
try:
subscribers = get_subscriber_emails(stream, requesting_user=user_profile)
except JsonableError:
subscribers = []
return subscribers
| null | null | null | Alternate version of get_subscriber_emails that takes a Stream object only
(not a name), and simply returns an empty list if unable to get a real
subscriber list (because we\'re on the MIT realm). | pcsd | def maybe get subscriber emails stream user profile try subscribers = get subscriber emails stream requesting user=user profile except Jsonable Error subscribers = [] return subscribers | 17771 | def maybe_get_subscriber_emails(stream, user_profile):
try:
subscribers = get_subscriber_emails(stream, requesting_user=user_profile)
except JsonableError:
subscribers = []
return subscribers
| Alternate version of get_subscriber_emails that takes a Stream object only
(not a name), and simply returns an empty list if unable to get a real
subscriber list (because we\'re on the MIT realm). | alternate version of get _ subscriber _ emails that takes a stream object only , and simply returns an empty list if unable to get a real subscriber list . | Question:
What does this function do?
Code:
def maybe_get_subscriber_emails(stream, user_profile):
try:
subscribers = get_subscriber_emails(stream, requesting_user=user_profile)
except JsonableError:
subscribers = []
return subscribers
|
null | null | null | What does this function do? | def parse(url):
config = {}
url = urlparse.urlparse(url)
config.update({'NAME': url.path[1:], 'USER': url.username, 'PASSWORD': url.password, 'HOST': url.hostname, 'PORT': url.port})
if (url.scheme == 'postgres'):
config['ENGINE'] = 'django.db.backends.postgresql_psycopg2'
if (url.scheme == 'mysql'):
config['E... | null | null | null | Parses a database URL. | pcsd | def parse url config = {} url = urlparse urlparse url config update {'NAME' url path[1 ] 'USER' url username 'PASSWORD' url password 'HOST' url hostname 'PORT' url port} if url scheme == 'postgres' config['ENGINE'] = 'django db backends postgresql psycopg2' if url scheme == 'mysql' config['ENGINE'] = 'django db backend... | 17794 | def parse(url):
config = {}
url = urlparse.urlparse(url)
config.update({'NAME': url.path[1:], 'USER': url.username, 'PASSWORD': url.password, 'HOST': url.hostname, 'PORT': url.port})
if (url.scheme == 'postgres'):
config['ENGINE'] = 'django.db.backends.postgresql_psycopg2'
if (url.scheme == 'mysql'):
config['E... | Parses a database URL. | parses a database url . | Question:
What does this function do?
Code:
def parse(url):
config = {}
url = urlparse.urlparse(url)
config.update({'NAME': url.path[1:], 'USER': url.username, 'PASSWORD': url.password, 'HOST': url.hostname, 'PORT': url.port})
if (url.scheme == 'postgres'):
config['ENGINE'] = 'django.db.backends.postgresql_psy... |
null | null | null | What does this function do? | def read_properties_core(xml_source):
properties = DocumentProperties()
root = fromstring(xml_source)
creator_node = root.find(QName(NAMESPACES['dc'], 'creator').text)
if (creator_node is not None):
properties.creator = creator_node.text
else:
properties.creator = ''
last_modified_by_node = root.find(QName(NA... | null | null | null | Read assorted file properties. | pcsd | def read properties core xml source properties = Document Properties root = fromstring xml source creator node = root find Q Name NAMESPACES['dc'] 'creator' text if creator node is not None properties creator = creator node text else properties creator = '' last modified by node = root find Q Name NAMESPACES['cp'] 'las... | 17797 | def read_properties_core(xml_source):
properties = DocumentProperties()
root = fromstring(xml_source)
creator_node = root.find(QName(NAMESPACES['dc'], 'creator').text)
if (creator_node is not None):
properties.creator = creator_node.text
else:
properties.creator = ''
last_modified_by_node = root.find(QName(NA... | Read assorted file properties. | read assorted file properties . | Question:
What does this function do?
Code:
def read_properties_core(xml_source):
properties = DocumentProperties()
root = fromstring(xml_source)
creator_node = root.find(QName(NAMESPACES['dc'], 'creator').text)
if (creator_node is not None):
properties.creator = creator_node.text
else:
properties.creator =... |
null | null | null | What does this function do? | def add_to_recent_scan(name, md5, url):
try:
db_obj = RecentScansDB.objects.filter(MD5=md5)
if (not db_obj.exists()):
new_db_obj = RecentScansDB(NAME=name, MD5=md5, URL=url, TS=timezone.now())
new_db_obj.save()
except:
PrintException('[ERROR] Adding Scan URL to Database')
| null | null | null | Add Entry to Database under Recent Scan | pcsd | def add to recent scan name md5 url try db obj = Recent Scans DB objects filter MD5=md5 if not db obj exists new db obj = Recent Scans DB NAME=name MD5=md5 URL=url TS=timezone now new db obj save except Print Exception '[ERROR] Adding Scan URL to Database' | 17800 | def add_to_recent_scan(name, md5, url):
try:
db_obj = RecentScansDB.objects.filter(MD5=md5)
if (not db_obj.exists()):
new_db_obj = RecentScansDB(NAME=name, MD5=md5, URL=url, TS=timezone.now())
new_db_obj.save()
except:
PrintException('[ERROR] Adding Scan URL to Database')
| Add Entry to Database under Recent Scan | add entry to database under recent scan | Question:
What does this function do?
Code:
def add_to_recent_scan(name, md5, url):
try:
db_obj = RecentScansDB.objects.filter(MD5=md5)
if (not db_obj.exists()):
new_db_obj = RecentScansDB(NAME=name, MD5=md5, URL=url, TS=timezone.now())
new_db_obj.save()
except:
PrintException('[ERROR] Adding Scan URL ... |
null | null | null | What does this function do? | def write_urls_index(app, exc):
inventory = os.path.join(app.builder.outdir, 'objects.inv')
objects = sphinx.ext.intersphinx.fetch_inventory(app, DOCS_URL, inventory)
with open(os.path.join(app.builder.outdir, 'shorturls.json'), 'w') as f:
json.dump(objects, f)
| null | null | null | Generate a JSON file to serve as an index for short-URL lookups | pcsd | def write urls index app exc inventory = os path join app builder outdir 'objects inv' objects = sphinx ext intersphinx fetch inventory app DOCS URL inventory with open os path join app builder outdir 'shorturls json' 'w' as f json dump objects f | 17801 | def write_urls_index(app, exc):
inventory = os.path.join(app.builder.outdir, 'objects.inv')
objects = sphinx.ext.intersphinx.fetch_inventory(app, DOCS_URL, inventory)
with open(os.path.join(app.builder.outdir, 'shorturls.json'), 'w') as f:
json.dump(objects, f)
| Generate a JSON file to serve as an index for short-URL lookups | generate a json file to serve as an index for short - url lookups | Question:
What does this function do?
Code:
def write_urls_index(app, exc):
inventory = os.path.join(app.builder.outdir, 'objects.inv')
objects = sphinx.ext.intersphinx.fetch_inventory(app, DOCS_URL, inventory)
with open(os.path.join(app.builder.outdir, 'shorturls.json'), 'w') as f:
json.dump(objects, f)
|
null | null | null | What does this function do? | def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[np.logical_not(state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
| null | null | null | Add the value found in Step 4 to every element of each covered row,
and subtract it from every element of each uncovered column.
Return to Step 4 without altering any stars, primes, or covered lines. | pcsd | def step6 state if np any state row uncovered and np any state col uncovered minval = np min state C[state row uncovered] axis=0 minval = np min minval[state col uncovered] state C[np logical not state row uncovered ] += minval state C[ state col uncovered] -= minval return step4 | 17818 | def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[np.logical_not(state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
| Add the value found in Step 4 to every element of each covered row,
and subtract it from every element of each uncovered column.
Return to Step 4 without altering any stars, primes, or covered lines. | add the value found in step 4 to every element of each covered row , and subtract it from every element of each uncovered column . | Question:
What does this function do?
Code:
def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[np.logical_not(state.row_uncovered)] += minval
state.C[:, state.col_unco... |
null | null | null | What does this function do? | @register(u'start-kbd-macro')
def start_kbd_macro(event):
event.cli.input_processor.start_macro()
| null | null | null | Begin saving the characters typed into the current keyboard macro. | pcsd | @register u'start-kbd-macro' def start kbd macro event event cli input processor start macro | 17820 | @register(u'start-kbd-macro')
def start_kbd_macro(event):
event.cli.input_processor.start_macro()
| Begin saving the characters typed into the current keyboard macro. | begin saving the characters typed into the current keyboard macro . | Question:
What does this function do?
Code:
@register(u'start-kbd-macro')
def start_kbd_macro(event):
event.cli.input_processor.start_macro()
|
null | null | null | What does this function do? | def calc_wedge_bounds(levels, level_width):
inners = (levels * level_width)
outers = (inners + level_width)
return (inners, outers)
| null | null | null | Calculate inner and outer radius bounds of the donut wedge based on levels. | pcsd | def calc wedge bounds levels level width inners = levels * level width outers = inners + level width return inners outers | 17823 | def calc_wedge_bounds(levels, level_width):
inners = (levels * level_width)
outers = (inners + level_width)
return (inners, outers)
| Calculate inner and outer radius bounds of the donut wedge based on levels. | calculate inner and outer radius bounds of the donut wedge based on levels . | Question:
What does this function do?
Code:
def calc_wedge_bounds(levels, level_width):
inners = (levels * level_width)
outers = (inners + level_width)
return (inners, outers)
|
null | null | null | What does this function do? | def getBusFreq():
if importCtypesFailed:
return False
mib = (ctypes.c_int * 2)(CTL_HW, HW_BUS_FREQ)
val = ctypes.c_int()
intSize = ctypes.c_int(ctypes.sizeof(val))
cocoa.sysctl(ctypes.byref(mib), 2, ctypes.byref(val), ctypes.byref(intSize), 0, 0)
return val.value
| null | null | null | Get the frequency of the system bus (HZ). | pcsd | def get Bus Freq if import Ctypes Failed return False mib = ctypes c int * 2 CTL HW HW BUS FREQ val = ctypes c int int Size = ctypes c int ctypes sizeof val cocoa sysctl ctypes byref mib 2 ctypes byref val ctypes byref int Size 0 0 return val value | 17828 | def getBusFreq():
if importCtypesFailed:
return False
mib = (ctypes.c_int * 2)(CTL_HW, HW_BUS_FREQ)
val = ctypes.c_int()
intSize = ctypes.c_int(ctypes.sizeof(val))
cocoa.sysctl(ctypes.byref(mib), 2, ctypes.byref(val), ctypes.byref(intSize), 0, 0)
return val.value
| Get the frequency of the system bus (HZ). | get the frequency of the system bus . | Question:
What does this function do?
Code:
def getBusFreq():
if importCtypesFailed:
return False
mib = (ctypes.c_int * 2)(CTL_HW, HW_BUS_FREQ)
val = ctypes.c_int()
intSize = ctypes.c_int(ctypes.sizeof(val))
cocoa.sysctl(ctypes.byref(mib), 2, ctypes.byref(val), ctypes.byref(intSize), 0, 0)
return val.value
|
null | null | null | What does this function do? | def validate_settings():
try:
django_backend = [x for x in settings.TEMPLATES if (x['BACKEND'] == 'django.template.backends.django.DjangoTemplates')][0]
except IndexError:
raise ImproperlyConfigured("django CMS requires django.template.context_processors.request in 'django.template.backends.django.DjangoTemplates... | null | null | null | Check project settings file for required options | pcsd | def validate settings try django backend = [x for x in settings TEMPLATES if x['BACKEND'] == 'django template backends django Django Templates' ][0] except Index Error raise Improperly Configured "django CMS requires django template context processors request in 'django template backends django Django Templates' contex... | 17829 | def validate_settings():
try:
django_backend = [x for x in settings.TEMPLATES if (x['BACKEND'] == 'django.template.backends.django.DjangoTemplates')][0]
except IndexError:
raise ImproperlyConfigured("django CMS requires django.template.context_processors.request in 'django.template.backends.django.DjangoTemplates... | Check project settings file for required options | check project settings file for required options | Question:
What does this function do?
Code:
def validate_settings():
try:
django_backend = [x for x in settings.TEMPLATES if (x['BACKEND'] == 'django.template.backends.django.DjangoTemplates')][0]
except IndexError:
raise ImproperlyConfigured("django CMS requires django.template.context_processors.request in '... |
null | null | null | What does this function do? | def remove_instance_type_access(flavorid, projectid, ctxt=None):
if (ctxt is None):
ctxt = context.get_admin_context()
return db.instance_type_access_remove(ctxt, flavorid, projectid)
| null | null | null | Remove instance type access for project. | pcsd | def remove instance type access flavorid projectid ctxt=None if ctxt is None ctxt = context get admin context return db instance type access remove ctxt flavorid projectid | 17833 | def remove_instance_type_access(flavorid, projectid, ctxt=None):
if (ctxt is None):
ctxt = context.get_admin_context()
return db.instance_type_access_remove(ctxt, flavorid, projectid)
| Remove instance type access for project. | remove instance type access for project . | Question:
What does this function do?
Code:
def remove_instance_type_access(flavorid, projectid, ctxt=None):
if (ctxt is None):
ctxt = context.get_admin_context()
return db.instance_type_access_remove(ctxt, flavorid, projectid)
|
null | null | null | What does this function do? | def grouper(iterable, n, fillvalue=None):
args = ([iter(iterable)] * n)
return zip_longest(fillvalue=fillvalue, *args)
| null | null | null | Collect data into fixed-length chunks or blocks | pcsd | def grouper iterable n fillvalue=None args = [iter iterable ] * n return zip longest fillvalue=fillvalue *args | 17838 | def grouper(iterable, n, fillvalue=None):
args = ([iter(iterable)] * n)
return zip_longest(fillvalue=fillvalue, *args)
| Collect data into fixed-length chunks or blocks | collect data into fixed - length chunks or blocks | Question:
What does this function do?
Code:
def grouper(iterable, n, fillvalue=None):
args = ([iter(iterable)] * n)
return zip_longest(fillvalue=fillvalue, *args)
|
null | null | null | What does this function do? | def _get_default_context(request):
queues = Object.filter_by_request(request, TicketQueue.objects.filter(active=True, parent__isnull=True))
statuses = Object.filter_by_request(request, TicketStatus.objects)
try:
agent = request.user.profile.serviceagent_set.all()[0]
except Exception:
agent = None
massform = Ma... | null | null | null | Returns default context for all views as dict() | pcsd | def get default context request queues = Object filter by request request Ticket Queue objects filter active=True parent isnull=True statuses = Object filter by request request Ticket Status objects try agent = request user profile serviceagent set all [0] except Exception agent = None massform = Mass Action Form reque... | 17840 | def _get_default_context(request):
queues = Object.filter_by_request(request, TicketQueue.objects.filter(active=True, parent__isnull=True))
statuses = Object.filter_by_request(request, TicketStatus.objects)
try:
agent = request.user.profile.serviceagent_set.all()[0]
except Exception:
agent = None
massform = Ma... | Returns default context for all views as dict() | returns default context for all views as dict ( ) | Question:
What does this function do?
Code:
def _get_default_context(request):
queues = Object.filter_by_request(request, TicketQueue.objects.filter(active=True, parent__isnull=True))
statuses = Object.filter_by_request(request, TicketStatus.objects)
try:
agent = request.user.profile.serviceagent_set.all()[0]
... |
null | null | null | What does this function do? | def wrap_exception(notifier=None, publisher_id=None, event_type=None, level=None):
def inner(f):
def wrapped(self, context, *args, **kw):
try:
return f(self, context, *args, **kw)
except Exception as e:
with excutils.save_and_reraise_exception():
if notifier:
payload = dict(exception=e)
... | null | null | null | This decorator wraps a method to catch any exceptions that may
get thrown. It logs the exception as well as optionally sending
it to the notification system. | pcsd | def wrap exception notifier=None publisher id=None event type=None level=None def inner f def wrapped self context *args **kw try return f self context *args **kw except Exception as e with excutils save and reraise exception if notifier payload = dict exception=e call dict = safe utils getcallargs f *args **kw cleanse... | 17845 | def wrap_exception(notifier=None, publisher_id=None, event_type=None, level=None):
def inner(f):
def wrapped(self, context, *args, **kw):
try:
return f(self, context, *args, **kw)
except Exception as e:
with excutils.save_and_reraise_exception():
if notifier:
payload = dict(exception=e)
... | This decorator wraps a method to catch any exceptions that may
get thrown. It logs the exception as well as optionally sending
it to the notification system. | this decorator wraps a method to catch any exceptions that may get thrown . | Question:
What does this function do?
Code:
def wrap_exception(notifier=None, publisher_id=None, event_type=None, level=None):
def inner(f):
def wrapped(self, context, *args, **kw):
try:
return f(self, context, *args, **kw)
except Exception as e:
with excutils.save_and_reraise_exception():
if n... |
null | null | null | What does this function do? | def exception():
return sys.exc_info()[1]
| null | null | null | Return the current the exception instance currently being handled | pcsd | def exception return sys exc info [1] | 17849 | def exception():
return sys.exc_info()[1]
| Return the current the exception instance currently being handled | return the current the exception instance currently being handled | Question:
What does this function do?
Code:
def exception():
return sys.exc_info()[1]
|
null | null | null | What does this function do? | def backend():
return _BACKEND
| null | null | null | Publicly accessible method
for determining the current backend. | pcsd | def backend return BACKEND | 17851 | def backend():
return _BACKEND
| Publicly accessible method
for determining the current backend. | publicly accessible method for determining the current backend . | Question:
What does this function do?
Code:
def backend():
return _BACKEND
|
null | null | null | What does this function do? | def encode(lst):
encodeStream = BytesIO()
_i.transport = encodeStream
_i.sendEncoded(lst)
return encodeStream.getvalue()
| null | null | null | Encode a list s-expression. | pcsd | def encode lst encode Stream = Bytes IO i transport = encode Stream i send Encoded lst return encode Stream getvalue | 17852 | def encode(lst):
encodeStream = BytesIO()
_i.transport = encodeStream
_i.sendEncoded(lst)
return encodeStream.getvalue()
| Encode a list s-expression. | encode a list s - expression . | Question:
What does this function do?
Code:
def encode(lst):
encodeStream = BytesIO()
_i.transport = encodeStream
_i.sendEncoded(lst)
return encodeStream.getvalue()
|
null | null | null | What does this function do? | @control_command(args=[(u'max', int), (u'min', int)], signature=u'[max [min]]')
def autoscale(state, max=None, min=None):
autoscaler = state.consumer.controller.autoscaler
if autoscaler:
(max_, min_) = autoscaler.update(max, min)
return ok(u'autoscale now max={0} min={1}'.format(max_, min_))
raise ValueError(u'A... | null | null | null | Modify autoscale settings. | pcsd | @control command args=[ u'max' int u'min' int ] signature=u'[max [min]]' def autoscale state max=None min=None autoscaler = state consumer controller autoscaler if autoscaler max min = autoscaler update max min return ok u'autoscale now max={0} min={1}' format max min raise Value Error u'Autoscale not enabled' | 17860 | @control_command(args=[(u'max', int), (u'min', int)], signature=u'[max [min]]')
def autoscale(state, max=None, min=None):
autoscaler = state.consumer.controller.autoscaler
if autoscaler:
(max_, min_) = autoscaler.update(max, min)
return ok(u'autoscale now max={0} min={1}'.format(max_, min_))
raise ValueError(u'A... | Modify autoscale settings. | modify autoscale settings . | Question:
What does this function do?
Code:
@control_command(args=[(u'max', int), (u'min', int)], signature=u'[max [min]]')
def autoscale(state, max=None, min=None):
autoscaler = state.consumer.controller.autoscaler
if autoscaler:
(max_, min_) = autoscaler.update(max, min)
return ok(u'autoscale now max={0} min... |
null | null | null | What does this function do? | def convert_alpha_characters_in_number(number):
return _normalize_helper(number, _ALPHA_PHONE_MAPPINGS, False)
| null | null | null | Convert alpha chars in a number to their respective digits on a keypad,
but retains existing formatting. | pcsd | def convert alpha characters in number number return normalize helper number ALPHA PHONE MAPPINGS False | 17862 | def convert_alpha_characters_in_number(number):
return _normalize_helper(number, _ALPHA_PHONE_MAPPINGS, False)
| Convert alpha chars in a number to their respective digits on a keypad,
but retains existing formatting. | convert alpha chars in a number to their respective digits on a keypad , but retains existing formatting . | Question:
What does this function do?
Code:
def convert_alpha_characters_in_number(number):
return _normalize_helper(number, _ALPHA_PHONE_MAPPINGS, False)
|
null | null | null | What does this function do? | def process_destructor(pid, exitcode):
signals.worker_process_shutdown.send(sender=None, pid=pid, exitcode=exitcode)
| null | null | null | Pool child process destructor.
Dispatch the :signal:`worker_process_shutdown` signal. | pcsd | def process destructor pid exitcode signals worker process shutdown send sender=None pid=pid exitcode=exitcode | 17873 | def process_destructor(pid, exitcode):
signals.worker_process_shutdown.send(sender=None, pid=pid, exitcode=exitcode)
| Pool child process destructor.
Dispatch the :signal:`worker_process_shutdown` signal. | pool child process destructor . | Question:
What does this function do?
Code:
def process_destructor(pid, exitcode):
signals.worker_process_shutdown.send(sender=None, pid=pid, exitcode=exitcode)
|
null | null | null | What does this function do? | def _get_certificate_obj(cert):
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
| null | null | null | Returns a certificate object based on PEM text. | pcsd | def get certificate obj cert if isinstance cert M2Crypto X509 X509 return cert text = text or file cert text = get pem entry text pem type='CERTIFICATE' return M2Crypto X509 load cert string text | 17876 | def _get_certificate_obj(cert):
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
| Returns a certificate object based on PEM text. | returns a certificate object based on pem text . | Question:
What does this function do?
Code:
def _get_certificate_obj(cert):
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
|
null | null | null | What does this function do? | def StringSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
local_len = len
assert (not is_packed)
if is_repeated:
def RepeatedFieldSize(value):
result = (tag_size * len(value))
for element in value:
l = local_len(element.encode('utf-8'))
... | null | null | null | Returns a sizer for a string field. | pcsd | def String Sizer field number is repeated is packed tag size = Tag Size field number local Varint Size = Varint Size local len = len assert not is packed if is repeated def Repeated Field Size value result = tag size * len value for element in value l = local len element encode 'utf-8' result += local Varint Size l + l... | 17877 | def StringSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
local_len = len
assert (not is_packed)
if is_repeated:
def RepeatedFieldSize(value):
result = (tag_size * len(value))
for element in value:
l = local_len(element.encode('utf-8'))
... | Returns a sizer for a string field. | returns a sizer for a string field . | Question:
What does this function do?
Code:
def StringSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
local_len = len
assert (not is_packed)
if is_repeated:
def RepeatedFieldSize(value):
result = (tag_size * len(value))
for element in value:
... |
null | null | null | What does this function do? | def _init_mac():
g = {}
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
import MacOS
if (not hasattr(MacOS, 'runtimemodel')):
g['SO'] = '.ppc.slb'
else:
g['SO'] = ('.%s.slb' % Mac... | null | null | null | Initialize the module as appropriate for Macintosh systems | pcsd | def init mac g = {} g['LIBDEST'] = get python lib plat specific=0 standard lib=1 g['BINLIBDEST'] = get python lib plat specific=1 standard lib=1 g['INCLUDEPY'] = get python inc plat specific=0 import Mac OS if not hasattr Mac OS 'runtimemodel' g['SO'] = ' ppc slb' else g['SO'] = ' %s slb' % Mac OS runtimemodel g['insta... | 17879 | def _init_mac():
g = {}
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
import MacOS
if (not hasattr(MacOS, 'runtimemodel')):
g['SO'] = '.ppc.slb'
else:
g['SO'] = ('.%s.slb' % Mac... | Initialize the module as appropriate for Macintosh systems | initialize the module as appropriate for macintosh systems | Question:
What does this function do?
Code:
def _init_mac():
g = {}
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
import MacOS
if (not hasattr(MacOS, 'runtimemodel')):
g['SO'] =... |
null | null | null | What does this function do? | def runningAsAdmin():
isAdmin = None
if (PLATFORM in ('posix', 'mac')):
_ = os.geteuid()
isAdmin = (isinstance(_, (int, float, long)) and (_ == 0))
elif IS_WIN:
import ctypes
_ = ctypes.windll.shell32.IsUserAnAdmin()
isAdmin = (isinstance(_, (int, float, long)) and (_ == 1))
else:
errMsg = 'sqlmap is no... | null | null | null | Returns True if the current process is run under admin privileges | pcsd | def running As Admin is Admin = None if PLATFORM in 'posix' 'mac' = os geteuid is Admin = isinstance int float long and == 0 elif IS WIN import ctypes = ctypes windll shell32 Is User An Admin is Admin = isinstance int float long and == 1 else err Msg = 'sqlmap is not able to check if you are running it ' err Msg += 'as... | 17883 | def runningAsAdmin():
isAdmin = None
if (PLATFORM in ('posix', 'mac')):
_ = os.geteuid()
isAdmin = (isinstance(_, (int, float, long)) and (_ == 0))
elif IS_WIN:
import ctypes
_ = ctypes.windll.shell32.IsUserAnAdmin()
isAdmin = (isinstance(_, (int, float, long)) and (_ == 1))
else:
errMsg = 'sqlmap is no... | Returns True if the current process is run under admin privileges | returns true if the current process is run under admin privileges | Question:
What does this function do?
Code:
def runningAsAdmin():
isAdmin = None
if (PLATFORM in ('posix', 'mac')):
_ = os.geteuid()
isAdmin = (isinstance(_, (int, float, long)) and (_ == 0))
elif IS_WIN:
import ctypes
_ = ctypes.windll.shell32.IsUserAnAdmin()
isAdmin = (isinstance(_, (int, float, long)... |
null | null | null | What does this function do? | def _check_params(X, metric, p, metric_params):
params = zip(['metric', 'p', 'metric_params'], [metric, p, metric_params])
est_params = X.get_params()
for (param_name, func_param) in params:
if (func_param != est_params[param_name]):
raise ValueError(('Got %s for %s, while the estimator has %s for the same para... | null | null | null | Check the validity of the input parameters | pcsd | def check params X metric p metric params params = zip ['metric' 'p' 'metric params'] [metric p metric params] est params = X get params for param name func param in params if func param != est params[param name] raise Value Error 'Got %s for %s while the estimator has %s for the same parameter ' % func param param nam... | 17885 | def _check_params(X, metric, p, metric_params):
params = zip(['metric', 'p', 'metric_params'], [metric, p, metric_params])
est_params = X.get_params()
for (param_name, func_param) in params:
if (func_param != est_params[param_name]):
raise ValueError(('Got %s for %s, while the estimator has %s for the same para... | Check the validity of the input parameters | check the validity of the input parameters | Question:
What does this function do?
Code:
def _check_params(X, metric, p, metric_params):
params = zip(['metric', 'p', 'metric_params'], [metric, p, metric_params])
est_params = X.get_params()
for (param_name, func_param) in params:
if (func_param != est_params[param_name]):
raise ValueError(('Got %s for %... |
null | null | null | What does this function do? | def get_current_users():
current_users = {}
for session in Session.objects.all():
try:
uid = session.get_decoded().get(django.contrib.auth.SESSION_KEY)
except SuspiciousOperation:
uid = None
if (uid is not None):
try:
userobj = User.objects.get(pk=uid)
current_users[userobj] = last_access_map.g... | null | null | null | Return dictionary of User objects and
a dictionary of the user\'s IP address and last access time | pcsd | def get current users current users = {} for session in Session objects all try uid = session get decoded get django contrib auth SESSION KEY except Suspicious Operation uid = None if uid is not None try userobj = User objects get pk=uid current users[userobj] = last access map get userobj username {} except User Does ... | 17887 | def get_current_users():
current_users = {}
for session in Session.objects.all():
try:
uid = session.get_decoded().get(django.contrib.auth.SESSION_KEY)
except SuspiciousOperation:
uid = None
if (uid is not None):
try:
userobj = User.objects.get(pk=uid)
current_users[userobj] = last_access_map.g... | Return dictionary of User objects and
a dictionary of the user\'s IP address and last access time | return dictionary of user objects and a dictionary of the users ip address and last access time | Question:
What does this function do?
Code:
def get_current_users():
current_users = {}
for session in Session.objects.all():
try:
uid = session.get_decoded().get(django.contrib.auth.SESSION_KEY)
except SuspiciousOperation:
uid = None
if (uid is not None):
try:
userobj = User.objects.get(pk=uid)... |
null | null | null | What does this function do? | def get_conf_file_name(cfg_root, uuid, cfg_file, ensure_conf_dir=False):
conf_base = _get_conf_base(cfg_root, uuid, ensure_conf_dir)
return ('%s.%s' % (conf_base, cfg_file))
| null | null | null | Returns the file name for a given kind of config file. | pcsd | def get conf file name cfg root uuid cfg file ensure conf dir=False conf base = get conf base cfg root uuid ensure conf dir return '%s %s' % conf base cfg file | 17901 | def get_conf_file_name(cfg_root, uuid, cfg_file, ensure_conf_dir=False):
conf_base = _get_conf_base(cfg_root, uuid, ensure_conf_dir)
return ('%s.%s' % (conf_base, cfg_file))
| Returns the file name for a given kind of config file. | returns the file name for a given kind of config file . | Question:
What does this function do?
Code:
def get_conf_file_name(cfg_root, uuid, cfg_file, ensure_conf_dir=False):
conf_base = _get_conf_base(cfg_root, uuid, ensure_conf_dir)
return ('%s.%s' % (conf_base, cfg_file))
|
null | null | null | What does this function do? | def _safe_str(obj):
try:
return str(obj)
except Exception:
return object.__str__(obj)
| null | null | null | Helper for assert_* ports | pcsd | def safe str obj try return str obj except Exception return object str obj | 17902 | def _safe_str(obj):
try:
return str(obj)
except Exception:
return object.__str__(obj)
| Helper for assert_* ports | helper for assert _ * ports | Question:
What does this function do?
Code:
def _safe_str(obj):
try:
return str(obj)
except Exception:
return object.__str__(obj)
|
null | null | null | What does this function do? | def debug(msg):
if DEBUG:
sys.stderr.write((('DEBUG: ' + msg) + '\n'))
sys.stderr.flush()
| null | null | null | Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag. | pcsd | def debug msg if DEBUG sys stderr write 'DEBUG ' + msg + ' ' sys stderr flush | 17903 | def debug(msg):
if DEBUG:
sys.stderr.write((('DEBUG: ' + msg) + '\n'))
sys.stderr.flush()
| Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag. | displays debug messages to stderr only if the python interpreter was invoked with the - o flag . | Question:
What does this function do?
Code:
def debug(msg):
if DEBUG:
sys.stderr.write((('DEBUG: ' + msg) + '\n'))
sys.stderr.flush()
|
null | null | null | What does this function do? | def _try_lookup(table, value, default=''):
try:
string = table[value]
except KeyError:
string = default
return string
| null | null | null | try to get a string from the lookup table, return "" instead of key
error | pcsd | def try lookup table value default='' try string = table[value] except Key Error string = default return string | 17907 | def _try_lookup(table, value, default=''):
try:
string = table[value]
except KeyError:
string = default
return string
| try to get a string from the lookup table, return "" instead of key
error | try to get a string from the lookup table , return " " instead of key error | Question:
What does this function do?
Code:
def _try_lookup(table, value, default=''):
try:
string = table[value]
except KeyError:
string = default
return string
|
null | null | null | What does this function do? | def returner(ret):
job_fun = ret['fun']
job_fun_escaped = job_fun.replace('.', '_')
job_id = ret['jid']
job_retcode = ret.get('retcode', 1)
job_success = (True if (not job_retcode) else False)
options = _get_options(ret)
if (job_fun in options['functions_blacklist']):
log.info("Won't push new data to Elasticse... | null | null | null | Process the return from Salt | pcsd | def returner ret job fun = ret['fun'] job fun escaped = job fun replace ' ' ' ' job id = ret['jid'] job retcode = ret get 'retcode' 1 job success = True if not job retcode else False options = get options ret if job fun in options['functions blacklist'] log info "Won't push new data to Elasticsearch job with jid={0} an... | 17910 | def returner(ret):
job_fun = ret['fun']
job_fun_escaped = job_fun.replace('.', '_')
job_id = ret['jid']
job_retcode = ret.get('retcode', 1)
job_success = (True if (not job_retcode) else False)
options = _get_options(ret)
if (job_fun in options['functions_blacklist']):
log.info("Won't push new data to Elasticse... | Process the return from Salt | process the return from salt | Question:
What does this function do?
Code:
def returner(ret):
job_fun = ret['fun']
job_fun_escaped = job_fun.replace('.', '_')
job_id = ret['jid']
job_retcode = ret.get('retcode', 1)
job_success = (True if (not job_retcode) else False)
options = _get_options(ret)
if (job_fun in options['functions_blacklist']... |
null | null | null | What does this function do? | def apply_operators(obj, ops, op):
res = obj
for o in reversed(ops):
res = o.apply(res, op)
return res
| null | null | null | Apply the list of operators ``ops`` to object ``obj``, substituting
``op`` for the generator. | pcsd | def apply operators obj ops op res = obj for o in reversed ops res = o apply res op return res | 17919 | def apply_operators(obj, ops, op):
res = obj
for o in reversed(ops):
res = o.apply(res, op)
return res
| Apply the list of operators ``ops`` to object ``obj``, substituting
``op`` for the generator. | apply the list of operators ops to object obj , substituting op for the generator . | Question:
What does this function do?
Code:
def apply_operators(obj, ops, op):
res = obj
for o in reversed(ops):
res = o.apply(res, op)
return res
|
null | null | null | What does this function do? | def get_manager_from_config(admin_password=None, rdbms_type=None):
sect = 'AUTOTEST_WEB'
name = settings.settings.get_value(sect, 'database')
user = settings.settings.get_value(sect, 'user')
password = settings.settings.get_value(sect, 'password')
host = settings.settings.get_value(sect, 'host')
if (rdbms_type is... | null | null | null | Returns a manager instance from the information on the configuration file | pcsd | def get manager from config admin password=None rdbms type=None sect = 'AUTOTEST WEB' name = settings settings get value sect 'database' user = settings settings get value sect 'user' password = settings settings get value sect 'password' host = settings settings get value sect 'host' if rdbms type is None rdbms type =... | 17929 | def get_manager_from_config(admin_password=None, rdbms_type=None):
sect = 'AUTOTEST_WEB'
name = settings.settings.get_value(sect, 'database')
user = settings.settings.get_value(sect, 'user')
password = settings.settings.get_value(sect, 'password')
host = settings.settings.get_value(sect, 'host')
if (rdbms_type is... | Returns a manager instance from the information on the configuration file | returns a manager instance from the information on the configuration file | Question:
What does this function do?
Code:
def get_manager_from_config(admin_password=None, rdbms_type=None):
sect = 'AUTOTEST_WEB'
name = settings.settings.get_value(sect, 'database')
user = settings.settings.get_value(sect, 'user')
password = settings.settings.get_value(sect, 'password')
host = settings.sett... |
null | null | null | What does this function do? | def _coeffs_generator(n):
for coeffs in variations([1, (-1)], n, repetition=True):
(yield list(coeffs))
| null | null | null | Generate coefficients for `primitive_element()`. | pcsd | def coeffs generator n for coeffs in variations [1 -1 ] n repetition=True yield list coeffs | 17930 | def _coeffs_generator(n):
for coeffs in variations([1, (-1)], n, repetition=True):
(yield list(coeffs))
| Generate coefficients for `primitive_element()`. | generate coefficients for primitive _ element ( ) . | Question:
What does this function do?
Code:
def _coeffs_generator(n):
for coeffs in variations([1, (-1)], n, repetition=True):
(yield list(coeffs))
|
null | null | null | What does this function do? | def extract_description(texts):
document = ''
for text in texts:
try:
document += text['description']
except KeyError as e:
print ('KeyError: %s\n%s' % (e, text))
return document
| null | null | null | Returns all the text in text annotations as a single string | pcsd | def extract description texts document = '' for text in texts try document += text['description'] except Key Error as e print 'Key Error %s %s' % e text return document | 17943 | def extract_description(texts):
document = ''
for text in texts:
try:
document += text['description']
except KeyError as e:
print ('KeyError: %s\n%s' % (e, text))
return document
| Returns all the text in text annotations as a single string | returns all the text in text annotations as a single string | Question:
What does this function do?
Code:
def extract_description(texts):
document = ''
for text in texts:
try:
document += text['description']
except KeyError as e:
print ('KeyError: %s\n%s' % (e, text))
return document
|
null | null | null | What does this function do? | def ec2_connect(module):
(region, ec2_url, boto_params) = get_aws_connection_info(module)
if region:
try:
ec2 = connect_to_aws(boto.ec2, region, **boto_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
elif ec2_url:
try:
ec2 = boto.connect_ec2_endpo... | null | null | null | Return an ec2 connection | pcsd | def ec2 connect module region ec2 url boto params = get aws connection info module if region try ec2 = connect to aws boto ec2 region **boto params except boto exception No Auth Handler Found Ansible AWS Error as e module fail json msg=str e elif ec2 url try ec2 = boto connect ec2 endpoint ec2 url **boto params except ... | 17948 | def ec2_connect(module):
(region, ec2_url, boto_params) = get_aws_connection_info(module)
if region:
try:
ec2 = connect_to_aws(boto.ec2, region, **boto_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
elif ec2_url:
try:
ec2 = boto.connect_ec2_endpo... | Return an ec2 connection | return an ec2 connection | Question:
What does this function do?
Code:
def ec2_connect(module):
(region, ec2_url, boto_params) = get_aws_connection_info(module)
if region:
try:
ec2 = connect_to_aws(boto.ec2, region, **boto_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
elif ... |
null | null | null | What does this function do? | def encode_basestring(s, _PY3=PY3, _q=u('"')):
if _PY3:
if isinstance(s, binary_type):
s = s.decode('utf-8')
elif (isinstance(s, str) and (HAS_UTF8.search(s) is not None)):
s = s.decode('utf-8')
def replace(match):
return ESCAPE_DCT[match.group(0)]
return ((_q + ESCAPE.sub(replace, s)) + _q)
| null | null | null | Return a JSON representation of a Python string | pcsd | def encode basestring s PY3=PY3 q=u '"' if PY3 if isinstance s binary type s = s decode 'utf-8' elif isinstance s str and HAS UTF8 search s is not None s = s decode 'utf-8' def replace match return ESCAPE DCT[match group 0 ] return q + ESCAPE sub replace s + q | 17949 | def encode_basestring(s, _PY3=PY3, _q=u('"')):
if _PY3:
if isinstance(s, binary_type):
s = s.decode('utf-8')
elif (isinstance(s, str) and (HAS_UTF8.search(s) is not None)):
s = s.decode('utf-8')
def replace(match):
return ESCAPE_DCT[match.group(0)]
return ((_q + ESCAPE.sub(replace, s)) + _q)
| Return a JSON representation of a Python string | return a json representation of a python string | Question:
What does this function do?
Code:
def encode_basestring(s, _PY3=PY3, _q=u('"')):
if _PY3:
if isinstance(s, binary_type):
s = s.decode('utf-8')
elif (isinstance(s, str) and (HAS_UTF8.search(s) is not None)):
s = s.decode('utf-8')
def replace(match):
return ESCAPE_DCT[match.group(0)]
return ((_q... |
null | null | null | What does this function do? | def _make_model_field(label, initial, choices, multi=True):
if multi:
field = forms.models.ModelMultipleChoiceField(choices, required=False)
field.initial_objs = initial
field.initial = [obj.pk for obj in initial]
field.label = label
else:
field = forms.models.ModelChoiceField(choices, required=False)
fie... | null | null | null | Creates multiple choice field with given query object as choices. | pcsd | def make model field label initial choices multi=True if multi field = forms models Model Multiple Choice Field choices required=False field initial objs = initial field initial = [obj pk for obj in initial] field label = label else field = forms models Model Choice Field choices required=False field initial obj = init... | 17950 | def _make_model_field(label, initial, choices, multi=True):
if multi:
field = forms.models.ModelMultipleChoiceField(choices, required=False)
field.initial_objs = initial
field.initial = [obj.pk for obj in initial]
field.label = label
else:
field = forms.models.ModelChoiceField(choices, required=False)
fie... | Creates multiple choice field with given query object as choices. | creates multiple choice field with given query object as choices . | Question:
What does this function do?
Code:
def _make_model_field(label, initial, choices, multi=True):
if multi:
field = forms.models.ModelMultipleChoiceField(choices, required=False)
field.initial_objs = initial
field.initial = [obj.pk for obj in initial]
field.label = label
else:
field = forms.models.... |
null | null | null | What does this function do? | def CDLEVENINGDOJISTAR(barDs, count, penetration=(-4e+37)):
return call_talib_with_ohlc(barDs, count, talib.CDLEVENINGDOJISTAR, penetration)
| null | null | null | Evening Doji Star | pcsd | def CDLEVENINGDOJISTAR bar Ds count penetration= -4e+37 return call talib with ohlc bar Ds count talib CDLEVENINGDOJISTAR penetration | 17951 | def CDLEVENINGDOJISTAR(barDs, count, penetration=(-4e+37)):
return call_talib_with_ohlc(barDs, count, talib.CDLEVENINGDOJISTAR, penetration)
| Evening Doji Star | evening doji star | Question:
What does this function do?
Code:
def CDLEVENINGDOJISTAR(barDs, count, penetration=(-4e+37)):
return call_talib_with_ohlc(barDs, count, talib.CDLEVENINGDOJISTAR, penetration)
|
null | null | null | What does this function do? | @pytest.mark.parametrize('parallel', [True, False])
def test_csv_comment_default(parallel, read_csv):
text = 'a,b,c\n#1,2,3\n4,5,6'
table = read_csv(text, parallel=parallel)
expected = Table([['#1', '4'], [2, 5], [3, 6]], names=('a', 'b', 'c'))
assert_table_equal(table, expected)
| null | null | null | Unless the comment parameter is specified, the CSV reader should
not treat any lines as comments. | pcsd | @pytest mark parametrize 'parallel' [True False] def test csv comment default parallel read csv text = 'a b c #1 2 3 4 5 6' table = read csv text parallel=parallel expected = Table [['#1' '4'] [2 5] [3 6]] names= 'a' 'b' 'c' assert table equal table expected | 17952 | @pytest.mark.parametrize('parallel', [True, False])
def test_csv_comment_default(parallel, read_csv):
text = 'a,b,c\n#1,2,3\n4,5,6'
table = read_csv(text, parallel=parallel)
expected = Table([['#1', '4'], [2, 5], [3, 6]], names=('a', 'b', 'c'))
assert_table_equal(table, expected)
| Unless the comment parameter is specified, the CSV reader should
not treat any lines as comments. | unless the comment parameter is specified , the csv reader should not treat any lines as comments . | Question:
What does this function do?
Code:
@pytest.mark.parametrize('parallel', [True, False])
def test_csv_comment_default(parallel, read_csv):
text = 'a,b,c\n#1,2,3\n4,5,6'
table = read_csv(text, parallel=parallel)
expected = Table([['#1', '4'], [2, 5], [3, 6]], names=('a', 'b', 'c'))
assert_table_equal(table... |
null | null | null | What does this function do? | def send_command(remote_conn, cmd):
cmd = cmd.rstrip()
remote_conn.write((cmd + '\n'))
time.sleep(1)
return remote_conn.read_very_eager()
| null | null | null | Send a command down the telnet channel. | pcsd | def send command remote conn cmd cmd = cmd rstrip remote conn write cmd + ' ' time sleep 1 return remote conn read very eager | 17957 | def send_command(remote_conn, cmd):
cmd = cmd.rstrip()
remote_conn.write((cmd + '\n'))
time.sleep(1)
return remote_conn.read_very_eager()
| Send a command down the telnet channel. | send a command down the telnet channel . | Question:
What does this function do?
Code:
def send_command(remote_conn, cmd):
cmd = cmd.rstrip()
remote_conn.write((cmd + '\n'))
time.sleep(1)
return remote_conn.read_very_eager()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.