text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def add_spec(self, *specs):
"""Add specs to the topology
:type specs: HeronComponentSpec
:param specs: specs to add to the topology
"""
for spec in specs:
if not isinstance(spec, HeronComponentSpec):
raise TypeError("Argument to add_spec needs to be HeronComponentSpec, given: %s"
... | [
"def",
"add_spec",
"(",
"self",
",",
"*",
"specs",
")",
":",
"for",
"spec",
"in",
"specs",
":",
"if",
"not",
"isinstance",
"(",
"spec",
",",
"HeronComponentSpec",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument to add_spec needs to be HeronComponentSpec, given: %... | 38.333333 | 17.611111 |
def _register_mecab_loc(location):
''' Set MeCab binary location '''
global MECAB_LOC
if not os.path.isfile(location):
logging.getLogger(__name__).warning("Provided mecab binary location does not exist {}".format(location))
logging.getLogger(__name__).info("Mecab binary is switched to: {}".... | [
"def",
"_register_mecab_loc",
"(",
"location",
")",
":",
"global",
"MECAB_LOC",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"location",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warning",
"(",
"\"Provided mecab binary location ... | 51 | 23.857143 |
def _generate_examples(
self, image_dir, annotation_dir, split_type, has_annotation=True):
"""Generate examples as dicts.
Args:
image_dir: `str`, directory containing the images
annotation_dir: `str`, directory containing
split_type: `str`, <split_name><year> (ex: train2014)
has_a... | [
"def",
"_generate_examples",
"(",
"self",
",",
"image_dir",
",",
"annotation_dir",
",",
"split_type",
",",
"has_annotation",
"=",
"True",
")",
":",
"if",
"has_annotation",
":",
"instance_filename",
"=",
"\"instances_{}.json\"",
"else",
":",
"instance_filename",
"=",... | 34.147059 | 18.882353 |
def _construct_unique_id(self, id_prefix, lines):
"""Constructs a unique ID for a particular prompt in this case,
based on the id_prefix and the lines in the prompt.
"""
text = []
for line in lines:
if isinstance(line, str):
text.append(line)
... | [
"def",
"_construct_unique_id",
"(",
"self",
",",
"id_prefix",
",",
"lines",
")",
":",
"text",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
":",
"text",
".",
"append",
"(",
"line",
")",
"elif",
... | 39.818182 | 8.181818 |
def bind_and_save(self, lxc):
"""Binds metadata to an LXC and saves it"""
bound_meta = self.bind(lxc)
bound_meta.save()
return bound_meta | [
"def",
"bind_and_save",
"(",
"self",
",",
"lxc",
")",
":",
"bound_meta",
"=",
"self",
".",
"bind",
"(",
"lxc",
")",
"bound_meta",
".",
"save",
"(",
")",
"return",
"bound_meta"
] | 33 | 9.2 |
def calculate(self, T, method):
r'''Method to calculate surface tension of a liquid at temperature `T`
with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperature at whi... | [
"def",
"calculate",
"(",
"self",
",",
"T",
",",
"method",
")",
":",
"if",
"method",
"==",
"STREFPROP",
":",
"sigma0",
",",
"n0",
",",
"sigma1",
",",
"n1",
",",
"sigma2",
",",
"n2",
",",
"Tc",
"=",
"self",
".",
"STREFPROP_coeffs",
"sigma",
"=",
"REF... | 42.235294 | 20.235294 |
def dump_credibilities(self, output):
"""Dump credibilities of all products.
Args:
output: a writable object.
"""
for p in self.products:
json.dump({
"product_id": p.name,
"credibility": self.credibility(p)
}, output)
... | [
"def",
"dump_credibilities",
"(",
"self",
",",
"output",
")",
":",
"for",
"p",
"in",
"self",
".",
"products",
":",
"json",
".",
"dump",
"(",
"{",
"\"product_id\"",
":",
"p",
".",
"name",
",",
"\"credibility\"",
":",
"self",
".",
"credibility",
"(",
"p"... | 28 | 11.75 |
def find_sources_in_image(self, filename, hdu_index=0, outfile=None, rms=None, bkg=None, max_summits=None, innerclip=5,
outerclip=4, cores=None, rmsin=None, bkgin=None, beam=None, doislandflux=False,
nopositive=False, nonegative=False, mask=None, lat=None, img... | [
"def",
"find_sources_in_image",
"(",
"self",
",",
"filename",
",",
"hdu_index",
"=",
"0",
",",
"outfile",
"=",
"None",
",",
"rms",
"=",
"None",
",",
"bkg",
"=",
"None",
",",
"max_summits",
"=",
"None",
",",
"innerclip",
"=",
"5",
",",
"outerclip",
"=",... | 39.682759 | 25.37931 |
def board(self, *, _cache: bool = False) -> chess.Board:
"""
Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``).
"""
return self.headers.board() | [
"def",
"board",
"(",
"self",
",",
"*",
",",
"_cache",
":",
"bool",
"=",
"False",
")",
"->",
"chess",
".",
"Board",
":",
"return",
"self",
".",
"headers",
".",
"board",
"(",
")"
] | 34.125 | 12.875 |
def put_collisions( self, block_id, collisions ):
"""
Put collision state for a particular block.
Any operations checked at this block_id that collide
with the given collision state will be rejected.
"""
self.collisions[ block_id ] = copy.deepcopy( collisions ) | [
"def",
"put_collisions",
"(",
"self",
",",
"block_id",
",",
"collisions",
")",
":",
"self",
".",
"collisions",
"[",
"block_id",
"]",
"=",
"copy",
".",
"deepcopy",
"(",
"collisions",
")"
] | 43.428571 | 11.714286 |
def get_dates(self):
"""Get DataCite dates."""
if 'dates' in self.xml:
if isinstance(self.xml['dates']['date'], dict):
return self.xml['dates']['date'].values()[0]
return self.xml['dates']['date']
return None | [
"def",
"get_dates",
"(",
"self",
")",
":",
"if",
"'dates'",
"in",
"self",
".",
"xml",
":",
"if",
"isinstance",
"(",
"self",
".",
"xml",
"[",
"'dates'",
"]",
"[",
"'date'",
"]",
",",
"dict",
")",
":",
"return",
"self",
".",
"xml",
"[",
"'dates'",
... | 38 | 13.285714 |
def add_maxjobs_category(self,categoryName,maxJobsNum):
"""
Add a category to this DAG called categoryName with a maxjobs of maxJobsNum.
@param node: Add (categoryName,maxJobsNum) tuple to CondorDAG.__maxjobs_categories.
"""
self.__maxjobs_categories.append((str(categoryName),str(maxJobsNum))) | [
"def",
"add_maxjobs_category",
"(",
"self",
",",
"categoryName",
",",
"maxJobsNum",
")",
":",
"self",
".",
"__maxjobs_categories",
".",
"append",
"(",
"(",
"str",
"(",
"categoryName",
")",
",",
"str",
"(",
"maxJobsNum",
")",
")",
")"
] | 51.5 | 22.5 |
def get_endpoints(self, endpoints=[]):
"""
Universal selector method to obtain specific endpoints from the
data set.
Parameters
----------
endpoints: str or list
Desired valid endpoints for retrieval
Notes
-----
Only allow... | [
"def",
"get_endpoints",
"(",
"self",
",",
"endpoints",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"endpoints",
",",
"str",
")",
"and",
"endpoints",
"in",
"self",
".",
"_ENDPOINTS",
":",
"endpoints",
"=",
"list",
"(",
"endpoints",
")",
"if",
"not... | 35.25 | 17.305556 |
def ips(self):
"""return all the possible ips of this request, this will include public and private ips"""
r = []
names = ['X_FORWARDED_FOR', 'CLIENT_IP', 'X_REAL_IP', 'X_FORWARDED',
'X_CLUSTER_CLIENT_IP', 'FORWARDED_FOR', 'FORWARDED', 'VIA',
'REMOTE_ADDR']
... | [
"def",
"ips",
"(",
"self",
")",
":",
"r",
"=",
"[",
"]",
"names",
"=",
"[",
"'X_FORWARDED_FOR'",
",",
"'CLIENT_IP'",
",",
"'X_REAL_IP'",
",",
"'X_FORWARDED'",
",",
"'X_CLUSTER_CLIENT_IP'",
",",
"'FORWARDED_FOR'",
",",
"'FORWARDED'",
",",
"'VIA'",
",",
"'REMO... | 35.294118 | 23 |
def transmit_content_metadata(username, channel_code, channel_pk):
"""
Task to send content metadata to each linked integrated channel.
Arguments:
username (str): The username of the User to be used for making API requests to retrieve content metadata.
channel_code (str): Capitalized identi... | [
"def",
"transmit_content_metadata",
"(",
"username",
",",
"channel_code",
",",
"channel_pk",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"api_user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"integrated_channe... | 45.888889 | 30.777778 |
def render_log_filename(ti, try_number, filename_template):
"""
Given task instance, try_number, filename_template, return the rendered log
filename
:param ti: task instance
:param try_number: try_number of the task
:param filename_template: filename template, which can be jinja template or
... | [
"def",
"render_log_filename",
"(",
"ti",
",",
"try_number",
",",
"filename_template",
")",
":",
"filename_template",
",",
"filename_jinja_template",
"=",
"parse_template_string",
"(",
"filename_template",
")",
"if",
"filename_jinja_template",
":",
"jinja_context",
"=",
... | 43.6 | 20.8 |
def touch():
""" Create a .vacationrc file if none exists. """
if not os.path.isfile(get_rc_path()):
open(get_rc_path(), 'a').close()
print('Created file: {}'.format(get_rc_path())) | [
"def",
"touch",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"get_rc_path",
"(",
")",
")",
":",
"open",
"(",
"get_rc_path",
"(",
")",
",",
"'a'",
")",
".",
"close",
"(",
")",
"print",
"(",
"'Created file: {}'",
".",
"format",
... | 40.2 | 8.8 |
def get_buy_price(self, **params):
"""https://developers.coinbase.com/api/v2#get-buy-price"""
currency_pair = params.get('currency_pair', 'BTC-USD')
response = self._get('v2', 'prices', currency_pair, 'buy', params=params)
return self._make_api_object(response, APIObject) | [
"def",
"get_buy_price",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"currency_pair",
"=",
"params",
".",
"get",
"(",
"'currency_pair'",
",",
"'BTC-USD'",
")",
"response",
"=",
"self",
".",
"_get",
"(",
"'v2'",
",",
"'prices'",
",",
"currency_pair",
"... | 60 | 17.2 |
def validate_protected_resource_request(self, uri, http_method='GET',
body=None, headers=None, realms=None):
"""Create a request token response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A va... | [
"def",
"validate_protected_resource_request",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"realms",
"=",
"None",
")",
":",
"try",
":",
"request",
"=",
"self",
".",
"_create_request"... | 50.216216 | 24.945946 |
def attach_file(self, locator_or_path, path=None, **kwargs):
"""
Find a file field on the page and attach a file given its path. The file field can be found
via its name, id, or label text. ::
page.attach_file(locator, "/path/to/file.png")
Args:
locator_or_path ... | [
"def",
"attach_file",
"(",
"self",
",",
"locator_or_path",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
"is",
"None",
":",
"locator",
",",
"path",
"=",
"None",
",",
"locator_or_path",
"else",
":",
"locator",
"=",
"locator_... | 37.259259 | 25.555556 |
def migrateUp(self):
"""
Recreate the hooks in the site store to trigger this SubScheduler.
"""
te = self.store.findFirst(TimedEvent, sort=TimedEvent.time.descending)
if te is not None:
self._transientSchedule(te.time, None) | [
"def",
"migrateUp",
"(",
"self",
")",
":",
"te",
"=",
"self",
".",
"store",
".",
"findFirst",
"(",
"TimedEvent",
",",
"sort",
"=",
"TimedEvent",
".",
"time",
".",
"descending",
")",
"if",
"te",
"is",
"not",
"None",
":",
"self",
".",
"_transientSchedule... | 38.571429 | 16.571429 |
def updateItemIcon(self, item):
"""
Updates the items icon based on its state.
:param item | <QTreeWidgetItem>
"""
# update the column width
self.setUpdatesEnabled(False)
colwidth = self.columnWidth(0)
self.resizeColumnToContents(0)
... | [
"def",
"updateItemIcon",
"(",
"self",
",",
"item",
")",
":",
"# update the column width\r",
"self",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"colwidth",
"=",
"self",
".",
"columnWidth",
"(",
"0",
")",
"self",
".",
"resizeColumnToContents",
"(",
"0",
")",
... | 32 | 7.466667 |
def create_grid(self, grid_width, grid_height):
"""Create a grid layout with stacked widgets.
Parameters
----------
grid_width : int
the width of the grid
grid_height : int
the height of the grid
"""
self.grid_layout = QGridLayout()
... | [
"def",
"create_grid",
"(",
"self",
",",
"grid_width",
",",
"grid_height",
")",
":",
"self",
".",
"grid_layout",
"=",
"QGridLayout",
"(",
")",
"self",
".",
"setLayout",
"(",
"self",
".",
"grid_layout",
")",
"self",
".",
"grid_layout",
".",
"setSpacing",
"("... | 33.777778 | 11 |
def compose(*funcs):
'''
Compose an ordered list of functions. Args of a,b,c,d evaluates as a(b(c(d(ctx))))
'''
def _compose(ctx):
# last func gets context, rest get result of previous func
_result = funcs[-1](ctx)
for f in reversed(funcs[:-1]):
_result = f(_result)
... | [
"def",
"compose",
"(",
"*",
"funcs",
")",
":",
"def",
"_compose",
"(",
"ctx",
")",
":",
"# last func gets context, rest get result of previous func",
"_result",
"=",
"funcs",
"[",
"-",
"1",
"]",
"(",
"ctx",
")",
"for",
"f",
"in",
"reversed",
"(",
"funcs",
... | 29.25 | 22.75 |
def bz2_compress_stream(src, level=9):
"""Compress data from `src`.
Args:
src (iterable): iterable that yields blocks of data to compress
level (int): compression level (1-9) default is 9
Yields:
blocks of compressed data
"""
compressor = bz2.BZ2Compressor(level)
for b... | [
"def",
"bz2_compress_stream",
"(",
"src",
",",
"level",
"=",
"9",
")",
":",
"compressor",
"=",
"bz2",
".",
"BZ2Compressor",
"(",
"level",
")",
"for",
"block",
"in",
"src",
":",
"encoded",
"=",
"compressor",
".",
"compress",
"(",
"block",
")",
"if",
"en... | 25.647059 | 18.176471 |
def get_user_info(tokens, uk):
'''获取用户的部分信息.
比如头像, 用户名, 自我介绍, 粉丝数等.
这个接口可用于查询任何用户的信息, 只要知道他/她的uk.
'''
url = ''.join([
const.PAN_URL,
'pcloud/user/getinfo?channel=chunlei&clienttype=0&web=1',
'&bdstoken=', tokens['bdstoken'],
'&query_uk=', uk,
'&t=', util.time... | [
"def",
"get_user_info",
"(",
"tokens",
",",
"uk",
")",
":",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_URL",
",",
"'pcloud/user/getinfo?channel=chunlei&clienttype=0&web=1'",
",",
"'&bdstoken='",
",",
"tokens",
"[",
"'bdstoken'",
"]",
",",
"'&q... | 26 | 17.157895 |
def create(self, model_obj):
"""Write a record to the dict repository"""
# Update the value of the counters
model_obj = self._set_auto_fields(model_obj)
# Add the entity to the repository
identifier = model_obj[self.entity_cls.meta_.id_field.field_name]
with self.conn['l... | [
"def",
"create",
"(",
"self",
",",
"model_obj",
")",
":",
"# Update the value of the counters",
"model_obj",
"=",
"self",
".",
"_set_auto_fields",
"(",
"model_obj",
")",
"# Add the entity to the repository",
"identifier",
"=",
"model_obj",
"[",
"self",
".",
"entity_cl... | 37.636364 | 17.909091 |
def requeue(self):
"""Loop endlessly and requeue expired jobs."""
job_requeue_interval = float(
self.config.get('sharq', 'job_requeue_interval'))
while True:
self.sq.requeue()
gevent.sleep(job_requeue_interval / 1000.00) | [
"def",
"requeue",
"(",
"self",
")",
":",
"job_requeue_interval",
"=",
"float",
"(",
"self",
".",
"config",
".",
"get",
"(",
"'sharq'",
",",
"'job_requeue_interval'",
")",
")",
"while",
"True",
":",
"self",
".",
"sq",
".",
"requeue",
"(",
")",
"gevent",
... | 39.142857 | 13.428571 |
def is_mass_balanced(reaction):
"""Confirm that a reaction is mass balanced."""
balance = defaultdict(int)
for metabolite, coefficient in iteritems(reaction.metabolites):
if metabolite.elements is None or len(metabolite.elements) == 0:
return False
for element, amount in iteritem... | [
"def",
"is_mass_balanced",
"(",
"reaction",
")",
":",
"balance",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"metabolite",
",",
"coefficient",
"in",
"iteritems",
"(",
"reaction",
".",
"metabolites",
")",
":",
"if",
"metabolite",
".",
"elements",
"is",
"None"... | 50 | 16.555556 |
def refresh_rooms(self):
"""Calls GET /joined_rooms to refresh rooms list."""
for room_id in self.user_api.get_joined_rooms()["joined_rooms"]:
self._rooms[room_id] = MatrixRoom(room_id, self.user_api) | [
"def",
"refresh_rooms",
"(",
"self",
")",
":",
"for",
"room_id",
"in",
"self",
".",
"user_api",
".",
"get_joined_rooms",
"(",
")",
"[",
"\"joined_rooms\"",
"]",
":",
"self",
".",
"_rooms",
"[",
"room_id",
"]",
"=",
"MatrixRoom",
"(",
"room_id",
",",
"sel... | 56.25 | 19.25 |
def create_db_in_shard(db_name, shard, client=None):
"""
In a sharded cluster, create a database in a particular shard.
"""
client = client or pymongo.MongoClient()
# flush the router config to ensure it's not stale
res = client.admin.command('flushRouterConfig')
if not res.get('ok'):
... | [
"def",
"create_db_in_shard",
"(",
"db_name",
",",
"shard",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"client",
"or",
"pymongo",
".",
"MongoClient",
"(",
")",
"# flush the router config to ensure it's not stale",
"res",
"=",
"client",
".",
"admin",
"."... | 43.535714 | 12.892857 |
def getTerms(self, term=None, getFingerprint=None, startIndex=0, maxResults=10):
"""Get term objects
Args:
term, str: A term in the retina (optional)
getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional)
startIndex, in... | [
"def",
"getTerms",
"(",
"self",
",",
"term",
"=",
"None",
",",
"getFingerprint",
"=",
"None",
",",
"startIndex",
"=",
"0",
",",
"maxResults",
"=",
"10",
")",
":",
"return",
"self",
".",
"_terms",
".",
"getTerm",
"(",
"self",
".",
"_retina",
",",
"ter... | 49.692308 | 26.923077 |
def kube_resourcequota(self, metric, scraper_config):
""" Quota and current usage by resource type. """
metric_base_name = scraper_config['namespace'] + '.resourcequota.{}.{}'
suffixes = {'used': 'used', 'hard': 'limit'}
if metric.type in METRIC_TYPES:
for sample in metric.sa... | [
"def",
"kube_resourcequota",
"(",
"self",
",",
"metric",
",",
"scraper_config",
")",
":",
"metric_base_name",
"=",
"scraper_config",
"[",
"'namespace'",
"]",
"+",
"'.resourcequota.{}.{}'",
"suffixes",
"=",
"{",
"'used'",
":",
"'used'",
",",
"'hard'",
":",
"'limi... | 62.933333 | 27.666667 |
def new(self):
# type: () -> None
'''
A method to create a new UDF Anchor Volume Structure.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Anchor Volume Structure alread... | [
"def",
"new",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF Anchor Volume Structure already initialized'",
")",
"self",
".",
"desc_tag",
"=",
"UDFTag",
"(",
"... | 31.47619 | 24.428571 |
def enter(self):
"""Send a LineConfirmation to the controller.
When this state is entered, a
:class:`AYABInterface.communication.host_messages.LineConfirmation`
is sent to the controller.
Also, the :attr:`last line requested
<AYABInterface.communication.Communication.las... | [
"def",
"enter",
"(",
"self",
")",
":",
"self",
".",
"_communication",
".",
"last_requested_line_number",
"=",
"self",
".",
"_line_number",
"self",
".",
"_communication",
".",
"send",
"(",
"LineConfirmation",
",",
"self",
".",
"_line_number",
")"
] | 42.25 | 19.916667 |
def ecg_wave_detector(ecg, rpeaks):
"""
Returns the localization of the P, Q, T waves. This function needs massive help!
Parameters
----------
ecg : list or ndarray
ECG signal (preferably filtered).
rpeaks : list or ndarray
R peaks localization.
Returns
----------
e... | [
"def",
"ecg_wave_detector",
"(",
"ecg",
",",
"rpeaks",
")",
":",
"q_waves",
"=",
"[",
"]",
"p_waves",
"=",
"[",
"]",
"q_waves_starts",
"=",
"[",
"]",
"s_waves",
"=",
"[",
"]",
"t_waves",
"=",
"[",
"]",
"t_waves_starts",
"=",
"[",
"]",
"t_waves_ends",
... | 36.695946 | 27.763514 |
def get_nested(self, *args):
"""
get a nested value, returns None if path does not exist
"""
data = self.data
for key in args:
if key not in data:
return None
data = data[key]
return data | [
"def",
"get_nested",
"(",
"self",
",",
"*",
"args",
")",
":",
"data",
"=",
"self",
".",
"data",
"for",
"key",
"in",
"args",
":",
"if",
"key",
"not",
"in",
"data",
":",
"return",
"None",
"data",
"=",
"data",
"[",
"key",
"]",
"return",
"data"
] | 26.6 | 12.2 |
def edges(self, nbunch=None, keys=False):
""" Iterates over edges in current :class:`BreakpointGraph` instance.
Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__edges`.
:param nbunch: a vertex to iterate over edges outgoing from, if not provided,iteration over all edges is performed.... | [
"def",
"edges",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"keys",
"=",
"False",
")",
":",
"for",
"entry",
"in",
"self",
".",
"__edges",
"(",
"nbunch",
"=",
"nbunch",
",",
"keys",
"=",
"keys",
")",
":",
"yield",
"entry"
] | 50.428571 | 26.571429 |
def init_auth(username, password):
"""Initializes the auth settings for accessing MyAnimeList
through its official API from a given username and password.
:param username Your MyAnimeList account username.
:param password Your MyAnimeList account password.
:return A tuple containing your credentials... | [
"def",
"init_auth",
"(",
"username",
",",
"password",
")",
":",
"username",
"=",
"username",
".",
"strip",
"(",
")",
"password",
"=",
"password",
".",
"strip",
"(",
")",
"credentials",
"=",
"(",
"username",
",",
"password",
")",
"if",
"helpers",
".",
"... | 40 | 10.928571 |
def autocorrplot(trace, vars=None, fontmap = None, max_lag=100):
"""Bar plot of the autocorrelation function for a trace"""
try:
# MultiTrace
traces = trace.traces
except AttributeError:
# NpTrace
traces = [trace]
if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:... | [
"def",
"autocorrplot",
"(",
"trace",
",",
"vars",
"=",
"None",
",",
"fontmap",
"=",
"None",
",",
"max_lag",
"=",
"100",
")",
":",
"try",
":",
"# MultiTrace",
"traces",
"=",
"trace",
".",
"traces",
"except",
"AttributeError",
":",
"# NpTrace",
"traces",
"... | 23.9375 | 22.770833 |
def from_json(self, json):
"""Create resource out of JSON data.
:param json: JSON dict.
:return: Resource with a type defined by the given JSON data.
"""
res_type = json['sys']['type']
if ResourceType.Array.value == res_type:
return self.create_array(json)
... | [
"def",
"from_json",
"(",
"self",
",",
"json",
")",
":",
"res_type",
"=",
"json",
"[",
"'sys'",
"]",
"[",
"'type'",
"]",
"if",
"ResourceType",
".",
"Array",
".",
"value",
"==",
"res_type",
":",
"return",
"self",
".",
"create_array",
"(",
"json",
")",
... | 40.166667 | 13.222222 |
def _get_socket(self, sid):
"""Return the socket object for a given session."""
try:
s = self.sockets[sid]
except KeyError:
raise KeyError('Session not found')
if s.closed:
del self.sockets[sid]
raise KeyError('Session is disconnected')
... | [
"def",
"_get_socket",
"(",
"self",
",",
"sid",
")",
":",
"try",
":",
"s",
"=",
"self",
".",
"sockets",
"[",
"sid",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Session not found'",
")",
"if",
"s",
".",
"closed",
":",
"del",
"self",
"."... | 32.4 | 13.5 |
def make_form(fields=None, layout=None, layout_class=None, base_class=None,
get_form_field=None, name=None, rules=None, **kwargs):
"""
Make a from according dict data:
{'fields':[
{'name':'name', 'type':'str', 'label':'label,
'rules':{
'requ... | [
"def",
"make_form",
"(",
"fields",
"=",
"None",
",",
"layout",
"=",
"None",
",",
"layout_class",
"=",
"None",
",",
"base_class",
"=",
"None",
",",
"get_form_field",
"=",
"None",
",",
"name",
"=",
"None",
",",
"rules",
"=",
"None",
",",
"*",
"*",
"kwa... | 31.15 | 20.583333 |
def walk(self, topdown=True):
"""
Artifact tree generator - analogue of `os.walk`.
:param topdown: if is True or not specified, directories are scanned
from top-down. If topdown is set to False, directories are scanned
from bottom-up.
:rtype: collections.Iterator[
... | [
"def",
"walk",
"(",
"self",
",",
"topdown",
"=",
"True",
")",
":",
"return",
"self",
".",
"_manager",
".",
"walk",
"(",
"top",
"=",
"self",
".",
"_path",
",",
"topdown",
"=",
"topdown",
")"
] | 41.083333 | 22.916667 |
def get_status(self, response, finished=False):
"""Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`"""
status_pos = 0
for line in response.split("\n"):
if line.startswith('JOBID'):
... | [
"def",
"get_status",
"(",
"self",
",",
"response",
",",
"finished",
"=",
"False",
")",
":",
"status_pos",
"=",
"0",
"for",
"line",
"in",
"response",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'JOBID'",
")",
":",
"t... | 41.933333 | 10.066667 |
def sync_projects(self):
"""Sync projects.
This function will retrieve project from keystone
and populate them dfa database and dcnm
"""
p = self.keystone_event._service.projects.list()
for proj in p:
if proj.name in not_create_project_name:
... | [
"def",
"sync_projects",
"(",
"self",
")",
":",
"p",
"=",
"self",
".",
"keystone_event",
".",
"_service",
".",
"projects",
".",
"list",
"(",
")",
"for",
"proj",
"in",
"p",
":",
"if",
"proj",
".",
"name",
"in",
"not_create_project_name",
":",
"continue",
... | 35.75 | 14.416667 |
def get_profile(name=None, **kwargs):
"""Get the profile by name; if no name is given, return the
default profile.
"""
if isinstance(name, Profile):
return name
clazz = get_profile_class(name or 'default')
return clazz(**kwargs) | [
"def",
"get_profile",
"(",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"Profile",
")",
":",
"return",
"name",
"clazz",
"=",
"get_profile_class",
"(",
"name",
"or",
"'default'",
")",
"return",
"clazz",
"... | 28.111111 | 12.555556 |
def find_handfile(names=None):
"""
尝试定位 ``handfile`` 文件,明确指定或逐级搜索父路径
:param str names: 可选,待查找的文件名,主要用于调试,默认使用终端传入的配置
:return: ``handfile`` 文件所在的绝对路径,默认为 None
:rtype: str
"""
# 如果没有明确指定,则包含 env 中的值
names = names or [env.handfile]
# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾
if not nam... | [
"def",
"find_handfile",
"(",
"names",
"=",
"None",
")",
":",
"# 如果没有明确指定,则包含 env 中的值",
"names",
"=",
"names",
"or",
"[",
"env",
".",
"handfile",
"]",
"# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾",
"if",
"not",
"names",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.py'",
... | 30 | 15.243243 |
def parse_alert(server_handshake_bytes):
"""
Parses the handshake for protocol alerts
:param server_handshake_bytes:
A byte string of the handshake data received from the server
:return:
None or an 2-element tuple of integers:
0: 1 (warning) or 2 (fatal)
1: The alert ... | [
"def",
"parse_alert",
"(",
"server_handshake_bytes",
")",
":",
"for",
"record_type",
",",
"_",
",",
"record_data",
"in",
"parse_tls_records",
"(",
"server_handshake_bytes",
")",
":",
"if",
"record_type",
"!=",
"b'\\x15'",
":",
"continue",
"if",
"len",
"(",
"reco... | 33.55 | 20.15 |
def model(self):
"""The Android code name for the device.
"""
# If device is in bootloader mode, get mode name from fastboot.
if self.is_bootloader:
out = self.fastboot.getvar('product').strip()
# 'out' is never empty because of the 'total time' message fastboot
... | [
"def",
"model",
"(",
"self",
")",
":",
"# If device is in bootloader mode, get mode name from fastboot.",
"if",
"self",
".",
"is_bootloader",
":",
"out",
"=",
"self",
".",
"fastboot",
".",
"getvar",
"(",
"'product'",
")",
".",
"strip",
"(",
")",
"# 'out' is never ... | 40.833333 | 14.333333 |
def writeByteArray(self, n):
"""
Writes a L{ByteArray} to the data stream.
@param n: The L{ByteArray} data to be encoded to the AMF3 data stream.
@type n: L{ByteArray}
"""
self.stream.write(TYPE_BYTEARRAY)
ref = self.context.getObjectReference(n)
if ref... | [
"def",
"writeByteArray",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"stream",
".",
"write",
"(",
"TYPE_BYTEARRAY",
")",
"ref",
"=",
"self",
".",
"context",
".",
"getObjectReference",
"(",
"n",
")",
"if",
"ref",
"!=",
"-",
"1",
":",
"self",
".",
... | 23.954545 | 19.409091 |
def _autocorr_func2(mags, lag, maglen, magmed, magstd):
'''
This is an alternative function to calculate the autocorrelation.
This version is from (first definition):
https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations
Parameters
----------
mags : np.array
Th... | [
"def",
"_autocorr_func2",
"(",
"mags",
",",
"lag",
",",
"maglen",
",",
"magmed",
",",
"magstd",
")",
":",
"lagindex",
"=",
"nparange",
"(",
"0",
",",
"maglen",
"-",
"lag",
")",
"products",
"=",
"(",
"mags",
"[",
"lagindex",
"]",
"-",
"magmed",
")",
... | 23.978261 | 27.5 |
def get_cds_ranges_for_transcript(self, transcript_id):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=cds".format(transcript_id)
r = self.ensembl_re... | [
"def",
"get_cds_ranges_for_transcript",
"(",
"self",
",",
"transcript_id",
")",
":",
"headers",
"=",
"{",
"\"content-type\"",
":",
"\"application/json\"",
"}",
"self",
".",
"attempt",
"=",
"0",
"ext",
"=",
"\"/overlap/id/{}?feature=cds\"",
".",
"format",
"(",
"tra... | 30.904762 | 15.761905 |
def getBWTRange(self, start, end):
'''
This function masks the complexity of retrieving a chunk of the BWT from the compressed format
@param start - the beginning of the range to retrieve
@param end - the end of the range in normal python notation (bwt[end] is not part of the return)
... | [
"def",
"getBWTRange",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"#set aside an array block to fill",
"startBlockIndex",
"=",
"start",
">>",
"self",
".",
"bitPower",
"endBlockIndex",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"float",
"(",
"end",
")",... | 55.357143 | 29.071429 |
def parse(self):
""" parse data """
super(OpenWisp, self).parse()
self.parsed_data = self.parsed_data.getElementsByTagName('item') | [
"def",
"parse",
"(",
"self",
")",
":",
"super",
"(",
"OpenWisp",
",",
"self",
")",
".",
"parse",
"(",
")",
"self",
".",
"parsed_data",
"=",
"self",
".",
"parsed_data",
".",
"getElementsByTagName",
"(",
"'item'",
")"
] | 37.75 | 14.75 |
def run(self):
"""run entry"""
self._logger.info("Parsing data files for ssGSEA...........................")
# load data
data = self.load_data()
# normalized samples, and rank
normdat = self.norm_samples(data)
# filtering out gene sets and build gene sets dictiona... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Parsing data files for ssGSEA...........................\"",
")",
"# load data",
"data",
"=",
"self",
".",
"load_data",
"(",
")",
"# normalized samples, and rank",
"normdat",
"=",
"sel... | 47.583333 | 20.625 |
def get_csig(self):
"""
Generate a node's content signature, the digested signature
of its content.
node - the node
cache - alternate node to use for the signature cache
returns - the content signature
"""
try:
return self.ninfo.csig
e... | [
"def",
"get_csig",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"ninfo",
".",
"csig",
"except",
"AttributeError",
":",
"pass",
"contents",
"=",
"self",
".",
"get_contents",
"(",
")",
"csig",
"=",
"SCons",
".",
"Util",
".",
"MD5signature",
... | 27.055556 | 15.944444 |
def _get_label(self, urn):
""" Provisional route for GetLabel request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetLabel response
"""
node = self.resolver.getTextualNode(textId=urn)
r = render_template(
"cts/GetL... | [
"def",
"_get_label",
"(",
"self",
",",
"urn",
")",
":",
"node",
"=",
"self",
".",
"resolver",
".",
"getTextualNode",
"(",
"textId",
"=",
"urn",
")",
"r",
"=",
"render_template",
"(",
"\"cts/GetLabel.xml\"",
",",
"request_urn",
"=",
"str",
"(",
"urn",
")"... | 50 | 27.380952 |
def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Challenge
object from the dictionary.
:param dict: the dictionary to convert
"""
seed = hb_decode(dict['seed'])
index = dict['index']
return Challenge(seed, index) | [
"def",
"fromdict",
"(",
"dict",
")",
":",
"seed",
"=",
"hb_decode",
"(",
"dict",
"[",
"'seed'",
"]",
")",
"index",
"=",
"dict",
"[",
"'index'",
"]",
"return",
"Challenge",
"(",
"seed",
",",
"index",
")"
] | 31.888889 | 9.777778 |
def create_html_select(
options,
name=None,
selected=None,
disabled=None,
multiple=False,
attrs=None,
**other_attrs):
"""
Create an HTML select box.
>>> print create_html_select(["foo", "bar"], selected="bar", name="baz")
<select name="baz... | [
"def",
"create_html_select",
"(",
"options",
",",
"name",
"=",
"None",
",",
"selected",
"=",
"None",
",",
"disabled",
"=",
"None",
",",
"multiple",
"=",
"False",
",",
"attrs",
"=",
"None",
",",
"*",
"*",
"other_attrs",
")",
":",
"body",
"=",
"[",
"]"... | 34.009174 | 18.100917 |
def get_lists(client):
''' Gets all the client's lists '''
response = client.authenticated_request(client.api.Endpoints.LISTS)
return response.json() | [
"def",
"get_lists",
"(",
"client",
")",
":",
"response",
"=",
"client",
".",
"authenticated_request",
"(",
"client",
".",
"api",
".",
"Endpoints",
".",
"LISTS",
")",
"return",
"response",
".",
"json",
"(",
")"
] | 39.5 | 16 |
def EnumVariable(key, help, default, allowed_values, map={}, ignorecase=0):
"""
The input parameters describe an option with only certain values
allowed. They are returned with an appropriate converter and
validator appended. The result is usable for input to
Variables.Add().
'key' and 'default... | [
"def",
"EnumVariable",
"(",
"key",
",",
"help",
",",
"default",
",",
"allowed_values",
",",
"map",
"=",
"{",
"}",
",",
"ignorecase",
"=",
"0",
")",
":",
"help",
"=",
"'%s (%s)'",
"%",
"(",
"help",
",",
"'|'",
".",
"join",
"(",
"allowed_values",
")",
... | 41.697674 | 26.813953 |
def delete(self, id):
"""Deletes a grant.
Args:
id (str): The id of the custom domain to delete
See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/delete_custom_domains_by_id
"""
url = self._url('%s' % (id))
return self.client.delete(url) | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"url",
"=",
"self",
".",
"_url",
"(",
"'%s'",
"%",
"(",
"id",
")",
")",
"return",
"self",
".",
"client",
".",
"delete",
"(",
"url",
")"
] | 27.454545 | 22.545455 |
def adapt_meta(self, meta):
"""Convert meta from error response to href and surge_id attributes."""
surge = meta.get('surge_confirmation')
href = surge.get('href')
surge_id = surge.get('surge_confirmation_id')
return href, surge_id | [
"def",
"adapt_meta",
"(",
"self",
",",
"meta",
")",
":",
"surge",
"=",
"meta",
".",
"get",
"(",
"'surge_confirmation'",
")",
"href",
"=",
"surge",
".",
"get",
"(",
"'href'",
")",
"surge_id",
"=",
"surge",
".",
"get",
"(",
"'surge_confirmation_id'",
")",
... | 33.25 | 16.375 |
def return_val(self):
"""
Returns the return value of the function, as a ParamDoc with an
empty name:
>>> comments = parse_comments_for_file('examples/module_closure.js')
>>> fn1 = FunctionDoc(comments[1])
>>> fn1.return_val.name
''
>>> fn1.return_val.doc... | [
"def",
"return_val",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"get",
"(",
"'return'",
")",
"or",
"self",
".",
"get",
"(",
"'returns'",
")",
"type",
"=",
"self",
".",
"get",
"(",
"'type'",
")",
"if",
"'{'",
"in",
"ret",
"and",
"'}'",
"in",
... | 30.193548 | 14.903226 |
def _on_completions_refreshed(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When cli is first launched we call refresh_completions before
# instantiat... | [
"def",
"_on_completions_refreshed",
"(",
"self",
",",
"new_completer",
")",
":",
"with",
"self",
".",
"_completer_lock",
":",
"self",
".",
"completer",
"=",
"new_completer",
"# When cli is first launched we call refresh_completions before",
"# instantiating the cli object. So i... | 47.266667 | 18.066667 |
def get(self, url):
"""
Do a GET request
"""
r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT)
self._check_response(r, 200)
return r.json() | [
"def",
"get",
"(",
"self",
",",
"url",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_format_url",
"(",
"url",
")",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"timeout",
"=",
"TIMEOUT",
")",
"self",
".",
"_check_response",
"... | 26.25 | 18 |
def version(self):
"""
This attribute retrieve the API version.
>>> Works().version
'1.0.0'
"""
request_params = dict(self.request_params)
request_url = str(self.request_url)
result = self.do_http_request(
'get',
reque... | [
"def",
"version",
"(",
"self",
")",
":",
"request_params",
"=",
"dict",
"(",
"self",
".",
"request_params",
")",
"request_url",
"=",
"str",
"(",
"self",
".",
"request_url",
")",
"result",
"=",
"self",
".",
"do_http_request",
"(",
"'get'",
",",
"request_url... | 24.888889 | 15.222222 |
def get_sorted_hdrgo2usrgos(self, hdrgos, flat_list=None, hdrgo_prt=True, hdrgo_sort=True):
"""Return GO IDs sorting using go2nt's namedtuple."""
# Return user-specfied sort or default sort of header and user GO IDs
sorted_hdrgos_usrgos = []
h2u_get = self.grprobj.hdrgo2usrgos.get
... | [
"def",
"get_sorted_hdrgo2usrgos",
"(",
"self",
",",
"hdrgos",
",",
"flat_list",
"=",
"None",
",",
"hdrgo_prt",
"=",
"True",
",",
"hdrgo_sort",
"=",
"True",
")",
":",
"# Return user-specfied sort or default sort of header and user GO IDs",
"sorted_hdrgos_usrgos",
"=",
"[... | 54.76 | 18.08 |
def generate_source_catalogs(imglist, **pars):
"""Generates a dictionary of source catalogs keyed by image name.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for source detection.
Returns
-------
sourcecatalogdict : dictionary
... | [
"def",
"generate_source_catalogs",
"(",
"imglist",
",",
"*",
"*",
"pars",
")",
":",
"output",
"=",
"pars",
".",
"get",
"(",
"'output'",
",",
"False",
")",
"sourcecatalogdict",
"=",
"{",
"}",
"for",
"imgname",
"in",
"imglist",
":",
"log",
".",
"info",
"... | 50.83871 | 30.129032 |
def RegisterHelper(cls, resolver_helper):
"""Registers a path specification resolver helper.
Args:
resolver_helper (ResolverHelper): resolver helper.
Raises:
KeyError: if resolver helper object is already set for the corresponding
type indicator.
"""
if resolver_helper.type_i... | [
"def",
"RegisterHelper",
"(",
"cls",
",",
"resolver_helper",
")",
":",
"if",
"resolver_helper",
".",
"type_indicator",
"in",
"cls",
".",
"_resolver_helpers",
":",
"raise",
"KeyError",
"(",
"(",
"'Resolver helper object already set for type indicator: '",
"'{0!s}.'",
")"... | 35.4375 | 23.25 |
def paintEvent(self, event):
"""
Overloads the paint event to support rendering of hints if there are
no items in the tree.
:param event | <QPaintEvent>
"""
super(XListWidget, self).paintEvent(event)
if not self.visibleCount() and s... | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"XListWidget",
",",
"self",
")",
".",
"paintEvent",
"(",
"event",
")",
"if",
"not",
"self",
".",
"visibleCount",
"(",
")",
"and",
"self",
".",
"hint",
"(",
")",
":",
"text",
"=... | 34.419355 | 14.032258 |
def update_resource(self, resource, underlined=None):
"""Update the cache for global names in `resource`"""
try:
pymodule = self.project.get_pymodule(resource)
modname = self._module_name(resource)
self._add_names(pymodule, modname, underlined)
except exceptio... | [
"def",
"update_resource",
"(",
"self",
",",
"resource",
",",
"underlined",
"=",
"None",
")",
":",
"try",
":",
"pymodule",
"=",
"self",
".",
"project",
".",
"get_pymodule",
"(",
"resource",
")",
"modname",
"=",
"self",
".",
"_module_name",
"(",
"resource",
... | 43.875 | 14.25 |
def get_rule(self, template_name):
"""Find a matching compilation rule for a function.
Raises a :exc:`ValueError` if no matching rule can be found.
:param template_name: the name of the template
"""
for regex, render_func in self.rules:
if re.match(regex, template_n... | [
"def",
"get_rule",
"(",
"self",
",",
"template_name",
")",
":",
"for",
"regex",
",",
"render_func",
"in",
"self",
".",
"rules",
":",
"if",
"re",
".",
"match",
"(",
"regex",
",",
"template_name",
")",
":",
"return",
"render_func",
"raise",
"ValueError",
"... | 35.909091 | 13.545455 |
def generate_signed_url_v4(
credentials,
resource,
expiration,
api_access_endpoint=DEFAULT_ENDPOINT,
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
_request_timest... | [
"def",
"generate_signed_url_v4",
"(",
"credentials",
",",
"resource",
",",
"expiration",
",",
"api_access_endpoint",
"=",
"DEFAULT_ENDPOINT",
",",
"method",
"=",
"\"GET\"",
",",
"content_md5",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"response_type",
"=... | 35.880829 | 23.621762 |
def _process_binary_trigger(trigger_value, condition):
"""Create an InputTrigger object."""
ops = {
0: ">",
1: "<",
2: ">=",
3: "<=",
4: "==",
5: 'always'
}
sources = {
0: 'value',
1: 'count'
}
encoded_source = condition & 0b1
... | [
"def",
"_process_binary_trigger",
"(",
"trigger_value",
",",
"condition",
")",
":",
"ops",
"=",
"{",
"0",
":",
"\">\"",
",",
"1",
":",
"\"<\"",
",",
"2",
":",
"\">=\"",
",",
"3",
":",
"\"<=\"",
",",
"4",
":",
"\"==\"",
",",
"5",
":",
"'always'",
"}... | 24.6875 | 26.75 |
def to_dict(self):
"""
This method converts the DictCell into a python `dict`. This is useful
for JSON serialization.
"""
output = {}
for key, value in self.__dict__['p'].iteritems():
if value is None or isinstance(value, SIMPLE_TYPES):
output... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"output",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__dict__",
"[",
"'p'",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"value",
"is",
"None",
"or",
"isinstance",
"(",
"value",
",",
"SI... | 39.791667 | 14.708333 |
def matrix_is_equivalent(X, Y):
"""
Checks matrix equivalence with numpy, scipy and pandas
"""
return X is Y or (isinstance(X, Y.__class__) and X.shape == Y.shape and
np.sum((X != Y).sum()) == 0) | [
"def",
"matrix_is_equivalent",
"(",
"X",
",",
"Y",
")",
":",
"return",
"X",
"is",
"Y",
"or",
"(",
"isinstance",
"(",
"X",
",",
"Y",
".",
"__class__",
")",
"and",
"X",
".",
"shape",
"==",
"Y",
".",
"shape",
"and",
"np",
".",
"sum",
"(",
"(",
"X"... | 38 | 12 |
def balance_ions(anions, cations, anion_zs=None, cation_zs=None,
anion_concs=None, cation_concs=None, rho_w=997.1,
method='increase dominant', selected_ion=None):
r'''Performs an ion balance to adjust measured experimental ion
compositions to electroneutrality. Can accept ei... | [
"def",
"balance_ions",
"(",
"anions",
",",
"cations",
",",
"anion_zs",
"=",
"None",
",",
"cation_zs",
"=",
"None",
",",
"anion_concs",
"=",
"None",
",",
"cation_concs",
"=",
"None",
",",
"rho_w",
"=",
"997.1",
",",
"method",
"=",
"'increase dominant'",
","... | 46.468182 | 23.295455 |
def get_rel_attr(self, attr_name, model):
"""For a related attribute specification, returns (related model,
attribute).
Returns (None, None) if model is not found, or (model, None) if
attribute is not found.
"""
rel_attr_name, attr_name = attr_name.split(".", 1)
... | [
"def",
"get_rel_attr",
"(",
"self",
",",
"attr_name",
",",
"model",
")",
":",
"rel_attr_name",
",",
"attr_name",
"=",
"attr_name",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"rel_attr",
"=",
"getattr",
"(",
"self",
".",
"model",
",",
"rel_attr_name",
","... | 33.941176 | 17.823529 |
def skip(mapping):
"""
:param mapping: generator
:return: filtered generator
"""
found = set()
for m in mapping:
matched_atoms = set(m.values())
if found.intersection(matched_atoms):
continue
found.update(matched_atoms)
yield m | [
"def",
"skip",
"(",
"mapping",
")",
":",
"found",
"=",
"set",
"(",
")",
"for",
"m",
"in",
"mapping",
":",
"matched_atoms",
"=",
"set",
"(",
"m",
".",
"values",
"(",
")",
")",
"if",
"found",
".",
"intersection",
"(",
"matched_atoms",
")",
":",
"cont... | 23.666667 | 11.666667 |
def getExceptionClass(errorCode):
"""
Converts the specified error code into the corresponding class object.
Raises a KeyError if the errorCode is not found.
"""
classMap = {}
for name, class_ in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(class_) and issubclass(class_,... | [
"def",
"getExceptionClass",
"(",
"errorCode",
")",
":",
"classMap",
"=",
"{",
"}",
"for",
"name",
",",
"class_",
"in",
"inspect",
".",
"getmembers",
"(",
"sys",
".",
"modules",
"[",
"__name__",
"]",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"clas... | 41.7 | 16.3 |
def fetch_source(self) -> None:
"""Download the tar archive that contains the source code for the library.
"""
import requests # Do not import at the top that this file can be imported by setup.py
with TemporaryFile() as temp_file:
# Download the source archive
r... | [
"def",
"fetch_source",
"(",
"self",
")",
"->",
"None",
":",
"import",
"requests",
"# Do not import at the top that this file can be imported by setup.py",
"with",
"TemporaryFile",
"(",
")",
"as",
"temp_file",
":",
"# Download the source archive",
"request",
"=",
"requests",... | 46.769231 | 10.538462 |
def bind(self, graph, reset=True, initialize=True):
'''Bind this layer into a computation graph.
This method is a wrapper for performing common initialization tasks. It
calls :func:`resolve`, :func:`setup`, and :func:`log`.
Parameters
----------
graph : :class:`Network ... | [
"def",
"bind",
"(",
"self",
",",
"graph",
",",
"reset",
"=",
"True",
",",
"initialize",
"=",
"True",
")",
":",
"if",
"reset",
":",
"for",
"k",
"in",
"self",
".",
"_input_shapes",
":",
"self",
".",
"_input_shapes",
"[",
"k",
"]",
"=",
"None",
"for",... | 36.69697 | 18.030303 |
def observation_input(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space, and add input
encoder of the appropriate type.
'''
placeholder = observation_placeholder(ob_space, batch_size, name)
return placeholder... | [
"def",
"observation_input",
"(",
"ob_space",
",",
"batch_size",
"=",
"None",
",",
"name",
"=",
"'Ob'",
")",
":",
"placeholder",
"=",
"observation_placeholder",
"(",
"ob_space",
",",
"batch_size",
",",
"name",
")",
"return",
"placeholder",
",",
"encode_observatio... | 44.5 | 32 |
def patch_string(s):
"""
Reorganize a String in such a way that surrogates are printable
and lonely surrogates are escaped.
:param s: input string
:return: string with escaped lonely surrogates and 32bit surrogates
"""
res = ''
it = PeekIterator(s)
for c in it:
if (ord(c) >>... | [
"def",
"patch_string",
"(",
"s",
")",
":",
"res",
"=",
"''",
"it",
"=",
"PeekIterator",
"(",
"s",
")",
"for",
"c",
"in",
"it",
":",
"if",
"(",
"ord",
"(",
"c",
")",
">>",
"10",
")",
"==",
"0b110110",
":",
"# High surrogate",
"# Check for the next",
... | 33.233333 | 15.433333 |
def get_mapping_variable(variable_name, variables_mapping):
""" get variable from variables_mapping.
Args:
variable_name (str): variable name
variables_mapping (dict): variables mapping
Returns:
mapping variable value.
Raises:
exceptions.VariableNotFound: variable is n... | [
"def",
"get_mapping_variable",
"(",
"variable_name",
",",
"variables_mapping",
")",
":",
"try",
":",
"return",
"variables_mapping",
"[",
"variable_name",
"]",
"except",
"KeyError",
":",
"raise",
"exceptions",
".",
"VariableNotFound",
"(",
"\"{} is not found.\"",
".",
... | 26.833333 | 22.777778 |
def regions(self):
"""
This method will return all the available regions within the
DigitalOcean cloud.
"""
json = self.request('/regions', method='GET')
status = json.get('status')
if status == 'OK':
regions_json = json.get('regions', [])
... | [
"def",
"regions",
"(",
"self",
")",
":",
"json",
"=",
"self",
".",
"request",
"(",
"'/regions'",
",",
"method",
"=",
"'GET'",
")",
"status",
"=",
"json",
".",
"get",
"(",
"'status'",
")",
"if",
"status",
"==",
"'OK'",
":",
"regions_json",
"=",
"json"... | 36.857143 | 14.571429 |
def fullmatch(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning a match
object if the whole string matches, or None if no match was found."""
# Build a version of the pattern with a non-capturing group around it.
# This is needed to get m.end() to correctly rep... | [
"def",
"fullmatch",
"(",
"pattern",
",",
"string",
",",
"flags",
"=",
"0",
")",
":",
"# Build a version of the pattern with a non-capturing group around it.",
"# This is needed to get m.end() to correctly report the size of the",
"# matched expression (as per the final doctest above).",
... | 54.846154 | 15.769231 |
def labels(self):
"""Retrieve or set labels assigned to this bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets#labels
.. note::
The getter for this property returns a dict which is a *copy*
of the bucket's labels. Mutating that dict has no ef... | [
"def",
"labels",
"(",
"self",
")",
":",
"labels",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"labels\"",
")",
"if",
"labels",
"is",
"None",
":",
"return",
"{",
"}",
"return",
"copy",
".",
"deepcopy",
"(",
"labels",
")"
] | 32.357143 | 20.107143 |
def demo_update(self):
"""
Performs a demonstration update by calling the demo optimization operation.
Note that the batch data does not have to be fetched from the demo memory as this is now part of
the TensorFlow operation of the demo update.
"""
fetches = self.demo_opt... | [
"def",
"demo_update",
"(",
"self",
")",
":",
"fetches",
"=",
"self",
".",
"demo_optimization_output",
"self",
".",
"monitored_session",
".",
"run",
"(",
"fetches",
"=",
"fetches",
")"
] | 42.333333 | 21.666667 |
def tree_model_natsort(model, row1, row2, user_data=None):
'''用natural sorting算法对TreeModel的一个column进行排序'''
sort_column, sort_type = model.get_sort_column_id()
value1 = model.get_value(row1, sort_column)
value2 = model.get_value(row2, sort_column)
sort_list1 = util.natsort(value1)
sort_list2 = ut... | [
"def",
"tree_model_natsort",
"(",
"model",
",",
"row1",
",",
"row2",
",",
"user_data",
"=",
"None",
")",
":",
"sort_column",
",",
"sort_type",
"=",
"model",
".",
"get_sort_column_id",
"(",
")",
"value1",
"=",
"model",
".",
"get_value",
"(",
"row1",
",",
... | 36.75 | 12.916667 |
def parse_mode(mode, default_bitdepth=None):
"""Parse PIL-style mode and return tuple (grayscale, alpha, bitdeph)"""
# few special cases
if mode == 'P':
# Don't know what is pallette
raise Error('Unknown colour mode:' + mode)
elif mode == '1':
# Logical
return (True, Fals... | [
"def",
"parse_mode",
"(",
"mode",
",",
"default_bitdepth",
"=",
"None",
")",
":",
"# few special cases",
"if",
"mode",
"==",
"'P'",
":",
"# Don't know what is pallette",
"raise",
"Error",
"(",
"'Unknown colour mode:'",
"+",
"mode",
")",
"elif",
"mode",
"==",
"'1... | 26.864865 | 16.459459 |
def get_gradebook_column(self, gradebook_column_id):
"""Gets the ``GradebookColumn`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``GradebookColumn`` may have a
different ``Id`` than requested, such as the case wh... | [
"def",
"get_gradebook_column",
"(",
"self",
",",
"gradebook_column_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resource",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'grad... | 53 | 22.413793 |
def download_handler(feed, placeholders):
import shlex
"""
Parse and execute the download handler
"""
value = feed.retrieve_config('downloadhandler', 'greg')
if value == 'greg':
while os.path.isfile(placeholders.fullpath):
placeholders.fullpath = placeholders.fullpath + '_'
... | [
"def",
"download_handler",
"(",
"feed",
",",
"placeholders",
")",
":",
"import",
"shlex",
"value",
"=",
"feed",
".",
"retrieve_config",
"(",
"'downloadhandler'",
",",
"'greg'",
")",
"if",
"value",
"==",
"'greg'",
":",
"while",
"os",
".",
"path",
".",
"isfi... | 39.222222 | 14.555556 |
def removePadding(str, blocksize=AES_blocksize, mode='CMS'):
''' Remove padding from string
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Decrypted string withou... | [
"def",
"removePadding",
"(",
"str",
",",
"blocksize",
"=",
"AES_blocksize",
",",
"mode",
"=",
"'CMS'",
")",
":",
"if",
"mode",
"not",
"in",
"(",
"0",
",",
"'CMS'",
")",
":",
"for",
"k",
"in",
"MODES",
".",
"keys",
"(",
")",
":",
"if",
"mode",
"in... | 40 | 18.266667 |
def _parser_jsonip(text):
"""Parse response text like the one returned by http://jsonip.com/."""
import json
try:
return str(json.loads(text).get("ip"))
except ValueError as exc:
LOG.debug("Text '%s' could not be parsed", exc_info=exc)
return None | [
"def",
"_parser_jsonip",
"(",
"text",
")",
":",
"import",
"json",
"try",
":",
"return",
"str",
"(",
"json",
".",
"loads",
"(",
"text",
")",
".",
"get",
"(",
"\"ip\"",
")",
")",
"except",
"ValueError",
"as",
"exc",
":",
"LOG",
".",
"debug",
"(",
"\"... | 35 | 16.75 |
def cancel_task(all, task_id):
"""
Executor for `globus task cancel`
"""
if bool(all) + bool(task_id) != 1:
raise click.UsageError(
"You must pass EITHER the special --all flag "
"to cancel all in-progress tasks OR a single "
"task ID to cancel."
)
... | [
"def",
"cancel_task",
"(",
"all",
",",
"task_id",
")",
":",
"if",
"bool",
"(",
"all",
")",
"+",
"bool",
"(",
"task_id",
")",
"!=",
"1",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"You must pass EITHER the special --all flag \"",
"\"to cancel all in-progres... | 32.214286 | 23.321429 |
def wait_for_elements(
self, using, value, timeout=10000,
interval=1000, asserter=is_displayed):
"""Wait for elements till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(st... | [
"def",
"wait_for_elements",
"(",
"self",
",",
"using",
",",
"value",
",",
"timeout",
"=",
"10000",
",",
"interval",
"=",
"1000",
",",
"asserter",
"=",
"is_displayed",
")",
":",
"if",
"not",
"callable",
"(",
"asserter",
")",
":",
"raise",
"TypeError",
"("... | 33.605263 | 19.131579 |
def write_temp_file(self, content, filename=None, mode='w'):
"""Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the... | [
"def",
"write_temp_file",
"(",
"self",
",",
"content",
",",
"filename",
"=",
"None",
",",
"mode",
"=",
"'w'",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"fqpn",
"=",
"os",
".",
... | 39.833333 | 22.833333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.