code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def fontsize(count,maxsize,minsize,maxcount):
size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount)))
if size < minsize:
size = minsize
return size | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier binary_operator parenthesized_expression identifier parenthesized_expression parenthesized_expression binary_operator cal... | A formula for determining font sizes. |
def qr(self,text):
qr_code = qrcode.QRCode(version=4, box_size=4, border=1)
qr_code.add_data(text)
qr_code.make(fit=True)
qr_img = qr_code.make_image()
im = qr_img._img.convert("RGB")
self._convert_image(im) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer expression_statement call attribute ident... | Print QR Code for the provided string |
def parse_url_rules(urls_fp):
url_rules = []
for line in urls_fp:
re_url = line.strip()
if re_url:
url_rules.append({'str': re_url, 're': re.compile(re_url)})
return url_rules | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement call attribute iden... | URL rules from given fp |
def _on_process_finished(self):
exit_code = self._process.exitCode()
if self._process.exitStatus() != self._process.NormalExit:
exit_code = 139
self._formatter.append_message('\x1b[0m\nProcess finished with exit code %d' % exit_code,
output_form... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list attribute attribute identifier ide... | Write the process finished message and emit the `finished` signal. |
def add_page_if_missing(request):
try:
page = Page.objects.for_request(request, best_match=True)
return {
'leonardo_page': page,
'feincms_page': page,
}
except Page.DoesNotExist:
return {} | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier true return_statement dictionary pair string string_start string_content string_... | Returns ``feincms_page`` for request. |
async def expand(self, request: Request, layer: BaseLayer):
if isinstance(layer, lyr.RawText):
t = self.reading_time(layer.text)
yield layer
yield lyr.Sleep(t)
elif isinstance(layer, lyr.MultiText):
texts = await render(layer.text, request, True)
... | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identif... | Expand a layer into a list of layers including the pauses. |
def db_exec_and_commit(self, sql: str, *args) -> int:
rowcount = self.db_exec(sql, *args)
self.commit()
return rowcount | module function_definition identifier parameters identifier typed_parameter identifier type identifier list_splat_pattern identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier list_splat identifier expression_statement call attribute id... | Execute SQL and commit. |
def http_reply(self):
data = {
'status': self.status,
'error': self.code.upper(),
'error_description': str(self)
}
if self.error_caught:
data['error_caught'] = pformat(self.error_caught)
if self.error_id:
data['error_id'] = self... | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument... | Return a Flask reply object describing this error |
def handle(cls, vm, args):
docker = Iaas.info(vm)
if not docker:
raise Exception('docker vm %s not found' % vm)
if docker['state'] != 'running':
Iaas.start(vm)
remote_addr = docker['ifaces'][0]['ips'][0]['ip']
port = unixpipe.setup(remote_addr, 'root', '/v... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator string string_start st... | Setup forwarding connection to given VM and pipe docker cmds over SSH. |
def port_type(arg):
error_msg = "{0} is not a valid port".format(repr(arg))
try:
arg = ast.literal_eval(arg)
except ValueError:
raise argparse.ArgumentTypeError(error_msg)
if arg < 0 or arg > 65535:
raise argparse.ArgumentTypeError(error_msg)
return arg | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute identi... | An argparse type representing a tcp or udp port number. |
def run(self):
try:
if self.should_fetch:
self.fetch()
self.rebase_all_branches()
if self.with_bundler():
self.check_bundler()
if self.settings['push.auto']:
self.push()
except GitError as error:
... | module function_definition identifier parameters identifier block try_statement block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement call attribute identifier ... | Run all the git-up stuff. |
def start(context, mip_config, email, priority, dryrun, command, start_with, family):
mip_cli = MipCli(context.obj['script'])
mip_config = mip_config or context.obj['mip_config']
email = email or environ_email()
kwargs = dict(config=mip_config, family=family, priority=priority, email=email, dryrun=dryru... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_state... | Start a new analysis. |
def delete_all(self):
def delete_action_gen():
scanner = scan(self.es,
index=self.index_name,
query={'query': {'match_all':{}}})
for v in scanner:
yield { '_op_type': 'delete',
'_index': self.in... | module function_definition identifier parameters identifier block function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier dictionary pa... | Delete all books from the index |
def find_destination_type(self, resource_url):
resolvers = self.converters.values()
for resolver in resolvers:
if not hasattr(resolver, 'get_destination_type'):
continue
destination_type = resolver.get_destination_type(resource_url)
if destination_type... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier identifier block if_statement not_operator call identifier argument_list identifier string string_start... | Given a resource_url, figure out what it would resolve into |
def assumed_state(self):
return (not self._controller.car_online[self.id()] and
(self._controller._last_update_time[self.id()] -
self._controller._last_wake_up_time[self.id()] >
self._controller.update_interval)) | module function_definition identifier parameters identifier block return_statement parenthesized_expression boolean_operator not_operator subscript attribute attribute identifier identifier identifier call attribute identifier identifier argument_list parenthesized_expression comparison_operator binary_operator subscri... | Return whether the data is from an online vehicle. |
def begin_script(self):
if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_STATUS.EXECUTING):
return [1]
self.remote_bridge.status = BRIDGE_STATUS.WAITING
self.remote_bridge.error = 0
self.remote_bridge.script_error = None
self.re... | module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier block return_statement list integer expression_statement assignmen... | Indicate we are going to start loading a script. |
def leaves(tree):
lvs = []
def _leaves(node):
if np.isscalar(node):
lvs.append(node)
elif isinstance(node, tuple) and len(node) == 2:
_leaves(node[0])
_leaves(node[1])
else:
raise Exception("Not a tree!")
_leaves(tree)
return lvs | module function_definition identifier parameters identifier block expression_statement assignment identifier list function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument... | Return the leaves in this subtree. |
def _get_arg_names(func):
args, varargs, keywords, defaults = inspect.getargspec(func)
return(tuple(args)) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list identifier return_statement parenthesized_expression call identifier argument_list identifier | this returns the arg names since dictionaries dont guarantee order |
def fit_all(xy,uv,mode='rscale',center=None,verbose=True):
if mode not in ['general', 'shift', 'rscale']:
mode = 'rscale'
if not isinstance(xy,np.ndarray):
xy = np.array(xy)
if not isinstance(uv,np.ndarray):
uv = np.array(uv)
if mode == 'shift':
logstr = 'Performing "shif... | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier true block if_statement comparison_operator identifier list string string_start string_content string_end strin... | Performs an 'rscale' fit between matched lists of pixel positions xy and uv |
def auth_from_hass_config(path=None, **kwargs):
if path is None:
path = config.find_hass_config()
return Auth(os.path.join(path, ".storage/auth"), **kwargs) | module function_definition identifier parameters default_parameter identifier none dictionary_splat_pattern identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list... | Initialize auth from HASS config. |
def open(self):
device_type = 'cisco_ios'
if self.transport == 'telnet':
device_type = 'cisco_ios_telnet'
self.device = ConnectHandler(device_type=device_type,
host=self.hostname,
username=self.username,
... | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier strin... | Open a connection to the device. |
def sZ(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
return Pauli.sigma(qubit, 'Z', coefficient) | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier float type identifier block return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier | Return the Pauli sigma_Z operator acting on the given qubit |
def filter(self, *LayoutClasses, **kwargs):
self._check_layout()
max_level = kwargs.pop('max_level', 0)
greedy = kwargs.pop('greedy', False)
filtered_layout_objects = self.layout.get_layout_objects(LayoutClasses, max_level=max_level, greedy=greedy)
return LayoutSlice(self.layout,... | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start st... | Returns a LayoutSlice pointing to layout objects of type `LayoutClass` |
def _save_params(self):
self.model.save_params_to_file(self.current_params_fname)
utils.cleanup_params_files(self.model.output_dir, self.max_params_files_to_keep, self.state.checkpoint,
self.state.best_checkpoint, self.keep_initializations) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier attr... | Saves model parameters at current checkpoint and optionally cleans up older parameter files to save disk space. |
def acquire_restore(lock, state):
if hasattr(lock, '_acquire_restore'):
lock._acquire_restore(state)
elif hasattr(lock, 'acquire'):
lock.acquire()
else:
raise TypeError('expecting Lock/RLock') | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier s... | Acquire a lock and restore its state. |
def fetch_pkg_list(self):
self.logger.debug("DEBUG: Fetching package name list from PyPI")
package_list = self.list_packages()
cPickle.dump(package_list, open(self.pkg_cache_file, "w"))
self.pkg_list = package_list | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement ... | Fetch and cache master list of package names from PYPI |
async def ctcp_reply(self, target, query, response):
if self.is_channel(target) and not self.in_channel(target):
raise client.NotInChannel(target)
await self.notice(target, construct_ctcp(query, response)) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement boolean_operator call attribute identifier identifier argument_list identifier not_operator call attribute identifier identifier argument_list identifier block raise_statement call attribute identifier identi... | Send a CTCP reply to a target. |
def escape_md_section(text, snob=False):
text = md_backslash_matcher.sub(r"\\\1", text)
if snob:
text = md_chars_matcher_all.sub(r"\\\1", text)
text = md_dot_matcher.sub(r"\1\\\2", text)
text = md_plus_matcher.sub(r"\1\\\2", text)
text = md_dash_matcher.sub(r"\1\\\2", text)
return text | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identi... | Escapes markdown-sensitive characters across whole document sections. |
def zip_dir(directory):
result = io.BytesIO()
dlen = len(directory)
with ZipFile(result, "w") as zf:
for root, dirs, files in os.walk(directory):
for name in files:
full = os.path.join(root, name)
rel = root[dlen:]
dest = os.path.join(rel, ... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_lis... | zip a directory tree into a BytesIO object |
def arp_packet(opcode, src_mac, src_ip, dst_mac, dst_ip):
pkt = packet.Packet()
eth_pkt = ethernet.ethernet(dst_mac, src_mac, ETH_TYPE_ARP)
pkt.add_protocol(eth_pkt)
arp_pkt = arp.arp_ip(opcode, src_mac, src_ip, dst_mac, dst_ip)
pkt.add_protocol(arp_pkt)
pkt.serialize()
... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier ... | Generate ARP packet with ethernet encapsulated. |
def all_issues(issues):
logging.info('finding issues...')
seen = set()
for issue in issues:
if issue['title'] not in seen:
seen.add(issue['title'])
yield issue | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block if_statement comparis... | Yields unique set of issues given a list of issues. |
def _CreateAllTypes(self, enumTypes, dataTypes, managedTypes):
for typeInfo in managedTypes:
name = typeInfo[0]
version = typeInfo[3]
VmomiSupport.AddVersion(version, '', '1.0', 0, name)
VmomiSupport.AddVersionParent(version, 'vmodl.version.version0')
VmomiSupport.AddV... | module function_definition identifier parameters identifier identifier identifier identifier block for_statement identifier identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement call attribute... | Create pyVmomi types from pyVmomi type definitions |
def paren_split(sep,string):
if len(sep) != 1: raise Exception("Separation string must be one character long")
retlist = []
level = 0
blevel = 0
left = 0
for i in range(len(string)):
if string[i] == "(": level += 1
elif string[i] == ")": level -= 1
elif string[i] == "[": ... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier list expression_stat... | Splits the string into pieces divided by sep, when sep is outside of parentheses. |
def transition(trname='', field='', check=None, before=None, after=None):
if is_callable(trname):
raise ValueError(
"The @transition decorator should be called as "
"@transition(['transition_name'], **kwargs)")
if check or before or after:
warnings.warn(
"The ... | module function_definition identifier parameters default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement call identifier argument_list ... | Decorator to declare a function as a transition implementation. |
def convert(self, amount: Number, currency: str, to: str, reverse: bool=False) -> Number:
rate = self.get_rate_for(currency, to, reverse)
if self.return_decimal:
amount = Decimal(amount)
return amount * rate | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier false type identifier block expression_statement assignment identifier call attr... | Convert amount to another currency |
def _convert(self, val):
if isinstance(val, dict) and not isinstance(val, DotDict):
return DotDict(val), True
elif isinstance(val, list) and not isinstance(val, DotList):
return DotList(val), True
return val, False | module function_definition identifier parameters identifier identifier block if_statement boolean_operator call identifier argument_list identifier identifier not_operator call identifier argument_list identifier identifier block return_statement expression_list call identifier argument_list identifier true elif_clause... | Convert the type if necessary and return if a conversion happened. |
def _get_err_msg(row, col, fld, val, prt_flds):
import traceback
traceback.print_exc()
err_msg = (
"ROW({R}) COL({C}) FIELD({F}) VAL({V})\n".format(R=row, C=col, F=fld, V=val),
"PRINT FIELDS({N}): {F}".format(N=len(prt_flds), F=" ".join(prt_flds)))
return "\n".joi... | module function_definition identifier parameters identifier identifier identifier identifier identifier block import_statement dotted_name identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier tuple call attribute string string_start string_content... | Return an informative message with details of xlsx write attempt. |
def signed_ge(a, b):
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = b - a
return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b) | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier keyword_argument identifier true expression_statement assignment... | Return a single bit result of signed greater than or equal comparison. |
def _cell_output(cell):
outputs = cell.get('outputs', [])
stdout = ('\n'.join(_ensure_string(output.get('text', ''))
for output in outputs)).rstrip()
text_outputs = []
for output in outputs:
out = output.get('data', {}).get('text/plain', [])
out = _ensure_string(o... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list expression_statement assignment identifier call attribute parenthesized_expression call attribute string stri... | Return the output of an ipynb cell. |
def _compute_mfcc_c_extension(self):
self.log(u"Computing MFCCs using C extension...")
try:
self.log(u"Importing cmfcc...")
import aeneas.cmfcc.cmfcc
self.log(u"Importing cmfcc... done")
self.__mfcc = (aeneas.cmfcc.cmfcc.compute_from_data(
... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list string string_start string_content string_en... | Compute MFCCs using the Python C extension cmfcc. |
def UpdateManifestResourcesFromXML(dstpath, xmlstr, names=None,
languages=None):
logger.info("Updating manifest in %s", dstpath)
if dstpath.lower().endswith(".exe"):
name = 1
else:
name = 2
winresource.UpdateResources(dstpath, xmlstr, RT_MANIFEST, nam... | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement call attribute call attribute ide... | Update or add manifest XML as resource in dstpath |
def branches(directory=None, verbose=False):
config = current_app.extensions['migrate'].migrate.get_config(directory)
if alembic_version >= (0, 7, 0):
command.branches(config, verbose=verbose)
else:
command.branches(config) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call attribute attribute subscript attribute identifier identifier string string_start string_content string_end identifier identifier argument_list iden... | Show current branch points |
def ack(self, msg):
self.log.info("receiverId <%s> Received: <%s> " % (self.receiverId, msg['body']))
return stomper.NO_REPONSE_NEEDED | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier subscript identifier string string_start string_co... | Process the message and determine what to do with it. |
def __parse_domain_to_employer_line(self, raw_domain, raw_org):
d = re.match(self.DOMAIN_REGEX, raw_domain, re.UNICODE)
if not d:
cause = "invalid domain format: '%s'" % raw_domain
raise InvalidFormatError(cause=cause)
dom = d.group('domain').strip()
o = re.match(... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier if_statement not_operator identifier block expression_statement... | Parse domain to employer lines |
def _export_corpus(self):
if not os.path.exists(self.mallet_bin):
raise IOError("MALLET path invalid or non-existent.")
self.input_path = os.path.join(self.temp, "input.mallet")
exit = subprocess.call([
self.mallet_bin,
'import-file',
'... | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assig... | Calls MALLET's `import-file` method. |
def sync_one(self, aws_syncr, amazon, gateway):
gateway_info = amazon.apigateway.gateway_info(gateway.name, gateway.location)
if not gateway_info:
amazon.apigateway.create_gateway(gateway.name, gateway.location, gateway.stages, gateway.resources, gateway.api_keys, gateway.domain_names)
... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier if_statement not_operator identifier block... | Make sure this gateway exists and has only attributes we want it to have |
def closed(self):
closed = self._closing or self._closed
if not closed and self._reader and self._reader.at_eof():
self._closing = closed = True
self._loop.call_soon(self._do_close, None)
return closed | module function_definition identifier parameters identifier block expression_statement assignment identifier boolean_operator attribute identifier identifier attribute identifier identifier if_statement boolean_operator boolean_operator not_operator identifier attribute identifier identifier call attribute attribute id... | True if connection is closed. |
def SetPlatformArchContext():
_CONFIG.AddContext("Platform:%s" % platform.system().title())
machine = platform.uname()[4]
if machine in ["x86_64", "AMD64", "i686"]:
if platform.architecture()[0] == "32bit":
arch = "i386"
else:
arch = "amd64"
elif machine == "x86":
arch = "i386"
else:
... | module function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifi... | Add the running contexts to the config system. |
def from_json(self, data):
try:
d = json.loads(data)
except ValueError:
raise InvalidMessageException()
self.from_dict(d) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list expression_statement call attribute ident... | Initialise an API message from a JSON representation. |
def use_plenary_agent_view(self):
self._object_views['agent'] = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_agent_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement ... | Pass through to provider ResourceAgentSession.use_plenary_agent_view |
def _from_dict(cls, _dict):
args = {}
if 'request' in _dict:
args['request'] = MessageRequest._from_dict(_dict.get('request'))
else:
raise ValueError(
'Required property \'request\' not present in Log JSON')
if 'response' in _dict:
args... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content strin... | Initialize a Log object from a json dictionary. |
def rnumlistwithoutreplacement(min, max):
if checkquota() < 1:
raise Exception("Your www.random.org quota has already run out.")
requestparam = build_request_parameterNR(min, max)
request = urllib.request.Request(requestparam)
request.add_header('User-Agent', 'randomwrapy/0.1 very alpha')
op... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list i... | Returns a randomly ordered list of the integers between min and max |
def transform(self, x, warn=True):
array_list = [encodeSplines(x[..., i].reshape((-1, 1)),
n_bases=self.n_bases,
spline_order=self.degree,
warn=warn,
start=self.data_mi... | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier list_comprehension call attribute call identifier argument_list call attribute subscript identifier ellipsis identifier identifier argument_list tuple unary_operator ... | Obtain the transformed values |
def example():
client = Client(ACCOUNT_SID, AUTH_TOKEN)
all_messages = client.messages.list()
print('There are {} messages in your account.'.format(len(all_messages)))
some_messages = client.messages.list(limit=10)
print('Here are the last 10 messages in your account:')
for m in some_messages:
... | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list call... | Some example usage of different twilio resources. |
def recipe_list(backend, kitchen):
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
click.secho("%s - Getting the list of Recipes for Kitchen '%s'" % (get_datetime(), use_kitchen), fg='green')
check_and_print(DKCloudCommand... | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block raise_statement call attribute identifier identifier argume... | List the Recipes in a Kitchen |
def append_tier(self, coro, **kwargs):
source = self.tiers[-1] if self.tiers else None
return self.add_tier(coro, source=source, **kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier conditional_expression subscript attribute identifier identifier unary_operator integer attribute identifier identifier none return_statement call attribute identif... | Implicitly source from the tail tier like a pipe. |
def insert_option_group(self, idx, *args, **kwargs):
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call attribu... | Insert an OptionGroup at a given position. |
def _compute_quads(self, element, data, mapping):
quad_mapping = {'left': 'x0', 'right': 'x1', 'bottom': 'y0', 'top': 'y1'}
quad_data = dict(data['scatter_1'])
quad_data.update({'x0': [], 'x1': [], 'y0': [], 'y1': []})
for node in element._sankey['nodes']:
quad_data['x0'].app... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start... | Computes the node quad glyph data.x |
def format(self, record):
if record.levelno == DEBUG:
return self.debug_formatter.format(record)
if record.levelno == INFO:
return self.info_formatter.format(record)
if record.levelno == ERROR:
return self.error_formatter.format(record)
if record.level... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identif... | Format the record using the corresponding formatter. |
def handle_events(self):
for event in pymlgame.get_events():
if event.type == E_NEWCTLR:
self.players[event.uid] = {'name': 'alien_{}'.format(event.uid), 'score': 0}
elif event.type == E_DISCONNECT:
self.players.pop(event.uid)
elif event.type =... | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier attribute identi... | Loop through all events. |
def available_backends():
print 'The following LiveSync agents are available:'
for name, backend in current_plugin.backend_classes.iteritems():
print cformat(' - %{white!}{}%{reset}: {} ({})').format(name, backend.title, backend.description) | module function_definition identifier parameters block print_statement string string_start string_content string_end for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block print_statement call attribute call identifier argument_list string string_s... | Lists the currently available backend types |
def rollforward(self, date):
if self.onOffset(date):
return date
else:
return date + QuarterEnd(month=self.month) | module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement identifier else_clause block return_statement binary_operator identifier call identifier argument_list keyword_argument identifier attribute iden... | Roll date forward to nearest end of quarter |
def swap_buffers(self):
self.widget.swapBuffers()
self.set_default_viewport()
self.app.processEvents()
self.frames += 1 | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_l... | Swap buffers, set viewport, trigger events and increment frame counter |
def mark_featured(self, request, queryset):
queryset.update(featured=True)
self.message_user(
request, _('Selected entries are now marked as featured.')) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier true expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list string string_... | Mark selected as featured post. |
def safe_load_sensors(self):
try:
loaded = self._load_sensors()
except (EOFError, ValueError):
_LOGGER.error('Bad file contents: %s', self.persistence_file)
loaded = False
if not loaded:
_LOGGER.warning('Trying backup file: %s', self.persistence_ba... | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause tuple identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start ... | Load sensors safely from file. |
def reduce_mean(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'mean', new_attrs, inputs | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end string string_start string_content string_end return_statement ex... | Reduce the array along a given axis by mean value |
def run_check(self, data):
if not data:
sys.exit(1)
data, sentences, chars, num_words = self.pre_check(data)
w_dict = Counter(data)
uniq_len, uncommon, uncom_len = self.gsl(w_dict)
non_dchall_set = Counter({word: count for word, count in w_dict.items()
if ... | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list integer expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier ident... | Check for uncommon words and difficult words in file. |
def find_pyqt5(python):
pyqt5 = (
_state.get("pyqt5") or
os.getenv("PYBLISH_QML_PYQT5")
)
if not pyqt5:
try:
path = subprocess.check_output([
python, "-c",
"import PyQt5, sys;"
"sys.stdout.write(PyQt5.__file__)"
... | module function_definition identifier parameters identifier block expression_statement assignment identifier parenthesized_expression boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start s... | Search for PyQt5 automatically |
def timing(function):
@wraps(function)
def wrapped(*args, **kwargs):
start_time = time.time()
ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs))
end_time = time.time()
if function.__module__.startswith('salt.loaded.int.'):
mod_name = function.__module__[1... | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier... | Decorator wrapper to log execution time, for profiling purposes |
def filter_304_headers(headers):
return [(k, v) for k, v in headers if k.lower() not in _filter_from_304] | module function_definition identifier parameters identifier block return_statement list_comprehension tuple identifier identifier for_in_clause pattern_list identifier identifier identifier if_clause comparison_operator call attribute identifier identifier argument_list identifier | Filter a list of headers to include in a "304 Not Modified" response. |
def logged_insert(self, user):
self.insert()
entry = ChangeLogEntry({
'type': 'ADDED',
'documents': [self],
'user': user
})
entry.insert()
return entry | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content s... | Create and insert the document and log the event in the change log |
def save(self, *args, **kwargs):
self._create_slug()
self._create_date_slug()
self._render_content()
send_published_signal = False
if self.published and self.published_on is None:
send_published_signal = self._set_published()
super(Entry, self).save(*args, **k... | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifi... | Auto-generate a slug from the name. |
def save_info(self, dirn):
with current_directory(dirn):
info('Saving distribution info')
with open('dist_info.json', 'w') as fileh:
json.dump({'dist_name': self.ctx.dist_name,
'bootstrap': self.ctx.bootstrap.name,
'ar... | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item call identifier argument_list identifier block expression_statement call identifier argument_list string string_start string_content string_end with_statement with_clause with_item as_pattern call identifie... | Save information about the distribution in its dist_dir. |
def setdefault(self, name: str, default: Any=None) -> Any:
return self.__dict__.setdefault(name, default) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier none type identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Set an attribute with a default value. |
def _getPayload(self, record):
payload = super(LogglyHandler, self)._getPayload(record)
payload['tags'] = self._implodeTags()
return payload | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_en... | The data that will be sent to loggly. |
def unblockall(self):
for q in self.queues.values():
q.unblockall()
self.blockEvents.clear() | module function_definition identifier parameters identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier ... | Remove all blocks from the queue and all sub-queues |
def create_instance(self, parent):
self.kwargs['instantiate'] = True
self.kwargs['parent'] = parent
instance = self.cls(*self.args, **self.kwargs)
instance._field_seqno = self._field_seqno
return instance | module function_definition identifier parameters identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end true expression_statement assignment subscript attribute identifier identifier string string_start string_content string_en... | Create an instance based off this placeholder with some parent |
def memorized_timedelta(seconds):
try:
return _timedelta_cache[seconds]
except KeyError:
delta = timedelta(seconds=seconds)
_timedelta_cache[seconds] = delta
return delta | module function_definition identifier parameters identifier block try_statement block return_statement subscript identifier identifier except_clause identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment subscript ... | Create only one instance of each distinct timedelta |
def _assign_work_unit(self, node):
assert self.workqueue
scope, work_unit = self.workqueue.popitem(last=False)
assigned_to_node = self.assigned_work.setdefault(node, default=OrderedDict())
assigned_to_node[scope] = work_unit
worker_collection = self.registered_collections[node]
... | module function_definition identifier parameters identifier identifier block assert_statement attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false expression_statement ... | Assign a work unit to a node. |
def _iter_path_collection(paths, path_transforms, offsets, styles):
N = max(len(paths), len(offsets))
if not path_transforms:
path_transforms = [np.eye(3)]
edgecolor = styles['edgecolor']
if np.size(edgecolor) == 0:
edgecolor = ['none']
facecolor = styles[... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier if_statement not_operator identifier block expression_statement as... | Build an iterator over the elements of the path collection |
def zoom_out(self):
viewer = self.getfocus_viewer()
if hasattr(viewer, 'zoom_out'):
viewer.zoom_out()
return True | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identif... | Zoom the view out one zoom step. |
def complete_event(self, event_id: str):
event_ids = DB.get_list(self._processed_key)
if event_id not in event_ids:
raise KeyError('Unable to complete event. Event {} has not been '
'processed (ie. it is not in the processed '
'list).'.fo... | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier identifier block raise_statement call ide... | Complete the specified event. |
def ginga_to_matplotlib_cmap(cm, name=None):
if name is None:
name = cm.name
from matplotlib.colors import ListedColormap
carr = np.asarray(cm.clst)
mpl_cm = ListedColormap(carr, name=name, N=len(carr))
return mpl_cm | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_... | Convert Ginga colormap to matplotlib's. |
def _getFromDate(l, date):
try:
date = _toDate(date)
i = _insertDateIndex(date, l) - 1
if i == -1:
return l[0]
return l[i]
except (ValueError, TypeError):
return l[0] | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator call identifier argument_list identifier identifier integer if_statement compari... | returns the index of given or best fitting date |
def build(self, shutit):
target_child = self.start_container(shutit, 'target_child')
self.setup_host_child(shutit)
self.setup_target_child(shutit, target_child)
shutit.send('chmod -R 777 ' + shutit_global.shutit_global_object.shutit_state_dir + ' && mkdir -p ' + shutit_global.shutit_global_object.shutit_state_d... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expressio... | Sets up the target ready for building. |
def nodes_to_object(self, node, object):
"Map all child nodes to one object's attributes"
for n in list(node):
self.node_to_object(n, object) | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier identifier | Map all child nodes to one object's attributes |
def ensure_dir(path):
if not (os.path.exists(path) and
os.path.isdir(path)):
os.mkdir(path) | module function_definition identifier parameters identifier block if_statement not_operator parenthesized_expression boolean_operator call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_sta... | Ensures a directory exists |
def format_cffi_externs(cls):
extern_decls = [
f.extern_signature.pretty_print()
for _, f in cls._extern_fields.items()
]
return (
'extern "Python" {\n'
+ '\n'.join(extern_decls)
+ '\n}\n') | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call attribute attribute identifier identifier identifier argument_list for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list... | Generate stubs for the cffi bindings from @_extern_decl methods. |
def log_leave(event, nick, channel):
if channel not in pmxbot.config.log_channels:
return
ParticipantLogger.store.log(nick, channel, event.type) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute attribute identifier identifier identifier block return_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifi... | Log a quit or part event. |
def move_to(self, n):
self.term.stream.write(self.term.move_up * n) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list binary_operator attribute attribute identifier identifier identifier identifier | Move back N lines in terminal. |
def parse_statement(self):
token = self.stream.current
if token.type != 'name':
self.fail('tag name expected', token.lineno)
self._tag_stack.append(token.value)
pop_tag = True
try:
if token.value in _statement_keywords:
return getattr(self,... | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute ident... | Parse a single statement. |
def update_settings(self):
self.display()
self.display_markers()
if self.parent.notes.annot is not None:
self.parent.notes.display_notes() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement comparison_operator attribute attribute attribute identifier identifier identifier identifier non... | After changing the settings, we need to recreate the whole image. |
def training_job_analytics(self):
if self._current_job_name is None:
raise ValueError('Estimator is not associated with a TrainingJob')
return TrainingJobAnalytics(self._current_job_name, sagemaker_session=self.sagemaker_session) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end return_statement call identifier argument_list attribute identifier identifier keyword... | Return a ``TrainingJobAnalytics`` object for the current training job. |
def bigger_version(version_string_a, version_string_b):
major_a, minor_a, patch_a = parse_version_string(version_string_a)
major_b, minor_b, patch_b = parse_version_string(version_string_b)
if major_a > major_b:
return version_string_a
elif major_a == major_b and minor_a > minor_b:
retur... | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier if_st... | Returns the bigger version of two version strings. |
def issue(self, test, err):
self.step.setProgress('tests failed', len(self.failures) +
len(self.errors)) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end binary_operator call identifier argument_list attribute identifier identifier call identifier... | An issue - failing, erroring etc test. |
def init(scope, app, settings):
cfg = settings.get('rw.static', {})
static = Static()
scope['static'] = static
scope['template_env'].globals['static'] = static
for base_uri, sources in cfg.items():
full_paths = []
for source in sources:
if isinstance(source, dict):
... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary expression_statement assignment identifier call identifier argument_list expressi... | Plugin for serving static files in development mode |
def _convert_connected_app(self):
if self.services and "connected_app" in self.services:
return
connected_app = self.get_connected_app()
if not connected_app:
return
self.logger.warning(
"Reading Connected App info from deprecated config."
... | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier block return_statement expression_statement assignment identifier call attribute identifier id... | Convert Connected App to service |
def create_node_rating_counts_settings(sender, **kwargs):
created = kwargs['created']
node = kwargs['instance']
if created:
create_related_object.delay(NodeRatingCount, {'node': node})
create_related_object.delay(NodeParticipationSettings, {'node': node}) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_en... | create node rating count and settings |
def _get_v_angle_guess(self, case):
v_angle = array([bus.v_angle * (pi / 180.0)
for bus in case.connected_buses])
return v_angle | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list list_comprehension binary_operator attribute identifier identifier parenthesized_expression binary_operator identifier float for_in_clause identifier attribute identifier... | Make the vector of voltage phase guesses. |
def add_view(self, path: str, handler: AbstractView,
**kwargs: Any) -> AbstractRoute:
return self.add_route(hdrs.METH_ANY, path, handler, **kwargs) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter dictionary_splat_pattern identifier type identifier type identifier block return_statement call attribute identifier identifier argument_list attribute identi... | Shortcut for add_route with ANY methods for a class-based view |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.