id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1 value | is_duplicated bool 2 classes |
|---|---|---|---|---|---|
41,725 | def _find_image_bounding_boxes(filenames, image_to_bboxes):
num_image_bbox = 0
bboxes = []
for f in filenames:
basename = os.path.basename(f)
if (basename in image_to_bboxes):
bboxes.append(image_to_bboxes[basename])
num_image_bbox += 1
else:
bboxes.append([])
print(('Found %d images with bboxes out of %d images' % (num_image_bbox, len(filenames))))
return bboxes
| [
"def",
"_find_image_bounding_boxes",
"(",
"filenames",
",",
"image_to_bboxes",
")",
":",
"num_image_bbox",
"=",
"0",
"bboxes",
"=",
"[",
"]",
"for",
"f",
"in",
"filenames",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
"if",
"(",
"basename",
"in",
"image_to_bboxes",
")",
":",
"bboxes",
".",
"append",
"(",
"image_to_bboxes",
"[",
"basename",
"]",
")",
"num_image_bbox",
"+=",
"1",
"else",
":",
"bboxes",
".",
"append",
"(",
"[",
"]",
")",
"print",
"(",
"(",
"'Found %d images with bboxes out of %d images'",
"%",
"(",
"num_image_bbox",
",",
"len",
"(",
"filenames",
")",
")",
")",
")",
"return",
"bboxes"
] | find the bounding boxes for a given image file . | train | true |
41,726 | def open_resource(name):
name_parts = name.lstrip('/').split('/')
if (os.path.pardir in name_parts):
raise ValueError(('Bad path segment: %r' % os.path.pardir))
cache_key = ('pytz.zoneinfo.%s.%s' % (pytz.OLSON_VERSION, name))
zonedata = memcache.get(cache_key)
if (zonedata is None):
zonedata = get_zoneinfo().read(('zoneinfo/' + '/'.join(name_parts)))
memcache.add(cache_key, zonedata)
logging.info(('Added timezone to memcache: %s' % cache_key))
else:
logging.info(('Loaded timezone from memcache: %s' % cache_key))
return StringIO(zonedata)
| [
"def",
"open_resource",
"(",
"name",
")",
":",
"name_parts",
"=",
"name",
".",
"lstrip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"(",
"os",
".",
"path",
".",
"pardir",
"in",
"name_parts",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Bad path segment: %r'",
"%",
"os",
".",
"path",
".",
"pardir",
")",
")",
"cache_key",
"=",
"(",
"'pytz.zoneinfo.%s.%s'",
"%",
"(",
"pytz",
".",
"OLSON_VERSION",
",",
"name",
")",
")",
"zonedata",
"=",
"memcache",
".",
"get",
"(",
"cache_key",
")",
"if",
"(",
"zonedata",
"is",
"None",
")",
":",
"zonedata",
"=",
"get_zoneinfo",
"(",
")",
".",
"read",
"(",
"(",
"'zoneinfo/'",
"+",
"'/'",
".",
"join",
"(",
"name_parts",
")",
")",
")",
"memcache",
".",
"add",
"(",
"cache_key",
",",
"zonedata",
")",
"logging",
".",
"info",
"(",
"(",
"'Added timezone to memcache: %s'",
"%",
"cache_key",
")",
")",
"else",
":",
"logging",
".",
"info",
"(",
"(",
"'Loaded timezone from memcache: %s'",
"%",
"cache_key",
")",
")",
"return",
"StringIO",
"(",
"zonedata",
")"
] | open a resource from the zoneinfo subdir for reading . | train | false |
41,727 | def check_config_h():
from distutils import sysconfig
import string
if (string.find(sys.version, 'GCC') >= 0):
return (CONFIG_H_OK, "sys.version mentions 'GCC'")
fn = sysconfig.get_config_h_filename()
try:
f = open(fn)
s = f.read()
f.close()
except IOError as exc:
return (CONFIG_H_UNCERTAIN, ("couldn't read '%s': %s" % (fn, exc.strerror)))
else:
if (string.find(s, '__GNUC__') >= 0):
return (CONFIG_H_OK, ("'%s' mentions '__GNUC__'" % fn))
else:
return (CONFIG_H_NOTOK, ("'%s' does not mention '__GNUC__'" % fn))
| [
"def",
"check_config_h",
"(",
")",
":",
"from",
"distutils",
"import",
"sysconfig",
"import",
"string",
"if",
"(",
"string",
".",
"find",
"(",
"sys",
".",
"version",
",",
"'GCC'",
")",
">=",
"0",
")",
":",
"return",
"(",
"CONFIG_H_OK",
",",
"\"sys.version mentions 'GCC'\"",
")",
"fn",
"=",
"sysconfig",
".",
"get_config_h_filename",
"(",
")",
"try",
":",
"f",
"=",
"open",
"(",
"fn",
")",
"s",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"except",
"IOError",
"as",
"exc",
":",
"return",
"(",
"CONFIG_H_UNCERTAIN",
",",
"(",
"\"couldn't read '%s': %s\"",
"%",
"(",
"fn",
",",
"exc",
".",
"strerror",
")",
")",
")",
"else",
":",
"if",
"(",
"string",
".",
"find",
"(",
"s",
",",
"'__GNUC__'",
")",
">=",
"0",
")",
":",
"return",
"(",
"CONFIG_H_OK",
",",
"(",
"\"'%s' mentions '__GNUC__'\"",
"%",
"fn",
")",
")",
"else",
":",
"return",
"(",
"CONFIG_H_NOTOK",
",",
"(",
"\"'%s' does not mention '__GNUC__'\"",
"%",
"fn",
")",
")"
] | check if the current python installation appears amenable to building extensions with gcc . | train | false |
41,729 | def SetLogPrefix(prefix):
formatter = logging.Formatter((str(prefix) + ' [%(filename)s:%(lineno)d] %(levelname)s %(message)s'))
logging._acquireLock()
try:
for handler in logging._handlerList:
if isinstance(handler, weakref.ref):
handler = handler()
if handler:
handler.setFormatter(formatter)
finally:
logging._releaseLock()
| [
"def",
"SetLogPrefix",
"(",
"prefix",
")",
":",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"(",
"str",
"(",
"prefix",
")",
"+",
"' [%(filename)s:%(lineno)d] %(levelname)s %(message)s'",
")",
")",
"logging",
".",
"_acquireLock",
"(",
")",
"try",
":",
"for",
"handler",
"in",
"logging",
".",
"_handlerList",
":",
"if",
"isinstance",
"(",
"handler",
",",
"weakref",
".",
"ref",
")",
":",
"handler",
"=",
"handler",
"(",
")",
"if",
"handler",
":",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"finally",
":",
"logging",
".",
"_releaseLock",
"(",
")"
] | adds a prefix to the log handler to identify the process . | train | false |
41,732 | @pytest.mark.skipif((not os.getenv('TEST_READ_HUGE_FILE')), reason='Environment variable TEST_READ_HUGE_FILE must be defined to run this test')
def test_read_big_table(tmpdir):
NB_ROWS = 250000
NB_COLS = 500
filename = str(tmpdir.join('big_table.csv'))
print 'Creating a {} rows table ({} columns).'.format(NB_ROWS, NB_COLS)
data = np.random.random(NB_ROWS)
t = Table(data=([data] * NB_COLS), names=[str(i) for i in range(NB_COLS)])
data = None
print 'Saving the table to {}'.format(filename)
t.write(filename, format='ascii.csv', overwrite=True)
t = None
print 'Counting the number of lines in the csv, it should be {} + 1 (header).'.format(NB_ROWS)
assert (sum((1 for line in open(filename))) == (NB_ROWS + 1))
print 'Reading the file with astropy.'
t = Table.read(filename, format='ascii.csv', fast_reader=True)
assert (len(t) == NB_ROWS)
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"(",
"not",
"os",
".",
"getenv",
"(",
"'TEST_READ_HUGE_FILE'",
")",
")",
",",
"reason",
"=",
"'Environment variable TEST_READ_HUGE_FILE must be defined to run this test'",
")",
"def",
"test_read_big_table",
"(",
"tmpdir",
")",
":",
"NB_ROWS",
"=",
"250000",
"NB_COLS",
"=",
"500",
"filename",
"=",
"str",
"(",
"tmpdir",
".",
"join",
"(",
"'big_table.csv'",
")",
")",
"print",
"'Creating a {} rows table ({} columns).'",
".",
"format",
"(",
"NB_ROWS",
",",
"NB_COLS",
")",
"data",
"=",
"np",
".",
"random",
".",
"random",
"(",
"NB_ROWS",
")",
"t",
"=",
"Table",
"(",
"data",
"=",
"(",
"[",
"data",
"]",
"*",
"NB_COLS",
")",
",",
"names",
"=",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"NB_COLS",
")",
"]",
")",
"data",
"=",
"None",
"print",
"'Saving the table to {}'",
".",
"format",
"(",
"filename",
")",
"t",
".",
"write",
"(",
"filename",
",",
"format",
"=",
"'ascii.csv'",
",",
"overwrite",
"=",
"True",
")",
"t",
"=",
"None",
"print",
"'Counting the number of lines in the csv, it should be {} + 1 (header).'",
".",
"format",
"(",
"NB_ROWS",
")",
"assert",
"(",
"sum",
"(",
"(",
"1",
"for",
"line",
"in",
"open",
"(",
"filename",
")",
")",
")",
"==",
"(",
"NB_ROWS",
"+",
"1",
")",
")",
"print",
"'Reading the file with astropy.'",
"t",
"=",
"Table",
".",
"read",
"(",
"filename",
",",
"format",
"=",
"'ascii.csv'",
",",
"fast_reader",
"=",
"True",
")",
"assert",
"(",
"len",
"(",
"t",
")",
"==",
"NB_ROWS",
")"
] | test reading of a huge file . | train | false |
41,733 | def __add_obsolete_options(parser):
g = parser.add_argument_group('Obsolete options (not used anymore)')
g.add_argument(action=__obsolete_option, help='These options do not exist anymore.', *_OLD_OPTIONS)
| [
"def",
"__add_obsolete_options",
"(",
"parser",
")",
":",
"g",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Obsolete options (not used anymore)'",
")",
"g",
".",
"add_argument",
"(",
"action",
"=",
"__obsolete_option",
",",
"help",
"=",
"'These options do not exist anymore.'",
",",
"*",
"_OLD_OPTIONS",
")"
] | add the obsolete options to a option-parser instance and print error message when they are present . | train | false |
41,734 | def commit():
connection._commit()
set_clean()
| [
"def",
"commit",
"(",
")",
":",
"connection",
".",
"_commit",
"(",
")",
"set_clean",
"(",
")"
] | commits outstanding changes . | train | false |
41,735 | def buildIntegrationTests(mixinClass, name, fixture):
class RealTests(mixinClass, AsyncTestCase, ):
'\n Tests that endpoints are available over the network interfaces that\n real API users will be connecting from.\n '
def setUp(self):
self.app = fixture(self)
self.port = reactor.listenTCP(0, Site(self.app.resource()), interface='127.0.0.1')
self.addCleanup(self.port.stopListening)
portno = self.port.getHost().port
self.agent = ProxyAgent(TCP4ClientEndpoint(reactor, '127.0.0.1', portno), reactor)
super(RealTests, self).setUp()
class MemoryTests(mixinClass, AsyncTestCase, ):
'\n Tests that endpoints are available in the appropriate place, without\n testing that the correct network interfaces are listened on.\n '
def setUp(self):
self.app = fixture(self)
self.agent = MemoryAgent(self.app.resource())
super(MemoryTests, self).setUp()
RealTests.__name__ += name
MemoryTests.__name__ += name
RealTests.__module__ = mixinClass.__module__
MemoryTests.__module__ = mixinClass.__module__
return (RealTests, MemoryTests)
| [
"def",
"buildIntegrationTests",
"(",
"mixinClass",
",",
"name",
",",
"fixture",
")",
":",
"class",
"RealTests",
"(",
"mixinClass",
",",
"AsyncTestCase",
",",
")",
":",
"def",
"setUp",
"(",
"self",
")",
":",
"self",
".",
"app",
"=",
"fixture",
"(",
"self",
")",
"self",
".",
"port",
"=",
"reactor",
".",
"listenTCP",
"(",
"0",
",",
"Site",
"(",
"self",
".",
"app",
".",
"resource",
"(",
")",
")",
",",
"interface",
"=",
"'127.0.0.1'",
")",
"self",
".",
"addCleanup",
"(",
"self",
".",
"port",
".",
"stopListening",
")",
"portno",
"=",
"self",
".",
"port",
".",
"getHost",
"(",
")",
".",
"port",
"self",
".",
"agent",
"=",
"ProxyAgent",
"(",
"TCP4ClientEndpoint",
"(",
"reactor",
",",
"'127.0.0.1'",
",",
"portno",
")",
",",
"reactor",
")",
"super",
"(",
"RealTests",
",",
"self",
")",
".",
"setUp",
"(",
")",
"class",
"MemoryTests",
"(",
"mixinClass",
",",
"AsyncTestCase",
",",
")",
":",
"def",
"setUp",
"(",
"self",
")",
":",
"self",
".",
"app",
"=",
"fixture",
"(",
"self",
")",
"self",
".",
"agent",
"=",
"MemoryAgent",
"(",
"self",
".",
"app",
".",
"resource",
"(",
")",
")",
"super",
"(",
"MemoryTests",
",",
"self",
")",
".",
"setUp",
"(",
")",
"RealTests",
".",
"__name__",
"+=",
"name",
"MemoryTests",
".",
"__name__",
"+=",
"name",
"RealTests",
".",
"__module__",
"=",
"mixinClass",
".",
"__module__",
"MemoryTests",
".",
"__module__",
"=",
"mixinClass",
".",
"__module__",
"return",
"(",
"RealTests",
",",
"MemoryTests",
")"
] | build l{asynctestcase} classes that runs the tests in the mixin class with both real and in-memory queries . | train | false |
41,737 | def meter_message_from_counter(sample, secret):
msg = {'source': sample.source, 'counter_name': sample.name, 'counter_type': sample.type, 'counter_unit': sample.unit, 'counter_volume': sample.volume, 'user_id': sample.user_id, 'project_id': sample.project_id, 'resource_id': sample.resource_id, 'timestamp': sample.timestamp, 'resource_metadata': sample.resource_metadata, 'message_id': sample.id}
msg['message_signature'] = compute_signature(msg, secret)
return msg
| [
"def",
"meter_message_from_counter",
"(",
"sample",
",",
"secret",
")",
":",
"msg",
"=",
"{",
"'source'",
":",
"sample",
".",
"source",
",",
"'counter_name'",
":",
"sample",
".",
"name",
",",
"'counter_type'",
":",
"sample",
".",
"type",
",",
"'counter_unit'",
":",
"sample",
".",
"unit",
",",
"'counter_volume'",
":",
"sample",
".",
"volume",
",",
"'user_id'",
":",
"sample",
".",
"user_id",
",",
"'project_id'",
":",
"sample",
".",
"project_id",
",",
"'resource_id'",
":",
"sample",
".",
"resource_id",
",",
"'timestamp'",
":",
"sample",
".",
"timestamp",
",",
"'resource_metadata'",
":",
"sample",
".",
"resource_metadata",
",",
"'message_id'",
":",
"sample",
".",
"id",
"}",
"msg",
"[",
"'message_signature'",
"]",
"=",
"compute_signature",
"(",
"msg",
",",
"secret",
")",
"return",
"msg"
] | make a metering message ready to be published or stored . | train | false |
41,738 | def stage(func):
def coro(*args):
task = None
while True:
task = (yield task)
task = func(*(args + (task,)))
return coro
| [
"def",
"stage",
"(",
"func",
")",
":",
"def",
"coro",
"(",
"*",
"args",
")",
":",
"task",
"=",
"None",
"while",
"True",
":",
"task",
"=",
"(",
"yield",
"task",
")",
"task",
"=",
"func",
"(",
"*",
"(",
"args",
"+",
"(",
"task",
",",
")",
")",
")",
"return",
"coro"
] | decorate a function to become a simple stage . | train | false |
41,740 | def assure_entity(fnc):
@wraps(fnc)
def _wrapped(self, entity, *args, **kwargs):
if (not isinstance(entity, CloudMonitorEntity)):
entity = self._entity_manager.get(entity)
return fnc(self, entity, *args, **kwargs)
return _wrapped
| [
"def",
"assure_entity",
"(",
"fnc",
")",
":",
"@",
"wraps",
"(",
"fnc",
")",
"def",
"_wrapped",
"(",
"self",
",",
"entity",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"entity",
",",
"CloudMonitorEntity",
")",
")",
":",
"entity",
"=",
"self",
".",
"_entity_manager",
".",
"get",
"(",
"entity",
")",
"return",
"fnc",
"(",
"self",
",",
"entity",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"_wrapped"
] | converts an entityid passed as the entity to a cloudmonitorentity object . | train | true |
41,741 | def asset_diff(before, after):
alter_dic = {}
(before_dic, after_dic) = (before, dict(after.iterlists()))
for (k, v) in before_dic.items():
after_dic_values = after_dic.get(k, [])
if (k == 'group'):
after_dic_value = (after_dic_values if (len(after_dic_values) > 0) else u'')
uv = (v if (v is not None) else u'')
else:
after_dic_value = (after_dic_values[0] if (len(after_dic_values) > 0) else u'')
uv = (unicode(v) if (v is not None) else u'')
if (uv != after_dic_value):
alter_dic.update({k: [uv, after_dic_value]})
for (k, v) in alter_dic.items():
if (v == [None, u'']):
alter_dic.pop(k)
return alter_dic
| [
"def",
"asset_diff",
"(",
"before",
",",
"after",
")",
":",
"alter_dic",
"=",
"{",
"}",
"(",
"before_dic",
",",
"after_dic",
")",
"=",
"(",
"before",
",",
"dict",
"(",
"after",
".",
"iterlists",
"(",
")",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"before_dic",
".",
"items",
"(",
")",
":",
"after_dic_values",
"=",
"after_dic",
".",
"get",
"(",
"k",
",",
"[",
"]",
")",
"if",
"(",
"k",
"==",
"'group'",
")",
":",
"after_dic_value",
"=",
"(",
"after_dic_values",
"if",
"(",
"len",
"(",
"after_dic_values",
")",
">",
"0",
")",
"else",
"u''",
")",
"uv",
"=",
"(",
"v",
"if",
"(",
"v",
"is",
"not",
"None",
")",
"else",
"u''",
")",
"else",
":",
"after_dic_value",
"=",
"(",
"after_dic_values",
"[",
"0",
"]",
"if",
"(",
"len",
"(",
"after_dic_values",
")",
">",
"0",
")",
"else",
"u''",
")",
"uv",
"=",
"(",
"unicode",
"(",
"v",
")",
"if",
"(",
"v",
"is",
"not",
"None",
")",
"else",
"u''",
")",
"if",
"(",
"uv",
"!=",
"after_dic_value",
")",
":",
"alter_dic",
".",
"update",
"(",
"{",
"k",
":",
"[",
"uv",
",",
"after_dic_value",
"]",
"}",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"alter_dic",
".",
"items",
"(",
")",
":",
"if",
"(",
"v",
"==",
"[",
"None",
",",
"u''",
"]",
")",
":",
"alter_dic",
".",
"pop",
"(",
"k",
")",
"return",
"alter_dic"
] | asset change before and after . | train | false |
41,742 | def p_expression_2(t):
pass
| [
"def",
"p_expression_2",
"(",
"t",
")",
":",
"pass"
] | expression : expression comma assignment_expression . | train | false |
41,743 | def test_drange():
start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC)
end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)
delta = datetime.timedelta(hours=1)
assert_equal(24, len(mdates.drange(start, end, delta)))
end = (end + datetime.timedelta(microseconds=1))
assert_equal(25, len(mdates.drange(start, end, delta)))
end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)
delta = datetime.timedelta(hours=4)
daterange = mdates.drange(start, end, delta)
assert_equal(6, len(daterange))
assert_equal(mdates.num2date(daterange[(-1)]), (end - delta))
| [
"def",
"test_drange",
"(",
")",
":",
"start",
"=",
"datetime",
".",
"datetime",
"(",
"2011",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"mdates",
".",
"UTC",
")",
"end",
"=",
"datetime",
".",
"datetime",
"(",
"2011",
",",
"1",
",",
"2",
",",
"tzinfo",
"=",
"mdates",
".",
"UTC",
")",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"1",
")",
"assert_equal",
"(",
"24",
",",
"len",
"(",
"mdates",
".",
"drange",
"(",
"start",
",",
"end",
",",
"delta",
")",
")",
")",
"end",
"=",
"(",
"end",
"+",
"datetime",
".",
"timedelta",
"(",
"microseconds",
"=",
"1",
")",
")",
"assert_equal",
"(",
"25",
",",
"len",
"(",
"mdates",
".",
"drange",
"(",
"start",
",",
"end",
",",
"delta",
")",
")",
")",
"end",
"=",
"datetime",
".",
"datetime",
"(",
"2011",
",",
"1",
",",
"2",
",",
"tzinfo",
"=",
"mdates",
".",
"UTC",
")",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"4",
")",
"daterange",
"=",
"mdates",
".",
"drange",
"(",
"start",
",",
"end",
",",
"delta",
")",
"assert_equal",
"(",
"6",
",",
"len",
"(",
"daterange",
")",
")",
"assert_equal",
"(",
"mdates",
".",
"num2date",
"(",
"daterange",
"[",
"(",
"-",
"1",
")",
"]",
")",
",",
"(",
"end",
"-",
"delta",
")",
")"
] | this test should check if drange works as expected . | train | false |
41,745 | def getAllReceivers(sender=Any, signal=Any):
receivers = {}
for set in (getReceivers(sender, signal), getReceivers(sender, Any), getReceivers(Any, signal), getReceivers(Any, Any)):
for receiver in set:
if receiver:
try:
if (not receivers.has_key(receiver)):
receivers[receiver] = 1
(yield receiver)
except TypeError:
pass
| [
"def",
"getAllReceivers",
"(",
"sender",
"=",
"Any",
",",
"signal",
"=",
"Any",
")",
":",
"receivers",
"=",
"{",
"}",
"for",
"set",
"in",
"(",
"getReceivers",
"(",
"sender",
",",
"signal",
")",
",",
"getReceivers",
"(",
"sender",
",",
"Any",
")",
",",
"getReceivers",
"(",
"Any",
",",
"signal",
")",
",",
"getReceivers",
"(",
"Any",
",",
"Any",
")",
")",
":",
"for",
"receiver",
"in",
"set",
":",
"if",
"receiver",
":",
"try",
":",
"if",
"(",
"not",
"receivers",
".",
"has_key",
"(",
"receiver",
")",
")",
":",
"receivers",
"[",
"receiver",
"]",
"=",
"1",
"(",
"yield",
"receiver",
")",
"except",
"TypeError",
":",
"pass"
] | get list of all receivers from global tables this gets all dereferenced receivers which should receive the given signal from sender . | train | true |
41,747 | def remove_releases_from_collection(collection, releases=[]):
releaselist = ';'.join(releases)
return _do_mb_delete(('collection/%s/releases/%s' % (collection, releaselist)))
| [
"def",
"remove_releases_from_collection",
"(",
"collection",
",",
"releases",
"=",
"[",
"]",
")",
":",
"releaselist",
"=",
"';'",
".",
"join",
"(",
"releases",
")",
"return",
"_do_mb_delete",
"(",
"(",
"'collection/%s/releases/%s'",
"%",
"(",
"collection",
",",
"releaselist",
")",
")",
")"
] | remove releases from a collection . | train | false |
41,748 | def _np_conv_ok(volume, kernel, mode):
np_conv_ok = (volume.ndim == kernel.ndim == 1)
return (np_conv_ok and ((volume.size >= kernel.size) or (mode != 'same')))
| [
"def",
"_np_conv_ok",
"(",
"volume",
",",
"kernel",
",",
"mode",
")",
":",
"np_conv_ok",
"=",
"(",
"volume",
".",
"ndim",
"==",
"kernel",
".",
"ndim",
"==",
"1",
")",
"return",
"(",
"np_conv_ok",
"and",
"(",
"(",
"volume",
".",
"size",
">=",
"kernel",
".",
"size",
")",
"or",
"(",
"mode",
"!=",
"'same'",
")",
")",
")"
] | see if numpy supports convolution of volume and kernel . | train | false |
41,749 | def yuv2rgb(yuv):
return _convert(rgb_from_yuv, yuv)
| [
"def",
"yuv2rgb",
"(",
"yuv",
")",
":",
"return",
"_convert",
"(",
"rgb_from_yuv",
",",
"yuv",
")"
] | rgb to yiq color space conversion . | train | false |
41,750 | def get_initializer(name):
try:
return globals()[name]
except:
raise ValueError('Invalid initialization function.')
| [
"def",
"get_initializer",
"(",
"name",
")",
":",
"try",
":",
"return",
"globals",
"(",
")",
"[",
"name",
"]",
"except",
":",
"raise",
"ValueError",
"(",
"'Invalid initialization function.'",
")"
] | returns initialization function by the name . | train | false |
41,752 | def nova_import_alphabetical(logical_line, blank_lines, previous_logical, indent_level, previous_indent_level):
split_line = import_normalize(logical_line.strip()).lower().split()
split_previous = import_normalize(previous_logical.strip()).lower().split()
if ((blank_lines < 1) and (indent_level == previous_indent_level)):
length = [2, 4]
if ((len(split_line) in length) and (len(split_previous) in length) and (split_line[0] == 'import') and (split_previous[0] == 'import')):
if (split_line[1] < split_previous[1]):
(yield (0, ('N306: imports not in alphabetical order (%s, %s)' % (split_previous[1], split_line[1]))))
| [
"def",
"nova_import_alphabetical",
"(",
"logical_line",
",",
"blank_lines",
",",
"previous_logical",
",",
"indent_level",
",",
"previous_indent_level",
")",
":",
"split_line",
"=",
"import_normalize",
"(",
"logical_line",
".",
"strip",
"(",
")",
")",
".",
"lower",
"(",
")",
".",
"split",
"(",
")",
"split_previous",
"=",
"import_normalize",
"(",
"previous_logical",
".",
"strip",
"(",
")",
")",
".",
"lower",
"(",
")",
".",
"split",
"(",
")",
"if",
"(",
"(",
"blank_lines",
"<",
"1",
")",
"and",
"(",
"indent_level",
"==",
"previous_indent_level",
")",
")",
":",
"length",
"=",
"[",
"2",
",",
"4",
"]",
"if",
"(",
"(",
"len",
"(",
"split_line",
")",
"in",
"length",
")",
"and",
"(",
"len",
"(",
"split_previous",
")",
"in",
"length",
")",
"and",
"(",
"split_line",
"[",
"0",
"]",
"==",
"'import'",
")",
"and",
"(",
"split_previous",
"[",
"0",
"]",
"==",
"'import'",
")",
")",
":",
"if",
"(",
"split_line",
"[",
"1",
"]",
"<",
"split_previous",
"[",
"1",
"]",
")",
":",
"(",
"yield",
"(",
"0",
",",
"(",
"'N306: imports not in alphabetical order (%s, %s)'",
"%",
"(",
"split_previous",
"[",
"1",
"]",
",",
"split_line",
"[",
"1",
"]",
")",
")",
")",
")"
] | check for imports in alphabetical order . | train | false |
41,753 | def init(mpstate):
return SerialModule(mpstate)
| [
"def",
"init",
"(",
"mpstate",
")",
":",
"return",
"SerialModule",
"(",
"mpstate",
")"
] | initialise module . | train | false |
41,754 | def double_percent_hex_encoding(t):
return ('%25' + '%25'.join((hex(ord(c))[2:] for c in t)))
| [
"def",
"double_percent_hex_encoding",
"(",
"t",
")",
":",
"return",
"(",
"'%25'",
"+",
"'%25'",
".",
"join",
"(",
"(",
"hex",
"(",
"ord",
"(",
"c",
")",
")",
"[",
"2",
":",
"]",
"for",
"c",
"in",
"t",
")",
")",
")"
] | double percent hex encoding method . | train | false |
41,756 | def pinvh(a, cond=None, rcond=None, lower=True, return_rank=False, check_finite=True):
a = _asarray_validated(a, check_finite=check_finite)
(s, u) = decomp.eigh(a, lower=lower, check_finite=False)
if (rcond is not None):
cond = rcond
if (cond in [None, (-1)]):
t = u.dtype.char.lower()
factor = {'f': 1000.0, 'd': 1000000.0}
cond = (factor[t] * np.finfo(t).eps)
above_cutoff = (abs(s) > (cond * np.max(abs(s))))
psigma_diag = (1.0 / s[above_cutoff])
u = u[:, above_cutoff]
B = np.dot((u * psigma_diag), np.conjugate(u).T)
if return_rank:
return (B, len(psigma_diag))
else:
return B
| [
"def",
"pinvh",
"(",
"a",
",",
"cond",
"=",
"None",
",",
"rcond",
"=",
"None",
",",
"lower",
"=",
"True",
",",
"return_rank",
"=",
"False",
",",
"check_finite",
"=",
"True",
")",
":",
"a",
"=",
"_asarray_validated",
"(",
"a",
",",
"check_finite",
"=",
"check_finite",
")",
"(",
"s",
",",
"u",
")",
"=",
"decomp",
".",
"eigh",
"(",
"a",
",",
"lower",
"=",
"lower",
",",
"check_finite",
"=",
"False",
")",
"if",
"(",
"rcond",
"is",
"not",
"None",
")",
":",
"cond",
"=",
"rcond",
"if",
"(",
"cond",
"in",
"[",
"None",
",",
"(",
"-",
"1",
")",
"]",
")",
":",
"t",
"=",
"u",
".",
"dtype",
".",
"char",
".",
"lower",
"(",
")",
"factor",
"=",
"{",
"'f'",
":",
"1000.0",
",",
"'d'",
":",
"1000000.0",
"}",
"cond",
"=",
"(",
"factor",
"[",
"t",
"]",
"*",
"np",
".",
"finfo",
"(",
"t",
")",
".",
"eps",
")",
"above_cutoff",
"=",
"(",
"abs",
"(",
"s",
")",
">",
"(",
"cond",
"*",
"np",
".",
"max",
"(",
"abs",
"(",
"s",
")",
")",
")",
")",
"psigma_diag",
"=",
"(",
"1.0",
"/",
"s",
"[",
"above_cutoff",
"]",
")",
"u",
"=",
"u",
"[",
":",
",",
"above_cutoff",
"]",
"B",
"=",
"np",
".",
"dot",
"(",
"(",
"u",
"*",
"psigma_diag",
")",
",",
"np",
".",
"conjugate",
"(",
"u",
")",
".",
"T",
")",
"if",
"return_rank",
":",
"return",
"(",
"B",
",",
"len",
"(",
"psigma_diag",
")",
")",
"else",
":",
"return",
"B"
] | compute the pseudo-inverse of a hermitian matrix . | train | false |
41,757 | def _parse_route_template(template, default_sufix=''):
variables = {}
reverse_template = pattern = ''
args_count = last = 0
for match in _route_re.finditer(template):
part = template[last:match.start()]
name = match.group(1)
expr = (match.group(2) or default_sufix)
last = match.end()
if (not name):
name = ('__%d__' % args_count)
args_count += 1
pattern += ('%s(?P<%s>%s)' % (re.escape(part), name, expr))
reverse_template += ('%s%%(%s)s' % (part, name))
variables[name] = re.compile(('^%s$' % expr))
part = template[last:]
kwargs_count = (len(variables) - args_count)
reverse_template += part
regex = re.compile(('^%s%s$' % (pattern, re.escape(part))))
return (regex, reverse_template, args_count, kwargs_count, variables)
| [
"def",
"_parse_route_template",
"(",
"template",
",",
"default_sufix",
"=",
"''",
")",
":",
"variables",
"=",
"{",
"}",
"reverse_template",
"=",
"pattern",
"=",
"''",
"args_count",
"=",
"last",
"=",
"0",
"for",
"match",
"in",
"_route_re",
".",
"finditer",
"(",
"template",
")",
":",
"part",
"=",
"template",
"[",
"last",
":",
"match",
".",
"start",
"(",
")",
"]",
"name",
"=",
"match",
".",
"group",
"(",
"1",
")",
"expr",
"=",
"(",
"match",
".",
"group",
"(",
"2",
")",
"or",
"default_sufix",
")",
"last",
"=",
"match",
".",
"end",
"(",
")",
"if",
"(",
"not",
"name",
")",
":",
"name",
"=",
"(",
"'__%d__'",
"%",
"args_count",
")",
"args_count",
"+=",
"1",
"pattern",
"+=",
"(",
"'%s(?P<%s>%s)'",
"%",
"(",
"re",
".",
"escape",
"(",
"part",
")",
",",
"name",
",",
"expr",
")",
")",
"reverse_template",
"+=",
"(",
"'%s%%(%s)s'",
"%",
"(",
"part",
",",
"name",
")",
")",
"variables",
"[",
"name",
"]",
"=",
"re",
".",
"compile",
"(",
"(",
"'^%s$'",
"%",
"expr",
")",
")",
"part",
"=",
"template",
"[",
"last",
":",
"]",
"kwargs_count",
"=",
"(",
"len",
"(",
"variables",
")",
"-",
"args_count",
")",
"reverse_template",
"+=",
"part",
"regex",
"=",
"re",
".",
"compile",
"(",
"(",
"'^%s%s$'",
"%",
"(",
"pattern",
",",
"re",
".",
"escape",
"(",
"part",
")",
")",
")",
")",
"return",
"(",
"regex",
",",
"reverse_template",
",",
"args_count",
",",
"kwargs_count",
",",
"variables",
")"
] | lazy route template parser . | train | false |
41,758 | def createTestSocket(test, addressFamily, socketType):
skt = socket.socket(addressFamily, socketType)
test.addCleanup(skt.close)
return skt
| [
"def",
"createTestSocket",
"(",
"test",
",",
"addressFamily",
",",
"socketType",
")",
":",
"skt",
"=",
"socket",
".",
"socket",
"(",
"addressFamily",
",",
"socketType",
")",
"test",
".",
"addCleanup",
"(",
"skt",
".",
"close",
")",
"return",
"skt"
] | create a socket for the duration of the given test . | train | false |
41,759 | def bool_formatter(view, value):
glyph = ('ok-circle' if value else 'minus-sign')
fa = ('check-circle' if value else 'minus-circle')
return Markup(('<span class="fa fa-%s glyphicon glyphicon-%s icon-%s"></span>' % (fa, glyph, glyph)))
| [
"def",
"bool_formatter",
"(",
"view",
",",
"value",
")",
":",
"glyph",
"=",
"(",
"'ok-circle'",
"if",
"value",
"else",
"'minus-sign'",
")",
"fa",
"=",
"(",
"'check-circle'",
"if",
"value",
"else",
"'minus-circle'",
")",
"return",
"Markup",
"(",
"(",
"'<span class=\"fa fa-%s glyphicon glyphicon-%s icon-%s\"></span>'",
"%",
"(",
"fa",
",",
"glyph",
",",
"glyph",
")",
")",
")"
] | return check icon if value is true or empty string otherwise . | train | false |
41,761 | def replace_icon_with_default(request):
"\n Expected output will look something like this:\n {\n 'success': true,\n 'portfolio_entry__pk': 0\n }"
portfolio_entry = PortfolioEntry.objects.get(pk=int(request.POST['portfolio_entry__pk']), person__user=request.user)
project = portfolio_entry.project
project_before_changes = mysite.search.models.Project.objects.get(pk=project.pk)
mysite.search.models.WrongIcon.spawn_from_project(project)
try:
wrong_icon_url = project_before_changes.icon_for_profile.url
except ValueError:
wrong_icon_url = 'icon_url'
project.invalidate_all_icons()
project.save()
data = {}
data['success'] = True
data['portfolio_entry__pk'] = portfolio_entry.pk
return mysite.base.view_helpers.json_response(data)
| [
"def",
"replace_icon_with_default",
"(",
"request",
")",
":",
"portfolio_entry",
"=",
"PortfolioEntry",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"int",
"(",
"request",
".",
"POST",
"[",
"'portfolio_entry__pk'",
"]",
")",
",",
"person__user",
"=",
"request",
".",
"user",
")",
"project",
"=",
"portfolio_entry",
".",
"project",
"project_before_changes",
"=",
"mysite",
".",
"search",
".",
"models",
".",
"Project",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"project",
".",
"pk",
")",
"mysite",
".",
"search",
".",
"models",
".",
"WrongIcon",
".",
"spawn_from_project",
"(",
"project",
")",
"try",
":",
"wrong_icon_url",
"=",
"project_before_changes",
".",
"icon_for_profile",
".",
"url",
"except",
"ValueError",
":",
"wrong_icon_url",
"=",
"'icon_url'",
"project",
".",
"invalidate_all_icons",
"(",
")",
"project",
".",
"save",
"(",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'success'",
"]",
"=",
"True",
"data",
"[",
"'portfolio_entry__pk'",
"]",
"=",
"portfolio_entry",
".",
"pk",
"return",
"mysite",
".",
"base",
".",
"view_helpers",
".",
"json_response",
"(",
"data",
")"
] | expected postcondition: projects icon_dict says it is generic . | train | false |
41,763 | @utils.arg('vtype', metavar='<vtype>', help='Name or ID of the monitor type')
@utils.arg('action', metavar='<action>', choices=['set', 'unset'], help="Actions: 'set' or 'unset'")
@utils.arg('metadata', metavar='<key=value>', nargs='*', default=None, help='Extra_specs to set/unset (only key is necessary on unset)')
@utils.service_type('monitor')
def do_type_key(cs, args):
vtype = _find_monitor_type(cs, args.vtype)
if (args.metadata is not None):
keypair = _extract_metadata(args)
if (args.action == 'set'):
vtype.set_keys(keypair)
elif (args.action == 'unset'):
vtype.unset_keys(keypair.keys())
| [
"@",
"utils",
".",
"arg",
"(",
"'vtype'",
",",
"metavar",
"=",
"'<vtype>'",
",",
"help",
"=",
"'Name or ID of the monitor type'",
")",
"@",
"utils",
".",
"arg",
"(",
"'action'",
",",
"metavar",
"=",
"'<action>'",
",",
"choices",
"=",
"[",
"'set'",
",",
"'unset'",
"]",
",",
"help",
"=",
"\"Actions: 'set' or 'unset'\"",
")",
"@",
"utils",
".",
"arg",
"(",
"'metadata'",
",",
"metavar",
"=",
"'<key=value>'",
",",
"nargs",
"=",
"'*'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Extra_specs to set/unset (only key is necessary on unset)'",
")",
"@",
"utils",
".",
"service_type",
"(",
"'monitor'",
")",
"def",
"do_type_key",
"(",
"cs",
",",
"args",
")",
":",
"vtype",
"=",
"_find_monitor_type",
"(",
"cs",
",",
"args",
".",
"vtype",
")",
"if",
"(",
"args",
".",
"metadata",
"is",
"not",
"None",
")",
":",
"keypair",
"=",
"_extract_metadata",
"(",
"args",
")",
"if",
"(",
"args",
".",
"action",
"==",
"'set'",
")",
":",
"vtype",
".",
"set_keys",
"(",
"keypair",
")",
"elif",
"(",
"args",
".",
"action",
"==",
"'unset'",
")",
":",
"vtype",
".",
"unset_keys",
"(",
"keypair",
".",
"keys",
"(",
")",
")"
] | set or unset extra_spec for a monitor type . | train | false |
41,764 | def test_gp_new_generation():
tpot_obj = TPOTClassifier()
tpot_obj._pbar = tqdm(total=1, disable=True)
assert (tpot_obj._gp_generation == 0)
@_gp_new_generation
def dummy_function(self, foo):
pass
dummy_function(tpot_obj, None)
assert (tpot_obj._gp_generation == 1)
| [
"def",
"test_gp_new_generation",
"(",
")",
":",
"tpot_obj",
"=",
"TPOTClassifier",
"(",
")",
"tpot_obj",
".",
"_pbar",
"=",
"tqdm",
"(",
"total",
"=",
"1",
",",
"disable",
"=",
"True",
")",
"assert",
"(",
"tpot_obj",
".",
"_gp_generation",
"==",
"0",
")",
"@",
"_gp_new_generation",
"def",
"dummy_function",
"(",
"self",
",",
"foo",
")",
":",
"pass",
"dummy_function",
"(",
"tpot_obj",
",",
"None",
")",
"assert",
"(",
"tpot_obj",
".",
"_gp_generation",
"==",
"1",
")"
] | assert that the gp_generation count gets incremented when _gp_new_generation is called . | train | false |
41,765 | def _NormalizeEnvVarReferences(str):
str = re.sub('\\$([a-zA-Z_][a-zA-Z0-9_]*)', '${\\1}', str)
matches = re.findall('(\\$\\(([a-zA-Z0-9\\-_]+)\\))', str)
for match in matches:
(to_replace, variable) = match
assert ('$(' not in match), ('$($(FOO)) variables not supported: ' + match)
str = str.replace(to_replace, (('${' + variable) + '}'))
return str
| [
"def",
"_NormalizeEnvVarReferences",
"(",
"str",
")",
":",
"str",
"=",
"re",
".",
"sub",
"(",
"'\\\\$([a-zA-Z_][a-zA-Z0-9_]*)'",
",",
"'${\\\\1}'",
",",
"str",
")",
"matches",
"=",
"re",
".",
"findall",
"(",
"'(\\\\$\\\\(([a-zA-Z0-9\\\\-_]+)\\\\))'",
",",
"str",
")",
"for",
"match",
"in",
"matches",
":",
"(",
"to_replace",
",",
"variable",
")",
"=",
"match",
"assert",
"(",
"'$('",
"not",
"in",
"match",
")",
",",
"(",
"'$($(FOO)) variables not supported: '",
"+",
"match",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"to_replace",
",",
"(",
"(",
"'${'",
"+",
"variable",
")",
"+",
"'}'",
")",
")",
"return",
"str"
] | takes a string containing variable references in the form ${foo} . | train | false |
41,767 | def cpu_count_logical():
return cext.cpu_count_logical()
| [
"def",
"cpu_count_logical",
"(",
")",
":",
"return",
"cext",
".",
"cpu_count_logical",
"(",
")"
] | return the number of logical cpus in the system . | train | false |
41,770 | def decorator_apply(dec, func):
return FunctionMaker.create(func, 'return decorated(%(signature)s)', dict(decorated=dec(func)), __wrapped__=func)
| [
"def",
"decorator_apply",
"(",
"dec",
",",
"func",
")",
":",
"return",
"FunctionMaker",
".",
"create",
"(",
"func",
",",
"'return decorated(%(signature)s)'",
",",
"dict",
"(",
"decorated",
"=",
"dec",
"(",
"func",
")",
")",
",",
"__wrapped__",
"=",
"func",
")"
] | decorate a function by preserving the signature even if dec is not a signature-preserving decorator . | train | false |
41,772 | def findElementsWithAttributeShallow(parent, attribute):
return findNodesShallow(parent, (lambda n: ((getattr(n, 'tagName', None) is not None) and n.hasAttribute(attribute))))
| [
"def",
"findElementsWithAttributeShallow",
"(",
"parent",
",",
"attribute",
")",
":",
"return",
"findNodesShallow",
"(",
"parent",
",",
"(",
"lambda",
"n",
":",
"(",
"(",
"getattr",
"(",
"n",
",",
"'tagName'",
",",
"None",
")",
"is",
"not",
"None",
")",
"and",
"n",
".",
"hasAttribute",
"(",
"attribute",
")",
")",
")",
")"
] | return an iterable of the elements which are direct children of c{parent} and which have the c{attribute} attribute . | train | false |
41,774 | def test_git_require_no_update():
from fabtools.require.git import working_copy
try:
working_copy(REMOTE_URL, path='wc')
run('tar -c -f wc_old.tar --exclude .git wc')
old_md5 = md5sum('wc_old.tar')
working_copy(REMOTE_URL, path='wc', update=False)
run('tar -c -f wc_new.tar --exclude .git wc')
new_md5 = md5sum('wc_new.tar')
assert (old_md5 == new_md5)
finally:
run('rm -rf wc')
| [
"def",
"test_git_require_no_update",
"(",
")",
":",
"from",
"fabtools",
".",
"require",
".",
"git",
"import",
"working_copy",
"try",
":",
"working_copy",
"(",
"REMOTE_URL",
",",
"path",
"=",
"'wc'",
")",
"run",
"(",
"'tar -c -f wc_old.tar --exclude .git wc'",
")",
"old_md5",
"=",
"md5sum",
"(",
"'wc_old.tar'",
")",
"working_copy",
"(",
"REMOTE_URL",
",",
"path",
"=",
"'wc'",
",",
"update",
"=",
"False",
")",
"run",
"(",
"'tar -c -f wc_new.tar --exclude .git wc'",
")",
"new_md5",
"=",
"md5sum",
"(",
"'wc_new.tar'",
")",
"assert",
"(",
"old_md5",
"==",
"new_md5",
")",
"finally",
":",
"run",
"(",
"'rm -rf wc'",
")"
] | test working_copy() with update=false . | train | false |
41,775 | def create_readable_names_for_imagenet_labels():
base_url = 'https://raw.githubusercontent.com/tensorflow/models/master/inception/inception/data/'
synset_url = '{}/imagenet_lsvrc_2015_synsets.txt'.format(base_url)
synset_to_human_url = '{}/imagenet_metadata.txt'.format(base_url)
(filename, _) = urllib.request.urlretrieve(synset_url)
synset_list = [s.strip() for s in open(filename).readlines()]
num_synsets_in_ilsvrc = len(synset_list)
assert (num_synsets_in_ilsvrc == 1000)
(filename, _) = urllib.request.urlretrieve(synset_to_human_url)
synset_to_human_list = open(filename).readlines()
num_synsets_in_all_imagenet = len(synset_to_human_list)
assert (num_synsets_in_all_imagenet == 21842)
synset_to_human = {}
for s in synset_to_human_list:
parts = s.strip().split(' DCTB ')
assert (len(parts) == 2)
synset = parts[0]
human = parts[1]
synset_to_human[synset] = human
label_index = 1
labels_to_names = {0: 'background'}
for synset in synset_list:
name = synset_to_human[synset]
labels_to_names[label_index] = name
label_index += 1
return labels_to_names
| [
"def",
"create_readable_names_for_imagenet_labels",
"(",
")",
":",
"base_url",
"=",
"'https://raw.githubusercontent.com/tensorflow/models/master/inception/inception/data/'",
"synset_url",
"=",
"'{}/imagenet_lsvrc_2015_synsets.txt'",
".",
"format",
"(",
"base_url",
")",
"synset_to_human_url",
"=",
"'{}/imagenet_metadata.txt'",
".",
"format",
"(",
"base_url",
")",
"(",
"filename",
",",
"_",
")",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"synset_url",
")",
"synset_list",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"open",
"(",
"filename",
")",
".",
"readlines",
"(",
")",
"]",
"num_synsets_in_ilsvrc",
"=",
"len",
"(",
"synset_list",
")",
"assert",
"(",
"num_synsets_in_ilsvrc",
"==",
"1000",
")",
"(",
"filename",
",",
"_",
")",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"synset_to_human_url",
")",
"synset_to_human_list",
"=",
"open",
"(",
"filename",
")",
".",
"readlines",
"(",
")",
"num_synsets_in_all_imagenet",
"=",
"len",
"(",
"synset_to_human_list",
")",
"assert",
"(",
"num_synsets_in_all_imagenet",
"==",
"21842",
")",
"synset_to_human",
"=",
"{",
"}",
"for",
"s",
"in",
"synset_to_human_list",
":",
"parts",
"=",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' DCTB '",
")",
"assert",
"(",
"len",
"(",
"parts",
")",
"==",
"2",
")",
"synset",
"=",
"parts",
"[",
"0",
"]",
"human",
"=",
"parts",
"[",
"1",
"]",
"synset_to_human",
"[",
"synset",
"]",
"=",
"human",
"label_index",
"=",
"1",
"labels_to_names",
"=",
"{",
"0",
":",
"'background'",
"}",
"for",
"synset",
"in",
"synset_list",
":",
"name",
"=",
"synset_to_human",
"[",
"synset",
"]",
"labels_to_names",
"[",
"label_index",
"]",
"=",
"name",
"label_index",
"+=",
"1",
"return",
"labels_to_names"
] | create a dict mapping label id to human readable string . | train | false |
41,776 | def index_of(y):
try:
return (y.index.values, y.values)
except AttributeError:
y = np.atleast_1d(y)
return (np.arange(y.shape[0], dtype=float), y)
| [
"def",
"index_of",
"(",
"y",
")",
":",
"try",
":",
"return",
"(",
"y",
".",
"index",
".",
"values",
",",
"y",
".",
"values",
")",
"except",
"AttributeError",
":",
"y",
"=",
"np",
".",
"atleast_1d",
"(",
"y",
")",
"return",
"(",
"np",
".",
"arange",
"(",
"y",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"float",
")",
",",
"y",
")"
] | a helper function to get the index of an input to plot against if x values are not explicitly given . | train | false |
41,778 | @pytest.mark.skipif(u'not HAS_SCIPY')
def test_blackbody_scipy():
flux_unit = (u.Watt / ((u.m ** 2) * u.um))
wave = (np.logspace(0, 8, 100000) * u.AA)
temp = (100.0 * u.K)
with np.errstate(all=u'ignore'):
bb_nu = (blackbody_nu(wave, temp) * u.sr)
flux = (bb_nu.to(flux_unit, u.spectral_density(wave)) / u.sr)
lum = wave.to(u.um)
intflux = integrate.trapz(flux.value, x=lum.value)
ans = ((const.sigma_sb * (temp ** 4)) / np.pi)
np.testing.assert_allclose(intflux, ans.value, rtol=0.01)
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"u'not HAS_SCIPY'",
")",
"def",
"test_blackbody_scipy",
"(",
")",
":",
"flux_unit",
"=",
"(",
"u",
".",
"Watt",
"/",
"(",
"(",
"u",
".",
"m",
"**",
"2",
")",
"*",
"u",
".",
"um",
")",
")",
"wave",
"=",
"(",
"np",
".",
"logspace",
"(",
"0",
",",
"8",
",",
"100000",
")",
"*",
"u",
".",
"AA",
")",
"temp",
"=",
"(",
"100.0",
"*",
"u",
".",
"K",
")",
"with",
"np",
".",
"errstate",
"(",
"all",
"=",
"u'ignore'",
")",
":",
"bb_nu",
"=",
"(",
"blackbody_nu",
"(",
"wave",
",",
"temp",
")",
"*",
"u",
".",
"sr",
")",
"flux",
"=",
"(",
"bb_nu",
".",
"to",
"(",
"flux_unit",
",",
"u",
".",
"spectral_density",
"(",
"wave",
")",
")",
"/",
"u",
".",
"sr",
")",
"lum",
"=",
"wave",
".",
"to",
"(",
"u",
".",
"um",
")",
"intflux",
"=",
"integrate",
".",
"trapz",
"(",
"flux",
".",
"value",
",",
"x",
"=",
"lum",
".",
"value",
")",
"ans",
"=",
"(",
"(",
"const",
".",
"sigma_sb",
"*",
"(",
"temp",
"**",
"4",
")",
")",
"/",
"np",
".",
"pi",
")",
"np",
".",
"testing",
".",
"assert_allclose",
"(",
"intflux",
",",
"ans",
".",
"value",
",",
"rtol",
"=",
"0.01",
")"
] | test planck function . | train | false |
41,781 | def clear_credentials():
global identity, regions, services, cloudservers, cloudfiles, cloud_cdn
global cloud_loadbalancers, cloud_databases, cloud_blockstorage, cloud_dns
global cloud_networks, cloud_monitoring, autoscale, images, queues
identity = None
regions = tuple()
services = tuple()
cloudservers = None
cloudfiles = None
cloud_cdn = None
cloud_loadbalancers = None
cloud_databases = None
cloud_blockstorage = None
cloud_dns = None
cloud_networks = None
cloud_monitoring = None
autoscale = None
images = None
queues = None
| [
"def",
"clear_credentials",
"(",
")",
":",
"global",
"identity",
",",
"regions",
",",
"services",
",",
"cloudservers",
",",
"cloudfiles",
",",
"cloud_cdn",
"global",
"cloud_loadbalancers",
",",
"cloud_databases",
",",
"cloud_blockstorage",
",",
"cloud_dns",
"global",
"cloud_networks",
",",
"cloud_monitoring",
",",
"autoscale",
",",
"images",
",",
"queues",
"identity",
"=",
"None",
"regions",
"=",
"tuple",
"(",
")",
"services",
"=",
"tuple",
"(",
")",
"cloudservers",
"=",
"None",
"cloudfiles",
"=",
"None",
"cloud_cdn",
"=",
"None",
"cloud_loadbalancers",
"=",
"None",
"cloud_databases",
"=",
"None",
"cloud_blockstorage",
"=",
"None",
"cloud_dns",
"=",
"None",
"cloud_networks",
"=",
"None",
"cloud_monitoring",
"=",
"None",
"autoscale",
"=",
"None",
"images",
"=",
"None",
"queues",
"=",
"None"
] | de-authenticate by clearing all the names back to none . | train | true |
41,782 | def get_national_holidays(begin, end):
begin = datefactory(begin.year, begin.month, begin.day, begin)
end = datefactory(end.year, end.month, end.day, end)
holidays = [str2date(datestr, begin) for datestr in FRENCH_MOBILE_HOLIDAYS.values()]
for year in range(begin.year, (end.year + 1)):
for datestr in FRENCH_FIXED_HOLIDAYS.values():
date = str2date((datestr % year), begin)
if (date not in holidays):
holidays.append(date)
return [day for day in holidays if (begin <= day < end)]
| [
"def",
"get_national_holidays",
"(",
"begin",
",",
"end",
")",
":",
"begin",
"=",
"datefactory",
"(",
"begin",
".",
"year",
",",
"begin",
".",
"month",
",",
"begin",
".",
"day",
",",
"begin",
")",
"end",
"=",
"datefactory",
"(",
"end",
".",
"year",
",",
"end",
".",
"month",
",",
"end",
".",
"day",
",",
"end",
")",
"holidays",
"=",
"[",
"str2date",
"(",
"datestr",
",",
"begin",
")",
"for",
"datestr",
"in",
"FRENCH_MOBILE_HOLIDAYS",
".",
"values",
"(",
")",
"]",
"for",
"year",
"in",
"range",
"(",
"begin",
".",
"year",
",",
"(",
"end",
".",
"year",
"+",
"1",
")",
")",
":",
"for",
"datestr",
"in",
"FRENCH_FIXED_HOLIDAYS",
".",
"values",
"(",
")",
":",
"date",
"=",
"str2date",
"(",
"(",
"datestr",
"%",
"year",
")",
",",
"begin",
")",
"if",
"(",
"date",
"not",
"in",
"holidays",
")",
":",
"holidays",
".",
"append",
"(",
"date",
")",
"return",
"[",
"day",
"for",
"day",
"in",
"holidays",
"if",
"(",
"begin",
"<=",
"day",
"<",
"end",
")",
"]"
] | return french national days off between begin and end . | train | false |
41,783 | def get_selection_from_user(message, *values):
return _validate_user_input(SelectionDialog(message, values))
| [
"def",
"get_selection_from_user",
"(",
"message",
",",
"*",
"values",
")",
":",
"return",
"_validate_user_input",
"(",
"SelectionDialog",
"(",
"message",
",",
"values",
")",
")"
] | pauses test execution and asks user to select a value . | train | false |
41,784 | def bubblesort(a):
for i in range(len(a)):
for j in range(i, len(a)):
if (a[i] > a[j]):
(a[i], a[j]) = (a[j], a[i])
return a
| [
"def",
"bubblesort",
"(",
"a",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
",",
"len",
"(",
"a",
")",
")",
":",
"if",
"(",
"a",
"[",
"i",
"]",
">",
"a",
"[",
"j",
"]",
")",
":",
"(",
"a",
"[",
"i",
"]",
",",
"a",
"[",
"j",
"]",
")",
"=",
"(",
"a",
"[",
"j",
"]",
",",
"a",
"[",
"i",
"]",
")",
"return",
"a"
] | bubble sort implementation . | train | false |
41,785 | def _revalidate_node_edges(rag, node, heap_list):
for nbr in rag.neighbors(node):
data = rag[node][nbr]
try:
data['heap item'][3] = False
_invalidate_edge(rag, node, nbr)
except KeyError:
pass
wt = data['weight']
heap_item = [wt, node, nbr, True]
data['heap item'] = heap_item
heapq.heappush(heap_list, heap_item)
| [
"def",
"_revalidate_node_edges",
"(",
"rag",
",",
"node",
",",
"heap_list",
")",
":",
"for",
"nbr",
"in",
"rag",
".",
"neighbors",
"(",
"node",
")",
":",
"data",
"=",
"rag",
"[",
"node",
"]",
"[",
"nbr",
"]",
"try",
":",
"data",
"[",
"'heap item'",
"]",
"[",
"3",
"]",
"=",
"False",
"_invalidate_edge",
"(",
"rag",
",",
"node",
",",
"nbr",
")",
"except",
"KeyError",
":",
"pass",
"wt",
"=",
"data",
"[",
"'weight'",
"]",
"heap_item",
"=",
"[",
"wt",
",",
"node",
",",
"nbr",
",",
"True",
"]",
"data",
"[",
"'heap item'",
"]",
"=",
"heap_item",
"heapq",
".",
"heappush",
"(",
"heap_list",
",",
"heap_item",
")"
] | handles validation and invalidation of edges incident to a node . | train | false |
41,787 | def slice_array(out_name, in_name, blockdims, index):
index = replace_ellipsis(len(blockdims), index)
index = tuple(map(sanitize_index, index))
blockdims = tuple(map(tuple, blockdims))
if all(((index == slice(None, None, None)) for index in index)):
suffixes = product(*[range(len(bd)) for bd in blockdims])
dsk = dict(((((out_name,) + s), ((in_name,) + s)) for s in suffixes))
return (dsk, blockdims)
missing = (len(blockdims) - (len(index) - index.count(None)))
index += ((slice(None, None, None),) * missing)
(dsk_out, bd_out) = slice_with_newaxes(out_name, in_name, blockdims, index)
bd_out = tuple(map(tuple, bd_out))
return (dsk_out, bd_out)
| [
"def",
"slice_array",
"(",
"out_name",
",",
"in_name",
",",
"blockdims",
",",
"index",
")",
":",
"index",
"=",
"replace_ellipsis",
"(",
"len",
"(",
"blockdims",
")",
",",
"index",
")",
"index",
"=",
"tuple",
"(",
"map",
"(",
"sanitize_index",
",",
"index",
")",
")",
"blockdims",
"=",
"tuple",
"(",
"map",
"(",
"tuple",
",",
"blockdims",
")",
")",
"if",
"all",
"(",
"(",
"(",
"index",
"==",
"slice",
"(",
"None",
",",
"None",
",",
"None",
")",
")",
"for",
"index",
"in",
"index",
")",
")",
":",
"suffixes",
"=",
"product",
"(",
"*",
"[",
"range",
"(",
"len",
"(",
"bd",
")",
")",
"for",
"bd",
"in",
"blockdims",
"]",
")",
"dsk",
"=",
"dict",
"(",
"(",
"(",
"(",
"(",
"out_name",
",",
")",
"+",
"s",
")",
",",
"(",
"(",
"in_name",
",",
")",
"+",
"s",
")",
")",
"for",
"s",
"in",
"suffixes",
")",
")",
"return",
"(",
"dsk",
",",
"blockdims",
")",
"missing",
"=",
"(",
"len",
"(",
"blockdims",
")",
"-",
"(",
"len",
"(",
"index",
")",
"-",
"index",
".",
"count",
"(",
"None",
")",
")",
")",
"index",
"+=",
"(",
"(",
"slice",
"(",
"None",
",",
"None",
",",
"None",
")",
",",
")",
"*",
"missing",
")",
"(",
"dsk_out",
",",
"bd_out",
")",
"=",
"slice_with_newaxes",
"(",
"out_name",
",",
"in_name",
",",
"blockdims",
",",
"index",
")",
"bd_out",
"=",
"tuple",
"(",
"map",
"(",
"tuple",
",",
"bd_out",
")",
")",
"return",
"(",
"dsk_out",
",",
"bd_out",
")"
] | master function for array slicing this function makes a new dask that slices blocks along every dimension and aggregates each dimensions slices so that the resulting block slices give the same results as the original slice on the original structure index must be a tuple . | train | false |
41,788 | def split_list(l, split):
m = sp.match(split)
if (not m):
raise ValueError('split must be a string of the form a/b where a and b are ints')
(i, t) = map(int, m.groups())
return l[(((i - 1) * len(l)) // t):((i * len(l)) // t)]
| [
"def",
"split_list",
"(",
"l",
",",
"split",
")",
":",
"m",
"=",
"sp",
".",
"match",
"(",
"split",
")",
"if",
"(",
"not",
"m",
")",
":",
"raise",
"ValueError",
"(",
"'split must be a string of the form a/b where a and b are ints'",
")",
"(",
"i",
",",
"t",
")",
"=",
"map",
"(",
"int",
",",
"m",
".",
"groups",
"(",
")",
")",
"return",
"l",
"[",
"(",
"(",
"(",
"i",
"-",
"1",
")",
"*",
"len",
"(",
"l",
")",
")",
"//",
"t",
")",
":",
"(",
"(",
"i",
"*",
"len",
"(",
"l",
")",
")",
"//",
"t",
")",
"]"
] | splits a list into part a of b split should be a string of the form a/b . | train | false |
41,789 | def onRequestCharge(ordersID, entityDBID, datas):
INFO_MSG(('onRequestCharge: entityDBID=%s, entityDBID=%s' % (ordersID, entityDBID)))
KBEngine.chargeResponse(ordersID, datas, KBEngine.SERVER_SUCCESS)
| [
"def",
"onRequestCharge",
"(",
"ordersID",
",",
"entityDBID",
",",
"datas",
")",
":",
"INFO_MSG",
"(",
"(",
"'onRequestCharge: entityDBID=%s, entityDBID=%s'",
"%",
"(",
"ordersID",
",",
"entityDBID",
")",
")",
")",
"KBEngine",
".",
"chargeResponse",
"(",
"ordersID",
",",
"datas",
",",
"KBEngine",
".",
"SERVER_SUCCESS",
")"
] | kbengine method . | train | false |
41,790 | def execlp(file, *args):
execvp(file, args)
| [
"def",
"execlp",
"(",
"file",
",",
"*",
"args",
")",
":",
"execvp",
"(",
"file",
",",
"args",
")"
] | execlp execute the executable file with argument list args . | train | false |
41,791 | def install_pip(python_cmd='python', use_sudo=True):
with cd('/tmp'):
download(GET_PIP_URL)
command = ('%(python_cmd)s get-pip.py' % locals())
if use_sudo:
run_as_root(command, pty=False)
else:
run(command, pty=False)
run('rm -f get-pip.py')
| [
"def",
"install_pip",
"(",
"python_cmd",
"=",
"'python'",
",",
"use_sudo",
"=",
"True",
")",
":",
"with",
"cd",
"(",
"'/tmp'",
")",
":",
"download",
"(",
"GET_PIP_URL",
")",
"command",
"=",
"(",
"'%(python_cmd)s get-pip.py'",
"%",
"locals",
"(",
")",
")",
"if",
"use_sudo",
":",
"run_as_root",
"(",
"command",
",",
"pty",
"=",
"False",
")",
"else",
":",
"run",
"(",
"command",
",",
"pty",
"=",
"False",
")",
"run",
"(",
"'rm -f get-pip.py'",
")"
] | install the latest version of pip_ . | train | false |
41,793 | def queens_constraint(A, a, B, b):
if (A == B):
return True
return ((a != b) and ((A + a) != (B + b)) and ((A - a) != (B - b)))
| [
"def",
"queens_constraint",
"(",
"A",
",",
"a",
",",
"B",
",",
"b",
")",
":",
"if",
"(",
"A",
"==",
"B",
")",
":",
"return",
"True",
"return",
"(",
"(",
"a",
"!=",
"b",
")",
"and",
"(",
"(",
"A",
"+",
"a",
")",
"!=",
"(",
"B",
"+",
"b",
")",
")",
"and",
"(",
"(",
"A",
"-",
"a",
")",
"!=",
"(",
"B",
"-",
"b",
")",
")",
")"
] | constraint is satisfied if its the same column . | train | false |
41,795 | def removeCSVFile(csvFilePath):
if (('alterations' in csvFilePath) and ('example_' not in csvFilePath)):
os.remove(csvFilePath)
print ('removeGeneratedFiles deleted ' + csvFilePath)
| [
"def",
"removeCSVFile",
"(",
"csvFilePath",
")",
":",
"if",
"(",
"(",
"'alterations'",
"in",
"csvFilePath",
")",
"and",
"(",
"'example_'",
"not",
"in",
"csvFilePath",
")",
")",
":",
"os",
".",
"remove",
"(",
"csvFilePath",
")",
"print",
"(",
"'removeGeneratedFiles deleted '",
"+",
"csvFilePath",
")"
] | remove csv file . | train | false |
41,796 | def denormalize_formset_dict(data_dict_list, formset, attr_list):
assert isinstance(formset, BaseSimpleFormSet)
res = django.http.QueryDict('', mutable=True)
for (i, data_dict) in enumerate(data_dict_list):
prefix = formset.make_prefix(i)
form = formset.form(prefix=prefix)
res.update(denormalize_form_dict(data_dict, form, attr_list))
res[(prefix + '-_exists')] = 'True'
res[str(formset.management_form.add_prefix('next_form_id'))] = str(len(data_dict_list))
return res
def __str__(self):
return ('%s: %s' % (self.__class__, self.query))
| [
"def",
"denormalize_formset_dict",
"(",
"data_dict_list",
",",
"formset",
",",
"attr_list",
")",
":",
"assert",
"isinstance",
"(",
"formset",
",",
"BaseSimpleFormSet",
")",
"res",
"=",
"django",
".",
"http",
".",
"QueryDict",
"(",
"''",
",",
"mutable",
"=",
"True",
")",
"for",
"(",
"i",
",",
"data_dict",
")",
"in",
"enumerate",
"(",
"data_dict_list",
")",
":",
"prefix",
"=",
"formset",
".",
"make_prefix",
"(",
"i",
")",
"form",
"=",
"formset",
".",
"form",
"(",
"prefix",
"=",
"prefix",
")",
"res",
".",
"update",
"(",
"denormalize_form_dict",
"(",
"data_dict",
",",
"form",
",",
"attr_list",
")",
")",
"res",
"[",
"(",
"prefix",
"+",
"'-_exists'",
")",
"]",
"=",
"'True'",
"res",
"[",
"str",
"(",
"formset",
".",
"management_form",
".",
"add_prefix",
"(",
"'next_form_id'",
")",
")",
"]",
"=",
"str",
"(",
"len",
"(",
"data_dict_list",
")",
")",
"return",
"res",
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"(",
"'%s: %s'",
"%",
"(",
"self",
".",
"__class__",
",",
"self",
".",
"query",
")",
")"
] | denormalize_formset_dict -> a querydict with the attributes set . | train | false |
41,798 | def is_valid_file(parser, file_name):
if (not os.path.exists(file_name)):
parser.error("The file '{}' does not exist!".format(file_name))
sys.exit(1)
| [
"def",
"is_valid_file",
"(",
"parser",
",",
"file_name",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_name",
")",
")",
":",
"parser",
".",
"error",
"(",
"\"The file '{}' does not exist!\"",
".",
"format",
"(",
"file_name",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | ensure that the input_file exists . | train | false |
41,799 | def _toledo8217StatusParse(status):
(weight, weight_info) = (None, None)
stat = ord(status[(status.index('?') + 1)])
if (stat == 0):
weight_info = 'ok'
else:
weight_info = []
if (stat & 1):
weight_info.append('moving')
if (stat & (1 << 1)):
weight_info.append('over_capacity')
if (stat & (1 << 2)):
weight_info.append('negative')
weight = 0.0
if (stat & (1 << 3)):
weight_info.append('outside_zero_capture_range')
if (stat & (1 << 4)):
weight_info.append('center_of_zero')
if (stat & (1 << 5)):
weight_info.append('net_weight')
return (weight, weight_info)
| [
"def",
"_toledo8217StatusParse",
"(",
"status",
")",
":",
"(",
"weight",
",",
"weight_info",
")",
"=",
"(",
"None",
",",
"None",
")",
"stat",
"=",
"ord",
"(",
"status",
"[",
"(",
"status",
".",
"index",
"(",
"'?'",
")",
"+",
"1",
")",
"]",
")",
"if",
"(",
"stat",
"==",
"0",
")",
":",
"weight_info",
"=",
"'ok'",
"else",
":",
"weight_info",
"=",
"[",
"]",
"if",
"(",
"stat",
"&",
"1",
")",
":",
"weight_info",
".",
"append",
"(",
"'moving'",
")",
"if",
"(",
"stat",
"&",
"(",
"1",
"<<",
"1",
")",
")",
":",
"weight_info",
".",
"append",
"(",
"'over_capacity'",
")",
"if",
"(",
"stat",
"&",
"(",
"1",
"<<",
"2",
")",
")",
":",
"weight_info",
".",
"append",
"(",
"'negative'",
")",
"weight",
"=",
"0.0",
"if",
"(",
"stat",
"&",
"(",
"1",
"<<",
"3",
")",
")",
":",
"weight_info",
".",
"append",
"(",
"'outside_zero_capture_range'",
")",
"if",
"(",
"stat",
"&",
"(",
"1",
"<<",
"4",
")",
")",
":",
"weight_info",
".",
"append",
"(",
"'center_of_zero'",
")",
"if",
"(",
"stat",
"&",
"(",
"1",
"<<",
"5",
")",
")",
":",
"weight_info",
".",
"append",
"(",
"'net_weight'",
")",
"return",
"(",
"weight",
",",
"weight_info",
")"
] | parse a scales status . | train | false |
41,800 | def delete_all_but(path, pages):
podofo = get_podofo()
p = podofo.PDFDoc()
with open(path, 'rb') as f:
raw = f.read()
p.load(raw)
total = p.page_count()
pages = {((total + x) if (x < 0) else x) for x in pages}
for page in xrange((total - 1), (-1), (-1)):
if (page not in pages):
p.delete_page(page)
with open(path, 'wb') as f:
f.save_to_fileobj(path)
| [
"def",
"delete_all_but",
"(",
"path",
",",
"pages",
")",
":",
"podofo",
"=",
"get_podofo",
"(",
")",
"p",
"=",
"podofo",
".",
"PDFDoc",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"raw",
"=",
"f",
".",
"read",
"(",
")",
"p",
".",
"load",
"(",
"raw",
")",
"total",
"=",
"p",
".",
"page_count",
"(",
")",
"pages",
"=",
"{",
"(",
"(",
"total",
"+",
"x",
")",
"if",
"(",
"x",
"<",
"0",
")",
"else",
"x",
")",
"for",
"x",
"in",
"pages",
"}",
"for",
"page",
"in",
"xrange",
"(",
"(",
"total",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
")",
":",
"if",
"(",
"page",
"not",
"in",
"pages",
")",
":",
"p",
".",
"delete_page",
"(",
"page",
")",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"save_to_fileobj",
"(",
"path",
")"
] | delete all the pages in the pdf except for the specified ones . | train | false |
41,801 | def _add_tags(conn, load_balancer_names, tags):
params = {}
conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d')
_build_tag_param_list(params, tags)
return conn.get_status('AddTags', params, verb='POST')
| [
"def",
"_add_tags",
"(",
"conn",
",",
"load_balancer_names",
",",
"tags",
")",
":",
"params",
"=",
"{",
"}",
"conn",
".",
"build_list_params",
"(",
"params",
",",
"load_balancer_names",
",",
"'LoadBalancerNames.member.%d'",
")",
"_build_tag_param_list",
"(",
"params",
",",
"tags",
")",
"return",
"conn",
".",
"get_status",
"(",
"'AddTags'",
",",
"params",
",",
"verb",
"=",
"'POST'",
")"
] | create new metadata tags for the specified resource ids . | train | true |
41,802 | def idzr_asvd(A, k):
A = np.asfortranarray(A)
(m, n) = A.shape
w = np.empty((((((((2 * k) + 22) * m) + (((6 * k) + 21) * n)) + (8 * (k ** 2))) + (10 * k)) + 90), dtype='complex128', order='F')
w_ = idzr_aidi(m, n, k)
w[:w_.size] = w_
(U, V, S, ier) = _id.idzr_asvd(A, k, w)
if ier:
raise _RETCODE_ERROR
return (U, V, S)
| [
"def",
"idzr_asvd",
"(",
"A",
",",
"k",
")",
":",
"A",
"=",
"np",
".",
"asfortranarray",
"(",
"A",
")",
"(",
"m",
",",
"n",
")",
"=",
"A",
".",
"shape",
"w",
"=",
"np",
".",
"empty",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"2",
"*",
"k",
")",
"+",
"22",
")",
"*",
"m",
")",
"+",
"(",
"(",
"(",
"6",
"*",
"k",
")",
"+",
"21",
")",
"*",
"n",
")",
")",
"+",
"(",
"8",
"*",
"(",
"k",
"**",
"2",
")",
")",
")",
"+",
"(",
"10",
"*",
"k",
")",
")",
"+",
"90",
")",
",",
"dtype",
"=",
"'complex128'",
",",
"order",
"=",
"'F'",
")",
"w_",
"=",
"idzr_aidi",
"(",
"m",
",",
"n",
",",
"k",
")",
"w",
"[",
":",
"w_",
".",
"size",
"]",
"=",
"w_",
"(",
"U",
",",
"V",
",",
"S",
",",
"ier",
")",
"=",
"_id",
".",
"idzr_asvd",
"(",
"A",
",",
"k",
",",
"w",
")",
"if",
"ier",
":",
"raise",
"_RETCODE_ERROR",
"return",
"(",
"U",
",",
"V",
",",
"S",
")"
] | compute svd of a complex matrix to a specified rank using random sampling . | train | false |
41,803 | def validate_users(form, field=u'users'):
local_site = form.cleaned_data[u'local_site']
users = form.cleaned_data.get(field, [])
if local_site:
for user in users:
if (not user.local_site.filter(pk=local_site.pk).exists()):
raise ValidationError([(_(u'The user %s is not a member of this site.') % user.username)])
return users
| [
"def",
"validate_users",
"(",
"form",
",",
"field",
"=",
"u'users'",
")",
":",
"local_site",
"=",
"form",
".",
"cleaned_data",
"[",
"u'local_site'",
"]",
"users",
"=",
"form",
".",
"cleaned_data",
".",
"get",
"(",
"field",
",",
"[",
"]",
")",
"if",
"local_site",
":",
"for",
"user",
"in",
"users",
":",
"if",
"(",
"not",
"user",
".",
"local_site",
".",
"filter",
"(",
"pk",
"=",
"local_site",
".",
"pk",
")",
".",
"exists",
"(",
")",
")",
":",
"raise",
"ValidationError",
"(",
"[",
"(",
"_",
"(",
"u'The user %s is not a member of this site.'",
")",
"%",
"user",
".",
"username",
")",
"]",
")",
"return",
"users"
] | validates that the users all have valid . | train | false |
41,804 | def get_data_dir():
this_dir = os.path.dirname(__file__)
data_dir = os.path.join(this_dir, 'data')
return data_dir
| [
"def",
"get_data_dir",
"(",
")",
":",
"this_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"data_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"this_dir",
",",
"'data'",
")",
"return",
"data_dir"
] | return directory where data is stored . | train | false |
41,807 | def detrend_none(x):
return x
| [
"def",
"detrend_none",
"(",
"x",
")",
":",
"return",
"x"
] | return x: no detrending . | train | false |
41,808 | def read_packed_refs(f):
for l in f:
if l.startswith('#'):
continue
if l.startswith('^'):
raise PackedRefsException('found peeled ref in packed-refs without peeled')
(yield _split_ref_line(l))
| [
"def",
"read_packed_refs",
"(",
"f",
")",
":",
"for",
"l",
"in",
"f",
":",
"if",
"l",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"if",
"l",
".",
"startswith",
"(",
"'^'",
")",
":",
"raise",
"PackedRefsException",
"(",
"'found peeled ref in packed-refs without peeled'",
")",
"(",
"yield",
"_split_ref_line",
"(",
"l",
")",
")"
] | read a packed refs file . | train | false |
41,809 | def calc_min_interval(x, alpha):
n = len(x)
cred_mass = (1.0 - alpha)
interval_idx_inc = int(np.floor((cred_mass * n)))
n_intervals = (n - interval_idx_inc)
interval_width = (x[interval_idx_inc:] - x[:n_intervals])
if (len(interval_width) == 0):
raise ValueError('Too few elements for interval calculation')
min_idx = np.argmin(interval_width)
hdi_min = x[min_idx]
hdi_max = x[(min_idx + interval_idx_inc)]
return (hdi_min, hdi_max)
| [
"def",
"calc_min_interval",
"(",
"x",
",",
"alpha",
")",
":",
"n",
"=",
"len",
"(",
"x",
")",
"cred_mass",
"=",
"(",
"1.0",
"-",
"alpha",
")",
"interval_idx_inc",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"(",
"cred_mass",
"*",
"n",
")",
")",
")",
"n_intervals",
"=",
"(",
"n",
"-",
"interval_idx_inc",
")",
"interval_width",
"=",
"(",
"x",
"[",
"interval_idx_inc",
":",
"]",
"-",
"x",
"[",
":",
"n_intervals",
"]",
")",
"if",
"(",
"len",
"(",
"interval_width",
")",
"==",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'Too few elements for interval calculation'",
")",
"min_idx",
"=",
"np",
".",
"argmin",
"(",
"interval_width",
")",
"hdi_min",
"=",
"x",
"[",
"min_idx",
"]",
"hdi_max",
"=",
"x",
"[",
"(",
"min_idx",
"+",
"interval_idx_inc",
")",
"]",
"return",
"(",
"hdi_min",
",",
"hdi_max",
")"
] | internal method to determine the minimum interval of a given width assumes that x is sorted numpy array . | train | true |
41,810 | def format_function_signature(func):
signature = get_function_signature(func)
args_text = []
for arg_name in signature['arg_names']:
if (arg_name in signature['arg_defaults']):
arg_default = signature['arg_defaults'][arg_name]
arg_text_template = '%(arg_name)s=%(arg_default)r'
else:
arg_text_template = '%(arg_name)s'
args_text.append((arg_text_template % vars()))
if ('var_args' in signature):
args_text.append(('*%(var_args)s' % signature))
if ('var_kw_args' in signature):
args_text.append(('**%(var_kw_args)s' % signature))
signature_args_text = ', '.join(args_text)
func_name = signature['name']
signature_text = ('%(func_name)s(%(signature_args_text)s)' % vars())
return signature_text
| [
"def",
"format_function_signature",
"(",
"func",
")",
":",
"signature",
"=",
"get_function_signature",
"(",
"func",
")",
"args_text",
"=",
"[",
"]",
"for",
"arg_name",
"in",
"signature",
"[",
"'arg_names'",
"]",
":",
"if",
"(",
"arg_name",
"in",
"signature",
"[",
"'arg_defaults'",
"]",
")",
":",
"arg_default",
"=",
"signature",
"[",
"'arg_defaults'",
"]",
"[",
"arg_name",
"]",
"arg_text_template",
"=",
"'%(arg_name)s=%(arg_default)r'",
"else",
":",
"arg_text_template",
"=",
"'%(arg_name)s'",
"args_text",
".",
"append",
"(",
"(",
"arg_text_template",
"%",
"vars",
"(",
")",
")",
")",
"if",
"(",
"'var_args'",
"in",
"signature",
")",
":",
"args_text",
".",
"append",
"(",
"(",
"'*%(var_args)s'",
"%",
"signature",
")",
")",
"if",
"(",
"'var_kw_args'",
"in",
"signature",
")",
":",
"args_text",
".",
"append",
"(",
"(",
"'**%(var_kw_args)s'",
"%",
"signature",
")",
")",
"signature_args_text",
"=",
"', '",
".",
"join",
"(",
"args_text",
")",
"func_name",
"=",
"signature",
"[",
"'name'",
"]",
"signature_text",
"=",
"(",
"'%(func_name)s(%(signature_args_text)s)'",
"%",
"vars",
"(",
")",
")",
"return",
"signature_text"
] | format the function signature as printable text . | train | false |
41,813 | def get_subhash(hash):
idx = [14, 3, 6, 8, 2]
mul = [2, 2, 5, 4, 3]
add = [0, 13, 16, 11, 5]
b = []
for i in range(len(idx)):
a = add[i]
m = mul[i]
i = idx[i]
t = (a + int(hash[i], 16))
v = int(hash[t:(t + 2)], 16)
b.append(('%x' % (v * m))[(-1)])
return ''.join(b)
| [
"def",
"get_subhash",
"(",
"hash",
")",
":",
"idx",
"=",
"[",
"14",
",",
"3",
",",
"6",
",",
"8",
",",
"2",
"]",
"mul",
"=",
"[",
"2",
",",
"2",
",",
"5",
",",
"4",
",",
"3",
"]",
"add",
"=",
"[",
"0",
",",
"13",
",",
"16",
",",
"11",
",",
"5",
"]",
"b",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"idx",
")",
")",
":",
"a",
"=",
"add",
"[",
"i",
"]",
"m",
"=",
"mul",
"[",
"i",
"]",
"i",
"=",
"idx",
"[",
"i",
"]",
"t",
"=",
"(",
"a",
"+",
"int",
"(",
"hash",
"[",
"i",
"]",
",",
"16",
")",
")",
"v",
"=",
"int",
"(",
"hash",
"[",
"t",
":",
"(",
"t",
"+",
"2",
")",
"]",
",",
"16",
")",
"b",
".",
"append",
"(",
"(",
"'%x'",
"%",
"(",
"v",
"*",
"m",
")",
")",
"[",
"(",
"-",
"1",
")",
"]",
")",
"return",
"''",
".",
"join",
"(",
"b",
")"
] | get a second hash based on napiprojekts hash . | train | true |
41,814 | @register(u'print-last-kbd-macro')
def print_last_kbd_macro(event):
def print_macro():
for k in event.cli.input_processor.macro:
print k
event.cli.run_in_terminal(print_macro)
| [
"@",
"register",
"(",
"u'print-last-kbd-macro'",
")",
"def",
"print_last_kbd_macro",
"(",
"event",
")",
":",
"def",
"print_macro",
"(",
")",
":",
"for",
"k",
"in",
"event",
".",
"cli",
".",
"input_processor",
".",
"macro",
":",
"print",
"k",
"event",
".",
"cli",
".",
"run_in_terminal",
"(",
"print_macro",
")"
] | print the last keboard macro . | train | true |
41,815 | def pltacorr(self, x, **kwargs):
return self.xcorr(x, x, **kwargs)
| [
"def",
"pltacorr",
"(",
"self",
",",
"x",
",",
"**",
"kwargs",
")",
":",
"return",
"self",
".",
"xcorr",
"(",
"x",
",",
"x",
",",
"**",
"kwargs",
")"
] | call signature:: acorr plot the autocorrelation of *x* . | train | false |
41,816 | def dev_mode(request):
return render_to_response('dev/dev_mode.html')
| [
"def",
"dev_mode",
"(",
"request",
")",
":",
"return",
"render_to_response",
"(",
"'dev/dev_mode.html'",
")"
] | sample static view . | train | false |
41,817 | def PrepareSpecialPropertiesForLoad(entity_proto):
_PrepareSpecialProperties(entity_proto, True)
| [
"def",
"PrepareSpecialPropertiesForLoad",
"(",
"entity_proto",
")",
":",
"_PrepareSpecialProperties",
"(",
"entity_proto",
",",
"True",
")"
] | computes special properties that are user-visible . | train | false |
41,819 | def Application_BeginRequest(app, e):
pass
| [
"def",
"Application_BeginRequest",
"(",
"app",
",",
"e",
")",
":",
"pass"
] | code that runs at the beginning of each request . | train | false |
41,821 | def safeseq(value):
return [mark_safe(force_unicode(obj)) for obj in value]
| [
"def",
"safeseq",
"(",
"value",
")",
":",
"return",
"[",
"mark_safe",
"(",
"force_unicode",
"(",
"obj",
")",
")",
"for",
"obj",
"in",
"value",
"]"
] | a "safe" filter for sequences . | train | false |
41,822 | def test_read_weird():
table = '\n Col1 | Col2 |\n 1.2 "hello"\n 2.4 sdf\'s worlds\n'
reader = ascii.get_reader(Reader=ascii.FixedWidth)
dat = reader.read(table)
assert_equal(dat.colnames, ['Col1', 'Col2'])
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hel')
assert_equal(dat[1][1], "df's wo")
| [
"def",
"test_read_weird",
"(",
")",
":",
"table",
"=",
"'\\n Col1 | Col2 |\\n 1.2 \"hello\"\\n 2.4 sdf\\'s worlds\\n'",
"reader",
"=",
"ascii",
".",
"get_reader",
"(",
"Reader",
"=",
"ascii",
".",
"FixedWidth",
")",
"dat",
"=",
"reader",
".",
"read",
"(",
"table",
")",
"assert_equal",
"(",
"dat",
".",
"colnames",
",",
"[",
"'Col1'",
",",
"'Col2'",
"]",
")",
"assert_almost_equal",
"(",
"dat",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"2.4",
")",
"assert_equal",
"(",
"dat",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"'\"hel'",
")",
"assert_equal",
"(",
"dat",
"[",
"1",
"]",
"[",
"1",
"]",
",",
"\"df's wo\"",
")"
] | weird input table with data values chopped by col extent . | train | false |
41,823 | def filter_testsuite(suite, matcher, level=None):
if (not isinstance(suite, unittest.TestSuite)):
raise TypeError('not a TestSuite', suite)
results = []
for test in suite._tests:
if ((level is not None) and (getattr(test, 'level', 0) > level)):
continue
if isinstance(test, unittest.TestCase):
testname = test.id()
if matcher(testname):
results.append(test)
else:
filtered = filter_testsuite(test, matcher, level)
results.extend(filtered)
return results
| [
"def",
"filter_testsuite",
"(",
"suite",
",",
"matcher",
",",
"level",
"=",
"None",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"suite",
",",
"unittest",
".",
"TestSuite",
")",
")",
":",
"raise",
"TypeError",
"(",
"'not a TestSuite'",
",",
"suite",
")",
"results",
"=",
"[",
"]",
"for",
"test",
"in",
"suite",
".",
"_tests",
":",
"if",
"(",
"(",
"level",
"is",
"not",
"None",
")",
"and",
"(",
"getattr",
"(",
"test",
",",
"'level'",
",",
"0",
")",
">",
"level",
")",
")",
":",
"continue",
"if",
"isinstance",
"(",
"test",
",",
"unittest",
".",
"TestCase",
")",
":",
"testname",
"=",
"test",
".",
"id",
"(",
")",
"if",
"matcher",
"(",
"testname",
")",
":",
"results",
".",
"append",
"(",
"test",
")",
"else",
":",
"filtered",
"=",
"filter_testsuite",
"(",
"test",
",",
"matcher",
",",
"level",
")",
"results",
".",
"extend",
"(",
"filtered",
")",
"return",
"results"
] | returns a flattened list of test cases that match the given matcher . | train | false |
41,824 | def _load_backend_classes(base_class=BaseAuth):
for class_path in settings.AUTHENTICATION_BACKENDS:
auth_class = module_member(class_path)
if issubclass(auth_class, base_class):
(yield auth_class)
| [
"def",
"_load_backend_classes",
"(",
"base_class",
"=",
"BaseAuth",
")",
":",
"for",
"class_path",
"in",
"settings",
".",
"AUTHENTICATION_BACKENDS",
":",
"auth_class",
"=",
"module_member",
"(",
"class_path",
")",
"if",
"issubclass",
"(",
"auth_class",
",",
"base_class",
")",
":",
"(",
"yield",
"auth_class",
")"
] | load the list of python-social-auth backend classes from django settings . | train | false |
41,825 | @contextmanager
def all_warnings():
frame = inspect.currentframe()
if frame:
for f in inspect.getouterframes(frame):
f[0].f_locals['__warningregistry__'] = {}
del frame
for (mod_name, mod) in list(sys.modules.items()):
if ('six.moves' in mod_name):
continue
try:
mod.__warningregistry__.clear()
except AttributeError:
pass
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
(yield w)
| [
"@",
"contextmanager",
"def",
"all_warnings",
"(",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"if",
"frame",
":",
"for",
"f",
"in",
"inspect",
".",
"getouterframes",
"(",
"frame",
")",
":",
"f",
"[",
"0",
"]",
".",
"f_locals",
"[",
"'__warningregistry__'",
"]",
"=",
"{",
"}",
"del",
"frame",
"for",
"(",
"mod_name",
",",
"mod",
")",
"in",
"list",
"(",
"sys",
".",
"modules",
".",
"items",
"(",
")",
")",
":",
"if",
"(",
"'six.moves'",
"in",
"mod_name",
")",
":",
"continue",
"try",
":",
"mod",
".",
"__warningregistry__",
".",
"clear",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
"as",
"w",
":",
"warnings",
".",
"simplefilter",
"(",
"'always'",
")",
"(",
"yield",
"w",
")"
] | context for use in testing to ensure that all warnings are raised . | train | false |
41,826 | def logprob(predictions, labels):
predictions[(predictions < 1e-10)] = 1e-10
return (np.sum(np.multiply(labels, (- np.log(predictions)))) / labels.shape[0])
| [
"def",
"logprob",
"(",
"predictions",
",",
"labels",
")",
":",
"predictions",
"[",
"(",
"predictions",
"<",
"1e-10",
")",
"]",
"=",
"1e-10",
"return",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"multiply",
"(",
"labels",
",",
"(",
"-",
"np",
".",
"log",
"(",
"predictions",
")",
")",
")",
")",
"/",
"labels",
".",
"shape",
"[",
"0",
"]",
")"
] | log-probability of the true labels in a predicted batch . | train | false |
41,827 | def urlfetch(request):
http_client = tornado.httpclient.HTTPClient()
try:
response = http_client.fetch(request)
result = {JSONTags.SUCCESS: True, JSONTags.BODY: response.body}
except tornado.httpclient.HTTPError as http_error:
logging.error("Error while trying to fetch '{0}': {1}".format(request.url, str(http_error)))
result = {JSONTags.SUCCESS: False, JSONTags.REASON: hermes_constants.HTTPError}
except Exception as exception:
logging.exception("Exception while trying to fetch '{0}': {1}".format(request.url, str(exception)))
result = {JSONTags.SUCCESS: False, JSONTags.REASON: str(exception)}
http_client.close()
return result
| [
"def",
"urlfetch",
"(",
"request",
")",
":",
"http_client",
"=",
"tornado",
".",
"httpclient",
".",
"HTTPClient",
"(",
")",
"try",
":",
"response",
"=",
"http_client",
".",
"fetch",
"(",
"request",
")",
"result",
"=",
"{",
"JSONTags",
".",
"SUCCESS",
":",
"True",
",",
"JSONTags",
".",
"BODY",
":",
"response",
".",
"body",
"}",
"except",
"tornado",
".",
"httpclient",
".",
"HTTPError",
"as",
"http_error",
":",
"logging",
".",
"error",
"(",
"\"Error while trying to fetch '{0}': {1}\"",
".",
"format",
"(",
"request",
".",
"url",
",",
"str",
"(",
"http_error",
")",
")",
")",
"result",
"=",
"{",
"JSONTags",
".",
"SUCCESS",
":",
"False",
",",
"JSONTags",
".",
"REASON",
":",
"hermes_constants",
".",
"HTTPError",
"}",
"except",
"Exception",
"as",
"exception",
":",
"logging",
".",
"exception",
"(",
"\"Exception while trying to fetch '{0}': {1}\"",
".",
"format",
"(",
"request",
".",
"url",
",",
"str",
"(",
"exception",
")",
")",
")",
"result",
"=",
"{",
"JSONTags",
".",
"SUCCESS",
":",
"False",
",",
"JSONTags",
".",
"REASON",
":",
"str",
"(",
"exception",
")",
"}",
"http_client",
".",
"close",
"(",
")",
"return",
"result"
] | uses a tornado http client to perform http requests . | train | false |
41,828 | def imfilter(arr, ftype):
_tdict = {'blur': ImageFilter.BLUR, 'contour': ImageFilter.CONTOUR, 'detail': ImageFilter.DETAIL, 'edge_enhance': ImageFilter.EDGE_ENHANCE, 'edge_enhance_more': ImageFilter.EDGE_ENHANCE_MORE, 'emboss': ImageFilter.EMBOSS, 'find_edges': ImageFilter.FIND_EDGES, 'smooth': ImageFilter.SMOOTH, 'smooth_more': ImageFilter.SMOOTH_MORE, 'sharpen': ImageFilter.SHARPEN}
im = toimage(arr)
if (ftype not in _tdict):
raise ValueError('Unknown filter type.')
return fromimage(im.filter(_tdict[ftype]))
| [
"def",
"imfilter",
"(",
"arr",
",",
"ftype",
")",
":",
"_tdict",
"=",
"{",
"'blur'",
":",
"ImageFilter",
".",
"BLUR",
",",
"'contour'",
":",
"ImageFilter",
".",
"CONTOUR",
",",
"'detail'",
":",
"ImageFilter",
".",
"DETAIL",
",",
"'edge_enhance'",
":",
"ImageFilter",
".",
"EDGE_ENHANCE",
",",
"'edge_enhance_more'",
":",
"ImageFilter",
".",
"EDGE_ENHANCE_MORE",
",",
"'emboss'",
":",
"ImageFilter",
".",
"EMBOSS",
",",
"'find_edges'",
":",
"ImageFilter",
".",
"FIND_EDGES",
",",
"'smooth'",
":",
"ImageFilter",
".",
"SMOOTH",
",",
"'smooth_more'",
":",
"ImageFilter",
".",
"SMOOTH_MORE",
",",
"'sharpen'",
":",
"ImageFilter",
".",
"SHARPEN",
"}",
"im",
"=",
"toimage",
"(",
"arr",
")",
"if",
"(",
"ftype",
"not",
"in",
"_tdict",
")",
":",
"raise",
"ValueError",
"(",
"'Unknown filter type.'",
")",
"return",
"fromimage",
"(",
"im",
".",
"filter",
"(",
"_tdict",
"[",
"ftype",
"]",
")",
")"
] | simple filtering of an image . | train | false |
41,829 | def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config):
if all(((config in product_data) for config in _OAUTH2_INSTALLED_APP_KEYS)):
oauth2_args = [product_data['client_id'], product_data['client_secret'], product_data['refresh_token']]
oauth2_client = googleads.oauth2.GoogleRefreshTokenClient
for key in _OAUTH2_INSTALLED_APP_KEYS:
del product_data[key]
elif all(((config in product_data) for config in _OAUTH2_SERVICE_ACCT_KEYS)):
oauth2_args = [googleads.oauth2.GetAPIScope(product_yaml_key), product_data['service_account_email'], product_data['path_to_private_key_file']]
oauth2_client = googleads.oauth2.GoogleServiceAccountClient
for key in _OAUTH2_SERVICE_ACCT_KEYS:
del product_data[key]
else:
raise googleads.errors.GoogleAdsValueError(('Your yaml file is incorrectly configured for OAuth2. You need to specify credentials for either the installed application flow (%s) or service account flow (%s).' % (_OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS)))
return oauth2_client(proxy_config=proxy_config, *oauth2_args)
| [
"def",
"_ExtractOAuth2Client",
"(",
"product_yaml_key",
",",
"product_data",
",",
"proxy_config",
")",
":",
"if",
"all",
"(",
"(",
"(",
"config",
"in",
"product_data",
")",
"for",
"config",
"in",
"_OAUTH2_INSTALLED_APP_KEYS",
")",
")",
":",
"oauth2_args",
"=",
"[",
"product_data",
"[",
"'client_id'",
"]",
",",
"product_data",
"[",
"'client_secret'",
"]",
",",
"product_data",
"[",
"'refresh_token'",
"]",
"]",
"oauth2_client",
"=",
"googleads",
".",
"oauth2",
".",
"GoogleRefreshTokenClient",
"for",
"key",
"in",
"_OAUTH2_INSTALLED_APP_KEYS",
":",
"del",
"product_data",
"[",
"key",
"]",
"elif",
"all",
"(",
"(",
"(",
"config",
"in",
"product_data",
")",
"for",
"config",
"in",
"_OAUTH2_SERVICE_ACCT_KEYS",
")",
")",
":",
"oauth2_args",
"=",
"[",
"googleads",
".",
"oauth2",
".",
"GetAPIScope",
"(",
"product_yaml_key",
")",
",",
"product_data",
"[",
"'service_account_email'",
"]",
",",
"product_data",
"[",
"'path_to_private_key_file'",
"]",
"]",
"oauth2_client",
"=",
"googleads",
".",
"oauth2",
".",
"GoogleServiceAccountClient",
"for",
"key",
"in",
"_OAUTH2_SERVICE_ACCT_KEYS",
":",
"del",
"product_data",
"[",
"key",
"]",
"else",
":",
"raise",
"googleads",
".",
"errors",
".",
"GoogleAdsValueError",
"(",
"(",
"'Your yaml file is incorrectly configured for OAuth2. You need to specify credentials for either the installed application flow (%s) or service account flow (%s).'",
"%",
"(",
"_OAUTH2_INSTALLED_APP_KEYS",
",",
"_OAUTH2_SERVICE_ACCT_KEYS",
")",
")",
")",
"return",
"oauth2_client",
"(",
"proxy_config",
"=",
"proxy_config",
",",
"*",
"oauth2_args",
")"
] | generates an googleoauth2client subclass using the given product_data . | train | false |
41,830 | def test_solved_steps_also_have_scenario_as_attribute():
scenario = Scenario.from_string(OUTLINED_SCENARIO)
for step in scenario.solved_steps:
assert_equals(step.scenario, scenario)
| [
"def",
"test_solved_steps_also_have_scenario_as_attribute",
"(",
")",
":",
"scenario",
"=",
"Scenario",
".",
"from_string",
"(",
"OUTLINED_SCENARIO",
")",
"for",
"step",
"in",
"scenario",
".",
"solved_steps",
":",
"assert_equals",
"(",
"step",
".",
"scenario",
",",
"scenario",
")"
] | steps solved in scenario outlines also have scenario as attribute . | train | false |
41,831 | def send_job_review_message(job, user, subject_template_path, message_template_path):
subject_template = loader.get_template(subject_template_path)
message_template = loader.get_template(message_template_path)
if (user.first_name or user.last_name):
reviewer_name = '{} {}'.format(user.first_name, user.last_name)
else:
reviewer_name = 'Community Reviewer'
message_context = Context({'reviewer_name': reviewer_name, 'content_object': job, 'site': Site.objects.get_current()})
subject = subject_template.render(message_context).strip()
message = message_template.render(message_context)
send_mail(subject, message, settings.JOB_FROM_EMAIL, [job.email, EMAIL_JOBS_BOARD])
| [
"def",
"send_job_review_message",
"(",
"job",
",",
"user",
",",
"subject_template_path",
",",
"message_template_path",
")",
":",
"subject_template",
"=",
"loader",
".",
"get_template",
"(",
"subject_template_path",
")",
"message_template",
"=",
"loader",
".",
"get_template",
"(",
"message_template_path",
")",
"if",
"(",
"user",
".",
"first_name",
"or",
"user",
".",
"last_name",
")",
":",
"reviewer_name",
"=",
"'{} {}'",
".",
"format",
"(",
"user",
".",
"first_name",
",",
"user",
".",
"last_name",
")",
"else",
":",
"reviewer_name",
"=",
"'Community Reviewer'",
"message_context",
"=",
"Context",
"(",
"{",
"'reviewer_name'",
":",
"reviewer_name",
",",
"'content_object'",
":",
"job",
",",
"'site'",
":",
"Site",
".",
"objects",
".",
"get_current",
"(",
")",
"}",
")",
"subject",
"=",
"subject_template",
".",
"render",
"(",
"message_context",
")",
".",
"strip",
"(",
")",
"message",
"=",
"message_template",
".",
"render",
"(",
"message_context",
")",
"send_mail",
"(",
"subject",
",",
"message",
",",
"settings",
".",
"JOB_FROM_EMAIL",
",",
"[",
"job",
".",
"email",
",",
"EMAIL_JOBS_BOARD",
"]",
")"
] | helper function wrapping logic of sending the review message concerning a job . | train | false |
41,832 | def flatten_response(content):
return ''.join((_force_utf8(x) for x in tup(content) if x))
| [
"def",
"flatten_response",
"(",
"content",
")",
":",
"return",
"''",
".",
"join",
"(",
"(",
"_force_utf8",
"(",
"x",
")",
"for",
"x",
"in",
"tup",
"(",
"content",
")",
"if",
"x",
")",
")"
] | convert a content iterable to a string . | train | false |
41,833 | def cleandoc(doc):
try:
lines = string.split(string.expandtabs(doc), '\n')
except UnicodeError:
return None
else:
margin = sys.maxint
for line in lines[1:]:
content = len(string.lstrip(line))
if content:
indent = (len(line) - content)
margin = min(margin, indent)
if lines:
lines[0] = lines[0].lstrip()
if (margin < sys.maxint):
for i in range(1, len(lines)):
lines[i] = lines[i][margin:]
while (lines and (not lines[(-1)])):
lines.pop()
while (lines and (not lines[0])):
lines.pop(0)
return string.join(lines, '\n')
| [
"def",
"cleandoc",
"(",
"doc",
")",
":",
"try",
":",
"lines",
"=",
"string",
".",
"split",
"(",
"string",
".",
"expandtabs",
"(",
"doc",
")",
",",
"'\\n'",
")",
"except",
"UnicodeError",
":",
"return",
"None",
"else",
":",
"margin",
"=",
"sys",
".",
"maxint",
"for",
"line",
"in",
"lines",
"[",
"1",
":",
"]",
":",
"content",
"=",
"len",
"(",
"string",
".",
"lstrip",
"(",
"line",
")",
")",
"if",
"content",
":",
"indent",
"=",
"(",
"len",
"(",
"line",
")",
"-",
"content",
")",
"margin",
"=",
"min",
"(",
"margin",
",",
"indent",
")",
"if",
"lines",
":",
"lines",
"[",
"0",
"]",
"=",
"lines",
"[",
"0",
"]",
".",
"lstrip",
"(",
")",
"if",
"(",
"margin",
"<",
"sys",
".",
"maxint",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"lines",
")",
")",
":",
"lines",
"[",
"i",
"]",
"=",
"lines",
"[",
"i",
"]",
"[",
"margin",
":",
"]",
"while",
"(",
"lines",
"and",
"(",
"not",
"lines",
"[",
"(",
"-",
"1",
")",
"]",
")",
")",
":",
"lines",
".",
"pop",
"(",
")",
"while",
"(",
"lines",
"and",
"(",
"not",
"lines",
"[",
"0",
"]",
")",
")",
":",
"lines",
".",
"pop",
"(",
"0",
")",
"return",
"string",
".",
"join",
"(",
"lines",
",",
"'\\n'",
")"
] | clean up indentation from docstrings . | train | false |
41,834 | def ramsey_R2(G):
if (not G):
return (set(), set())
node = arbitrary_element(G)
nbrs = nx.all_neighbors(G, node)
nnbrs = nx.non_neighbors(G, node)
(c_1, i_1) = ramsey_R2(G.subgraph(nbrs))
(c_2, i_2) = ramsey_R2(G.subgraph(nnbrs))
c_1.add(node)
i_2.add(node)
return (max(c_1, c_2, key=len), max(i_1, i_2, key=len))
| [
"def",
"ramsey_R2",
"(",
"G",
")",
":",
"if",
"(",
"not",
"G",
")",
":",
"return",
"(",
"set",
"(",
")",
",",
"set",
"(",
")",
")",
"node",
"=",
"arbitrary_element",
"(",
"G",
")",
"nbrs",
"=",
"nx",
".",
"all_neighbors",
"(",
"G",
",",
"node",
")",
"nnbrs",
"=",
"nx",
".",
"non_neighbors",
"(",
"G",
",",
"node",
")",
"(",
"c_1",
",",
"i_1",
")",
"=",
"ramsey_R2",
"(",
"G",
".",
"subgraph",
"(",
"nbrs",
")",
")",
"(",
"c_2",
",",
"i_2",
")",
"=",
"ramsey_R2",
"(",
"G",
".",
"subgraph",
"(",
"nnbrs",
")",
")",
"c_1",
".",
"add",
"(",
"node",
")",
"i_2",
".",
"add",
"(",
"node",
")",
"return",
"(",
"max",
"(",
"c_1",
",",
"c_2",
",",
"key",
"=",
"len",
")",
",",
"max",
"(",
"i_1",
",",
"i_2",
",",
"key",
"=",
"len",
")",
")"
] | approximately computes the ramsey number r for graph . | train | false |
41,835 | def accepts_content_type(request, content_type):
if (not hasattr(request, 'headers')):
return False
accept = request.headers.get('accept', None)
if (not accept):
return None
return (content_type in str(accept))
| [
"def",
"accepts_content_type",
"(",
"request",
",",
"content_type",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"request",
",",
"'headers'",
")",
")",
":",
"return",
"False",
"accept",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'accept'",
",",
"None",
")",
"if",
"(",
"not",
"accept",
")",
":",
"return",
"None",
"return",
"(",
"content_type",
"in",
"str",
"(",
"accept",
")",
")"
] | determine if the request wants the given content_type as a response . | train | false |
41,837 | def get_python_os_info():
info = platform.system_alias(platform.system(), platform.release(), platform.version())
(os_type, os_ver, _) = info
os_type = os_type.lower()
if os_type.startswith('linux'):
info = platform.linux_distribution()
if info[0]:
os_type = info[0]
if info[1]:
os_ver = info[1]
elif os_type.startswith('darwin'):
os_ver = subprocess.Popen(['sw_vers', '-productVersion'], stdout=subprocess.PIPE).communicate()[0].rstrip('\n')
elif os_type.startswith('freebsd'):
os_ver = os_ver.partition('-')[0]
os_ver = os_ver.partition('.')[0]
elif platform.win32_ver()[1]:
os_ver = platform.win32_ver()[1]
else:
os_ver = ''
return (os_type, os_ver)
| [
"def",
"get_python_os_info",
"(",
")",
":",
"info",
"=",
"platform",
".",
"system_alias",
"(",
"platform",
".",
"system",
"(",
")",
",",
"platform",
".",
"release",
"(",
")",
",",
"platform",
".",
"version",
"(",
")",
")",
"(",
"os_type",
",",
"os_ver",
",",
"_",
")",
"=",
"info",
"os_type",
"=",
"os_type",
".",
"lower",
"(",
")",
"if",
"os_type",
".",
"startswith",
"(",
"'linux'",
")",
":",
"info",
"=",
"platform",
".",
"linux_distribution",
"(",
")",
"if",
"info",
"[",
"0",
"]",
":",
"os_type",
"=",
"info",
"[",
"0",
"]",
"if",
"info",
"[",
"1",
"]",
":",
"os_ver",
"=",
"info",
"[",
"1",
"]",
"elif",
"os_type",
".",
"startswith",
"(",
"'darwin'",
")",
":",
"os_ver",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'sw_vers'",
",",
"'-productVersion'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"elif",
"os_type",
".",
"startswith",
"(",
"'freebsd'",
")",
":",
"os_ver",
"=",
"os_ver",
".",
"partition",
"(",
"'-'",
")",
"[",
"0",
"]",
"os_ver",
"=",
"os_ver",
".",
"partition",
"(",
"'.'",
")",
"[",
"0",
"]",
"elif",
"platform",
".",
"win32_ver",
"(",
")",
"[",
"1",
"]",
":",
"os_ver",
"=",
"platform",
".",
"win32_ver",
"(",
")",
"[",
"1",
"]",
"else",
":",
"os_ver",
"=",
"''",
"return",
"(",
"os_type",
",",
"os_ver",
")"
] | get operating system type/distribution and major version using python platform module :returns: :rtype: tuple of str . | train | false |
41,838 | def migrate_vm(vm_object, host_object):
relocate_spec = vim.vm.RelocateSpec(host=host_object)
task_object = vm_object.Relocate(relocate_spec)
return task_object
| [
"def",
"migrate_vm",
"(",
"vm_object",
",",
"host_object",
")",
":",
"relocate_spec",
"=",
"vim",
".",
"vm",
".",
"RelocateSpec",
"(",
"host",
"=",
"host_object",
")",
"task_object",
"=",
"vm_object",
".",
"Relocate",
"(",
"relocate_spec",
")",
"return",
"task_object"
] | migrate virtual machine and return the task . | train | false |
41,839 | def make_xontribs_wiz():
md = xontrib_metadata()
pkgs = [md['packages'].get(d.get('package', None), {}) for d in md['xontribs']]
w = _make_flat_wiz(make_xontrib, md['xontribs'], pkgs)
return w
| [
"def",
"make_xontribs_wiz",
"(",
")",
":",
"md",
"=",
"xontrib_metadata",
"(",
")",
"pkgs",
"=",
"[",
"md",
"[",
"'packages'",
"]",
".",
"get",
"(",
"d",
".",
"get",
"(",
"'package'",
",",
"None",
")",
",",
"{",
"}",
")",
"for",
"d",
"in",
"md",
"[",
"'xontribs'",
"]",
"]",
"w",
"=",
"_make_flat_wiz",
"(",
"make_xontrib",
",",
"md",
"[",
"'xontribs'",
"]",
",",
"pkgs",
")",
"return",
"w"
] | makes a xontrib wizard . | train | false |
41,841 | def clean_directory(directory):
if (not os.path.exists(directory)):
return
for entry in os.listdir(directory):
if entry.startswith(u'.'):
continue
path = os.path.join(directory, entry)
if os.path.isdir(path):
shutil.rmtree(path, True)
else:
os.unlink(path)
| [
"def",
"clean_directory",
"(",
"directory",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
")",
":",
"return",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"if",
"entry",
".",
"startswith",
"(",
"u'.'",
")",
":",
"continue",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"entry",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"path",
",",
"True",
")",
"else",
":",
"os",
".",
"unlink",
"(",
"path",
")"
] | remove the content of a directory recursively but not the directory itself . | train | false |
41,842 | def _create_collection(committer_id, collection, commit_message, commit_cmds):
collection.validate(strict=False)
rights_manager.create_new_collection_rights(collection.id, committer_id)
model = collection_models.CollectionModel(id=collection.id, category=collection.category, title=collection.title, objective=collection.objective, language_code=collection.language_code, tags=collection.tags, schema_version=collection.schema_version, nodes=[collection_node.to_dict() for collection_node in collection.nodes])
model.commit(committer_id, commit_message, commit_cmds)
collection.version += 1
create_collection_summary(collection.id, committer_id)
| [
"def",
"_create_collection",
"(",
"committer_id",
",",
"collection",
",",
"commit_message",
",",
"commit_cmds",
")",
":",
"collection",
".",
"validate",
"(",
"strict",
"=",
"False",
")",
"rights_manager",
".",
"create_new_collection_rights",
"(",
"collection",
".",
"id",
",",
"committer_id",
")",
"model",
"=",
"collection_models",
".",
"CollectionModel",
"(",
"id",
"=",
"collection",
".",
"id",
",",
"category",
"=",
"collection",
".",
"category",
",",
"title",
"=",
"collection",
".",
"title",
",",
"objective",
"=",
"collection",
".",
"objective",
",",
"language_code",
"=",
"collection",
".",
"language_code",
",",
"tags",
"=",
"collection",
".",
"tags",
",",
"schema_version",
"=",
"collection",
".",
"schema_version",
",",
"nodes",
"=",
"[",
"collection_node",
".",
"to_dict",
"(",
")",
"for",
"collection_node",
"in",
"collection",
".",
"nodes",
"]",
")",
"model",
".",
"commit",
"(",
"committer_id",
",",
"commit_message",
",",
"commit_cmds",
")",
"collection",
".",
"version",
"+=",
"1",
"create_collection_summary",
"(",
"collection",
".",
"id",
",",
"committer_id",
")"
] | creates a new collection . | train | false |
41,844 | @dispatch(Broadcast, MongoQuery)
def post_compute(e, q, scope=None):
columns = dict(((col, 1) for qry in q.query for col in qry.get('$project', [])))
scope = {'$project': toolz.merge({'_id': 0}, dict(((col, 1) for col in columns)))}
q = q.append(scope)
dicts = get_result(q.coll.aggregate(list(q.query)))
assert (len(columns) == 1)
return list(pluck(first(columns.keys()), dicts))
| [
"@",
"dispatch",
"(",
"Broadcast",
",",
"MongoQuery",
")",
"def",
"post_compute",
"(",
"e",
",",
"q",
",",
"scope",
"=",
"None",
")",
":",
"columns",
"=",
"dict",
"(",
"(",
"(",
"col",
",",
"1",
")",
"for",
"qry",
"in",
"q",
".",
"query",
"for",
"col",
"in",
"qry",
".",
"get",
"(",
"'$project'",
",",
"[",
"]",
")",
")",
")",
"scope",
"=",
"{",
"'$project'",
":",
"toolz",
".",
"merge",
"(",
"{",
"'_id'",
":",
"0",
"}",
",",
"dict",
"(",
"(",
"(",
"col",
",",
"1",
")",
"for",
"col",
"in",
"columns",
")",
")",
")",
"}",
"q",
"=",
"q",
".",
"append",
"(",
"scope",
")",
"dicts",
"=",
"get_result",
"(",
"q",
".",
"coll",
".",
"aggregate",
"(",
"list",
"(",
"q",
".",
"query",
")",
")",
")",
"assert",
"(",
"len",
"(",
"columns",
")",
"==",
"1",
")",
"return",
"list",
"(",
"pluck",
"(",
"first",
"(",
"columns",
".",
"keys",
"(",
")",
")",
",",
"dicts",
")",
")"
] | compute the result of a broadcast expression . | train | false |
41,850 | def additions_installed(name, reboot=False, upgrade_os=False):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_state = __salt__['vbox_guest.additions_version']()
if current_state:
ret['result'] = True
ret['comment'] = 'System already in the correct state'
return ret
if __opts__['test']:
ret['comment'] = 'The state of VirtualBox Guest Additions will be changed.'
ret['changes'] = {'old': current_state, 'new': True}
ret['result'] = None
return ret
new_state = __salt__['vbox_guest.additions_install'](reboot=reboot, upgrade_os=upgrade_os)
ret['comment'] = 'The state of VirtualBox Guest Additions was changed!'
ret['changes'] = {'old': current_state, 'new': new_state}
ret['result'] = bool(new_state)
return ret
| [
"def",
"additions_installed",
"(",
"name",
",",
"reboot",
"=",
"False",
",",
"upgrade_os",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"current_state",
"=",
"__salt__",
"[",
"'vbox_guest.additions_version'",
"]",
"(",
")",
"if",
"current_state",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"'System already in the correct state'",
"return",
"ret",
"if",
"__opts__",
"[",
"'test'",
"]",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'The state of VirtualBox Guest Additions will be changed.'",
"ret",
"[",
"'changes'",
"]",
"=",
"{",
"'old'",
":",
"current_state",
",",
"'new'",
":",
"True",
"}",
"ret",
"[",
"'result'",
"]",
"=",
"None",
"return",
"ret",
"new_state",
"=",
"__salt__",
"[",
"'vbox_guest.additions_install'",
"]",
"(",
"reboot",
"=",
"reboot",
",",
"upgrade_os",
"=",
"upgrade_os",
")",
"ret",
"[",
"'comment'",
"]",
"=",
"'The state of VirtualBox Guest Additions was changed!'",
"ret",
"[",
"'changes'",
"]",
"=",
"{",
"'old'",
":",
"current_state",
",",
"'new'",
":",
"new_state",
"}",
"ret",
"[",
"'result'",
"]",
"=",
"bool",
"(",
"new_state",
")",
"return",
"ret"
] | ensure that the virtualbox guest additions are installed . | train | true |
41,851 | def convert_video_status(video):
now = datetime.now(video['created'].tzinfo)
if ((video['status'] == 'upload') and ((now - video['created']) > timedelta(hours=MAX_UPLOAD_HOURS))):
new_status = 'upload_failed'
status = StatusDisplayStrings.get(new_status)
message = ('Video with id [%s] is still in upload after [%s] hours, setting status to [%s]' % (video['edx_video_id'], MAX_UPLOAD_HOURS, new_status))
send_video_status_update([{'edxVideoId': video['edx_video_id'], 'status': new_status, 'message': message}])
elif (video['status'] == 'invalid_token'):
status = StatusDisplayStrings.get('youtube_duplicate')
else:
status = StatusDisplayStrings.get(video['status'])
return status
| [
"def",
"convert_video_status",
"(",
"video",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
"video",
"[",
"'created'",
"]",
".",
"tzinfo",
")",
"if",
"(",
"(",
"video",
"[",
"'status'",
"]",
"==",
"'upload'",
")",
"and",
"(",
"(",
"now",
"-",
"video",
"[",
"'created'",
"]",
")",
">",
"timedelta",
"(",
"hours",
"=",
"MAX_UPLOAD_HOURS",
")",
")",
")",
":",
"new_status",
"=",
"'upload_failed'",
"status",
"=",
"StatusDisplayStrings",
".",
"get",
"(",
"new_status",
")",
"message",
"=",
"(",
"'Video with id [%s] is still in upload after [%s] hours, setting status to [%s]'",
"%",
"(",
"video",
"[",
"'edx_video_id'",
"]",
",",
"MAX_UPLOAD_HOURS",
",",
"new_status",
")",
")",
"send_video_status_update",
"(",
"[",
"{",
"'edxVideoId'",
":",
"video",
"[",
"'edx_video_id'",
"]",
",",
"'status'",
":",
"new_status",
",",
"'message'",
":",
"message",
"}",
"]",
")",
"elif",
"(",
"video",
"[",
"'status'",
"]",
"==",
"'invalid_token'",
")",
":",
"status",
"=",
"StatusDisplayStrings",
".",
"get",
"(",
"'youtube_duplicate'",
")",
"else",
":",
"status",
"=",
"StatusDisplayStrings",
".",
"get",
"(",
"video",
"[",
"'status'",
"]",
")",
"return",
"status"
] | convert status of a video . | train | false |
41,853 | def runIoThroughNupic(inputData, model, gymName, plot):
inputFile = open(inputData, 'rb')
csvReader = csv.reader(inputFile)
csvReader.next()
csvReader.next()
csvReader.next()
shifter = InferenceShifter()
if plot:
output = nupic_anomaly_output.NuPICPlotOutput(gymName)
else:
output = nupic_anomaly_output.NuPICFileOutput(gymName)
counter = 0
for row in csvReader:
counter += 1
if ((counter % 100) == 0):
print ('Read %i lines...' % counter)
timestamp = datetime.datetime.strptime(row[0], DATE_FORMAT)
consumption = float(row[1])
result = model.run({'timestamp': timestamp, 'kw_energy_consumption': consumption})
if plot:
result = shifter.shift(result)
prediction = result.inferences['multiStepBestPredictions'][1]
anomalyScore = result.inferences['anomalyScore']
output.write(timestamp, consumption, prediction, anomalyScore)
inputFile.close()
output.close()
| [
"def",
"runIoThroughNupic",
"(",
"inputData",
",",
"model",
",",
"gymName",
",",
"plot",
")",
":",
"inputFile",
"=",
"open",
"(",
"inputData",
",",
"'rb'",
")",
"csvReader",
"=",
"csv",
".",
"reader",
"(",
"inputFile",
")",
"csvReader",
".",
"next",
"(",
")",
"csvReader",
".",
"next",
"(",
")",
"csvReader",
".",
"next",
"(",
")",
"shifter",
"=",
"InferenceShifter",
"(",
")",
"if",
"plot",
":",
"output",
"=",
"nupic_anomaly_output",
".",
"NuPICPlotOutput",
"(",
"gymName",
")",
"else",
":",
"output",
"=",
"nupic_anomaly_output",
".",
"NuPICFileOutput",
"(",
"gymName",
")",
"counter",
"=",
"0",
"for",
"row",
"in",
"csvReader",
":",
"counter",
"+=",
"1",
"if",
"(",
"(",
"counter",
"%",
"100",
")",
"==",
"0",
")",
":",
"print",
"(",
"'Read %i lines...'",
"%",
"counter",
")",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"row",
"[",
"0",
"]",
",",
"DATE_FORMAT",
")",
"consumption",
"=",
"float",
"(",
"row",
"[",
"1",
"]",
")",
"result",
"=",
"model",
".",
"run",
"(",
"{",
"'timestamp'",
":",
"timestamp",
",",
"'kw_energy_consumption'",
":",
"consumption",
"}",
")",
"if",
"plot",
":",
"result",
"=",
"shifter",
".",
"shift",
"(",
"result",
")",
"prediction",
"=",
"result",
".",
"inferences",
"[",
"'multiStepBestPredictions'",
"]",
"[",
"1",
"]",
"anomalyScore",
"=",
"result",
".",
"inferences",
"[",
"'anomalyScore'",
"]",
"output",
".",
"write",
"(",
"timestamp",
",",
"consumption",
",",
"prediction",
",",
"anomalyScore",
")",
"inputFile",
".",
"close",
"(",
")",
"output",
".",
"close",
"(",
")"
] | handles looping over the input data and passing each row into the given model object . | train | true |
41,854 | def getZComponentCrossProduct(vec3First, vec3Second):
return ((vec3First.x * vec3Second.y) - (vec3First.y * vec3Second.x))
| [
"def",
"getZComponentCrossProduct",
"(",
"vec3First",
",",
"vec3Second",
")",
":",
"return",
"(",
"(",
"vec3First",
".",
"x",
"*",
"vec3Second",
".",
"y",
")",
"-",
"(",
"vec3First",
".",
"y",
"*",
"vec3Second",
".",
"x",
")",
")"
] | get z component cross product of a pair of vector3s . | train | false |
41,855 | def _is_author_or_privileged(cc_content, context):
return (context['is_requester_privileged'] or _is_author(cc_content, context))
| [
"def",
"_is_author_or_privileged",
"(",
"cc_content",
",",
"context",
")",
":",
"return",
"(",
"context",
"[",
"'is_requester_privileged'",
"]",
"or",
"_is_author",
"(",
"cc_content",
",",
"context",
")",
")"
] | return true if the requester authored the given content or is a privileged user . | train | false |
41,857 | def dfs(command=None, *args):
if command:
return _hadoop_cmd('dfs', command, *args)
else:
return 'Error: command must be provided'
| [
"def",
"dfs",
"(",
"command",
"=",
"None",
",",
"*",
"args",
")",
":",
"if",
"command",
":",
"return",
"_hadoop_cmd",
"(",
"'dfs'",
",",
"command",
",",
"*",
"args",
")",
"else",
":",
"return",
"'Error: command must be provided'"
] | execute a command on dfs cli example: . | train | false |
41,860 | def retry_on_failure(f, *args, **kwargs):
def t(*args, **kwargs):
for i in xrange(MAX_FAILURE_RETRY):
try:
ret_val = f(*args, **kwargs)
return ret_val
except Exception as e:
print ("retry_on_failure(%s): failed on attempt '%d':" % (f.__name__, (i + 1)))
print e
excp_info = sys.exc_info()
continue
raise excp_info[0], excp_info[1], excp_info[2]
return t
| [
"def",
"retry_on_failure",
"(",
"f",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"def",
"t",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"MAX_FAILURE_RETRY",
")",
":",
"try",
":",
"ret_val",
"=",
"f",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"ret_val",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"retry_on_failure(%s): failed on attempt '%d':\"",
"%",
"(",
"f",
".",
"__name__",
",",
"(",
"i",
"+",
"1",
")",
")",
")",
"print",
"e",
"excp_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"continue",
"raise",
"excp_info",
"[",
"0",
"]",
",",
"excp_info",
"[",
"1",
"]",
",",
"excp_info",
"[",
"2",
"]",
"return",
"t"
] | utility function which: 1 . | train | false |
41,861 | def semanage_fcontext_exists(sefcontext, target, ftype):
record = (target, option_to_file_type_str[ftype])
records = sefcontext.get_all()
try:
return records[record]
except KeyError:
return None
| [
"def",
"semanage_fcontext_exists",
"(",
"sefcontext",
",",
"target",
",",
"ftype",
")",
":",
"record",
"=",
"(",
"target",
",",
"option_to_file_type_str",
"[",
"ftype",
"]",
")",
"records",
"=",
"sefcontext",
".",
"get_all",
"(",
")",
"try",
":",
"return",
"records",
"[",
"record",
"]",
"except",
"KeyError",
":",
"return",
"None"
] | get the selinux file context mapping definition from policy . | train | false |
41,862 | def dmp_to_tuple(f, u):
if (not u):
return tuple(f)
v = (u - 1)
return tuple((dmp_to_tuple(c, v) for c in f))
| [
"def",
"dmp_to_tuple",
"(",
"f",
",",
"u",
")",
":",
"if",
"(",
"not",
"u",
")",
":",
"return",
"tuple",
"(",
"f",
")",
"v",
"=",
"(",
"u",
"-",
"1",
")",
"return",
"tuple",
"(",
"(",
"dmp_to_tuple",
"(",
"c",
",",
"v",
")",
"for",
"c",
"in",
"f",
")",
")"
] | convert f into a nested tuple of tuples . | train | false |
41,863 | def run_operation(jboss_config, operation, fail_on_error=True, retries=1):
cli_command_result = __call_cli(jboss_config, operation, retries)
if (cli_command_result['retcode'] == 0):
if _is_cli_output(cli_command_result['stdout']):
cli_result = _parse(cli_command_result['stdout'])
cli_result['success'] = (cli_result['outcome'] == 'success')
else:
raise CommandExecutionError('Operation has returned unparseable output: {0}'.format(cli_command_result['stdout']))
elif _is_cli_output(cli_command_result['stdout']):
cli_result = _parse(cli_command_result['stdout'])
cli_result['success'] = False
match = re.search('^(JBAS\\d+):', cli_result['failure-description'])
cli_result['err_code'] = match.group(1)
cli_result['stdout'] = cli_command_result['stdout']
elif fail_on_error:
raise CommandExecutionError("Command execution failed, return code={retcode}, stdout='{stdout}', stderr='{stderr}' ".format(**cli_command_result))
else:
cli_result = {'success': False, 'stdout': cli_command_result['stdout'], 'stderr': cli_command_result['stderr'], 'retcode': cli_command_result['retcode']}
return cli_result
| [
"def",
"run_operation",
"(",
"jboss_config",
",",
"operation",
",",
"fail_on_error",
"=",
"True",
",",
"retries",
"=",
"1",
")",
":",
"cli_command_result",
"=",
"__call_cli",
"(",
"jboss_config",
",",
"operation",
",",
"retries",
")",
"if",
"(",
"cli_command_result",
"[",
"'retcode'",
"]",
"==",
"0",
")",
":",
"if",
"_is_cli_output",
"(",
"cli_command_result",
"[",
"'stdout'",
"]",
")",
":",
"cli_result",
"=",
"_parse",
"(",
"cli_command_result",
"[",
"'stdout'",
"]",
")",
"cli_result",
"[",
"'success'",
"]",
"=",
"(",
"cli_result",
"[",
"'outcome'",
"]",
"==",
"'success'",
")",
"else",
":",
"raise",
"CommandExecutionError",
"(",
"'Operation has returned unparseable output: {0}'",
".",
"format",
"(",
"cli_command_result",
"[",
"'stdout'",
"]",
")",
")",
"elif",
"_is_cli_output",
"(",
"cli_command_result",
"[",
"'stdout'",
"]",
")",
":",
"cli_result",
"=",
"_parse",
"(",
"cli_command_result",
"[",
"'stdout'",
"]",
")",
"cli_result",
"[",
"'success'",
"]",
"=",
"False",
"match",
"=",
"re",
".",
"search",
"(",
"'^(JBAS\\\\d+):'",
",",
"cli_result",
"[",
"'failure-description'",
"]",
")",
"cli_result",
"[",
"'err_code'",
"]",
"=",
"match",
".",
"group",
"(",
"1",
")",
"cli_result",
"[",
"'stdout'",
"]",
"=",
"cli_command_result",
"[",
"'stdout'",
"]",
"elif",
"fail_on_error",
":",
"raise",
"CommandExecutionError",
"(",
"\"Command execution failed, return code={retcode}, stdout='{stdout}', stderr='{stderr}' \"",
".",
"format",
"(",
"**",
"cli_command_result",
")",
")",
"else",
":",
"cli_result",
"=",
"{",
"'success'",
":",
"False",
",",
"'stdout'",
":",
"cli_command_result",
"[",
"'stdout'",
"]",
",",
"'stderr'",
":",
"cli_command_result",
"[",
"'stderr'",
"]",
",",
"'retcode'",
":",
"cli_command_result",
"[",
"'retcode'",
"]",
"}",
"return",
"cli_result"
] | execute an operation against jboss instance through the cli interface . | train | true |
41,864 | def apply_web_specific_fixes(font, unhinted, family_name):
hhea = font['hhea']
hhea.ascent = 1900
hhea.descent = (-500)
os2 = font['OS/2']
os2.sTypoAscender = 1536
os2.sTypoDescender = (-512)
os2.sTypoLineGap = 102
os2.usWinAscent = 1946
os2.usWinDescent = 512
apply_web_cros_common_fixes(font, unhinted, family_name)
| [
"def",
"apply_web_specific_fixes",
"(",
"font",
",",
"unhinted",
",",
"family_name",
")",
":",
"hhea",
"=",
"font",
"[",
"'hhea'",
"]",
"hhea",
".",
"ascent",
"=",
"1900",
"hhea",
".",
"descent",
"=",
"(",
"-",
"500",
")",
"os2",
"=",
"font",
"[",
"'OS/2'",
"]",
"os2",
".",
"sTypoAscender",
"=",
"1536",
"os2",
".",
"sTypoDescender",
"=",
"(",
"-",
"512",
")",
"os2",
".",
"sTypoLineGap",
"=",
"102",
"os2",
".",
"usWinAscent",
"=",
"1946",
"os2",
".",
"usWinDescent",
"=",
"512",
"apply_web_cros_common_fixes",
"(",
"font",
",",
"unhinted",
",",
"family_name",
")"
] | apply fixes needed for web fonts . | train | false |
41,867 | def tests_from_manifest(testdir_from_ns):
for (ns, testdir) in testdir_from_ns.items():
for testmod in testmods_from_testdir(testdir):
if hasattr(testmod, 'test_suite_class'):
testsuite_class = testmod.test_suite_class
if (not issubclass(testsuite_class, unittest.TestSuite)):
testmod_path = testmod.__file__
if testmod_path.endswith('.pyc'):
testmod_path = testmod_path[:(-1)]
log.warn("'test_suite_class' of '%s' module is not a subclass of 'unittest.TestSuite': ignoring", testmod_path)
else:
testsuite_class = None
for testcase in testcases_from_testmod(testmod):
try:
(yield Test(ns, testmod, testcase, testcase._testMethodName, testsuite_class))
except AttributeError:
(yield Test(ns, testmod, testcase, testcase._TestCase__testMethodName, testsuite_class))
| [
"def",
"tests_from_manifest",
"(",
"testdir_from_ns",
")",
":",
"for",
"(",
"ns",
",",
"testdir",
")",
"in",
"testdir_from_ns",
".",
"items",
"(",
")",
":",
"for",
"testmod",
"in",
"testmods_from_testdir",
"(",
"testdir",
")",
":",
"if",
"hasattr",
"(",
"testmod",
",",
"'test_suite_class'",
")",
":",
"testsuite_class",
"=",
"testmod",
".",
"test_suite_class",
"if",
"(",
"not",
"issubclass",
"(",
"testsuite_class",
",",
"unittest",
".",
"TestSuite",
")",
")",
":",
"testmod_path",
"=",
"testmod",
".",
"__file__",
"if",
"testmod_path",
".",
"endswith",
"(",
"'.pyc'",
")",
":",
"testmod_path",
"=",
"testmod_path",
"[",
":",
"(",
"-",
"1",
")",
"]",
"log",
".",
"warn",
"(",
"\"'test_suite_class' of '%s' module is not a subclass of 'unittest.TestSuite': ignoring\"",
",",
"testmod_path",
")",
"else",
":",
"testsuite_class",
"=",
"None",
"for",
"testcase",
"in",
"testcases_from_testmod",
"(",
"testmod",
")",
":",
"try",
":",
"(",
"yield",
"Test",
"(",
"ns",
",",
"testmod",
",",
"testcase",
",",
"testcase",
".",
"_testMethodName",
",",
"testsuite_class",
")",
")",
"except",
"AttributeError",
":",
"(",
"yield",
"Test",
"(",
"ns",
",",
"testmod",
",",
"testcase",
",",
"testcase",
".",
"_TestCase__testMethodName",
",",
"testsuite_class",
")",
")"
] | return a list of testlib . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.