seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def convert_html_tags_to_jats(xml_etree):
"""
This methods receives an etree node and replace all "html tags" to
jats compliant tags.
"""
tags = (
('strong', 'bold'),
('i', 'italic'),
('u', 'underline'),
('small', 'sc')
)
for from_tag, to_tag in tags... | bigcode/self-oss-instruct-sc2-concepts |
def _is_valid_input_row(row, conf):
"""
Filters blank rows and applies the optional configuration filter
argument if necessary.
:param row: the input row
:param config: the configuration
:return: whether the row should be converted
"""
# Filter blank rows.
if all(value == None for v... | bigcode/self-oss-instruct-sc2-concepts |
def accuracy(labels, predictions):
"""
Returns the percentage of correct predictions in the
set (labels, predictions).
"""
acc = 0
for label, pred in zip(labels, predictions):
if label == pred:
acc += 1
return acc / labels.shape[0] | bigcode/self-oss-instruct-sc2-concepts |
def _generate_line(club, name_column_width):
""" Generates a single line of output.
:param Organization club: object holding information about club
:param int name_column_width: width of name column
:return: nicely formatted line of output
:rtype: str
"""
name_column = str(club.name) + ":"... | bigcode/self-oss-instruct-sc2-concepts |
def __metro(soup):
"""
Gets the most read news from the Metropoles DF page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Metropoles DF Page
"""
news = []
container = soup.select('.m-title')
for item in container:
a = item.a
title... | bigcode/self-oss-instruct-sc2-concepts |
def get_base_image(version_map, version):
"""Selects the appropriate base image from the version map.
This function takes into account the .NET Core versioning story to
determine the appropriate base image for the given version. It
will select from within the same major version and only if the
mino... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def extend_object_field(base_obj, client_obj, field_name):
"""
:param base_obj: an object which has a property `field_name` that is a list
:param client_obj: an object which has a property `field_name` that is a list.
A copy of this object is returned with `field_name` modified
:pa... | bigcode/self-oss-instruct-sc2-concepts |
def is_linux(repository_ctx):
"""Returns true if the host operating system is linux."""
os_name = repository_ctx.os.name.lower()
return os_name.find("linux") != -1 | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_auto_embedding_dim(num_classes):
""" Calculate the dim of embedding vector according to number of classes in the category
emb_dim = [6 * (num_classes)^(1/4)]
ref: Ruoxi Wang, Bin Fu, Gang Fu, and Mingliang Wang. 2017. Deep & Cross Network for Ad Click Predictions.
In Proceedings o... | bigcode/self-oss-instruct-sc2-concepts |
def convert_retention_to_seconds(desired_retention, retention_unit):
"""Convert desired retention to seconds.
:param desired_retention: The desired retention for snapshot
schedule
:param retention_unit: The retention unit for snapshot schedule
:return: The integer value in seconds
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _split(a: List[bytes], n: int) -> List[List[bytes]]:
"""
Splits a list into a list of n sub-lists. Assumes that len(a) % n == 0
:param a: the list to split
:param n: number of parts to split the list into
:return: a list containing the parts of the source list
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def is_equal_to_as_set(l1, l2):
""" return true if two lists contain the same content
:param l1: first list
:param l2: second list
:return: whether lists match
"""
# Note specifically that set(l1) == set(l2) does not work as expected.
return len(set(l1).symmetric_difference(set(l2))) == 0 | bigcode/self-oss-instruct-sc2-concepts |
def possible_mine_limits(tallies):
"""return the total minimum and maximum possible # of mines across all
tallied fronts
returns (min, max)"""
return (sum(f(tally) for tally in tallies) for f in (lambda tally: tally.min_mines(), lambda tally: tally.max_mines())) | bigcode/self-oss-instruct-sc2-concepts |
def line_goes_through_border(pos1, pos2, dest1, dest2, border, lower, upper):
"""
Test if the line from (pos1, pos2) to (dest1, dest2) goes through the border between lower and upper.
"""
try:
m = (border - pos1) / (dest1 - pos1)
except ZeroDivisionError:
return False
wall_closer... | bigcode/self-oss-instruct-sc2-concepts |
def build_path(node):
"""
Builds a path going backward from a node
Args:
node: node to start from
Returns:
path from root to ``node``
"""
path = []
while node.parent is not None:
path.append(node.state)
node = node.parent
return tuple(reversed(path)) | bigcode/self-oss-instruct-sc2-concepts |
def constant(wait_time):
"""
Returns a function that just returns the number specified by the wait_time argument
Example::
class MyUser(User):
wait_time = constant(3)
"""
return lambda instance: wait_time | bigcode/self-oss-instruct-sc2-concepts |
def api_handler(*, name=None):
"""
Decorator for API handlers with method names not matching
their command names.
:param name: Command name for the function
:return: Wrapper function to set the name
"""
def predicate(func):
func.__api_name__ = name if name else func.__name__... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_sneden(whichdata):
""" Loading the r-process isotopes from Sneden et al. 2008 (pickled in SMHR) """
assert whichdata in ['rproc','sproc','sneden'], whichdata
_datadir = "/Users/alexji/smhr/smh/data/isotopes"
datamap = {'rproc':'sneden08_rproc_isotopes.pkl',
'sproc... | bigcode/self-oss-instruct-sc2-concepts |
def fetchUserPubKeys(conn):
"""
Returns array containing (discord_id, stellar_public_key) tuples
"""
c = conn.cursor()
c.execute("SELECT user_id, stellar_account FROM users")
return c.fetchall() | bigcode/self-oss-instruct-sc2-concepts |
def plot_shape(ax, xaxis, yaxis, zaxis, plot_3d, data, linewidth):
"""Plot shape and return line.
Args:
ax (matplotlib.axes.Axes): axis
xaxis (int): indicate which data to plot on the x-axis (0 for x, 1 for y, 2 for z)
yaxis (int): indicate which data to plot on the y-axis (0 for x, 1 f... | bigcode/self-oss-instruct-sc2-concepts |
def _quote(expr: str) -> str:
"""Quote a string, if not already quoted."""
if expr.startswith("'") and expr.endswith("'"):
return expr
return f"'{expr}'" | bigcode/self-oss-instruct-sc2-concepts |
def is_not_none(sample):
"""
Returns True if sample is not None and constituents are not none.
"""
if sample is None:
return False
if isinstance(sample, (list, tuple)):
if any(s is None for s in sample):
return False
if isinstance(sample, dict):
if any(s is ... | bigcode/self-oss-instruct-sc2-concepts |
def user_can_comment(user):
"""check if user has permission to comment
:user: user to be check
:returns: boolean
"""
return user.is_authenticated and user.has_perm('restaurants.can_comment') | bigcode/self-oss-instruct-sc2-concepts |
def getEnrichementFractionFromDelta(desired_delta, reference_ratio = 0.011115):
"""
Calculates the enrichment fraction given a desired delta value using a reference ratio.
"""
ratio = (desired_delta / 1000. + 1) * reference_ratio
fraction = ratio / (1 + ratio)
return fraction | bigcode/self-oss-instruct-sc2-concepts |
def typeddict(expected_k, expected_v):
"""Return a dictionary that enforces a key/value type signature.
>>> tdict = typeddict(int, str)
>>> mydict = tdict()
>>> mydict[3] = 'three'
But this fails:
>>> mydict['3'] = 'three'
"""
class TypedDict(dict):
def __setitem__(self, k, v)... | bigcode/self-oss-instruct-sc2-concepts |
def find_header_row(sheet, header_start):
"""
Finds the header row number in a sheet of an XLRD Workbook.
:param sheet: Input sheet
:param header_start: Header pattern (a substring of the first header)
:return: Row number for the header row
"""
row_number = 0
for row in sheet.get_rows()... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import Optional
from typing import Dict
import json
def find_maybe_info_json(absolute_directory_path: Path) -> Optional[Dict]:
"""
Recursively search parent folders to find the closest info.json file.
"""
possible_info_json_path = absolute_directory_path.joinpath(... | bigcode/self-oss-instruct-sc2-concepts |
import hmac
import hashlib
def sign(key, msg):
"""Make sha256 signature"""
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() | bigcode/self-oss-instruct-sc2-concepts |
def get_dir(xy):
"""
|NW|N |NE|
+--+--+--+
|W |C |E |
+--+--+--+
|SW|S |SE|
"""
if xy == (0, 0):
return "NW"
elif xy == (0, 1):
return "N"
elif xy == (0, 2):
return "NE"
elif xy == (1, 0):
return "W"
elif xy == (1, 1):
return "C"
... | bigcode/self-oss-instruct-sc2-concepts |
def format_qnode(qnode: str) -> str:
"""Formats a qnode with the required prefix.
"wd:" is prepended for qnodes and "wdt:" is prepended for pnodes.
Args:
qnode: Unformatted qnode.
Returns:
Formatted qnode.
"""
return f"wd:{qnode}" if qnode.startswith("Q") else f"wdt:{qnode}" | bigcode/self-oss-instruct-sc2-concepts |
def address(corporation):
"""Get billing address of Apple subsidiary with given handle"""
if corporation == 'AU':
return """Apple Pty Limited
Level 3
20 Martin Place
Sydney South 2000
Australia"""
elif corporation == 'CA':
return """Apple Canada Inc.
120 Bremner Boulevard, Suite 1600
Toronto... | bigcode/self-oss-instruct-sc2-concepts |
def get_note_freq(note: int) -> float:
"""Return the frequency of a note value in Hz (C2=0)."""
return 440 * 2 ** ((note - 33) / 12) | bigcode/self-oss-instruct-sc2-concepts |
def process_single_text(raw_text, max_seq_length, encoder,
BOS_token, EOS_token, PAD_token):
"""Processes a single piece of text. Performs BPE encoding,
converting to indexes, truncation, and padding, etc.
"""
# BPE
tokens = encoder.encode(raw_text)
# Truncate
max_le... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_show_spanning_tree(raw_result):
"""
Parse the 'show spanning-tree' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show spanning-tree \
command in a dictionary of the form:
::
{
... | bigcode/self-oss-instruct-sc2-concepts |
def propfind_mock(url, request):
"""Simulate a PROPFIND request."""
content = b"""
<d:multistatus xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/">
<d:response>
<d:href>/radicale/user@test.com/contacts/</d:href>
<d:propstat>
<d:prop>
<d:sync-token>http://mo... | bigcode/self-oss-instruct-sc2-concepts |
def make_rand_vector(dims, random_state):
"""
Generate a random unit vector. This works by first generating a vector each of whose elements
is a random Gaussian and then normalizing the resulting vector.
"""
vec = random_state.normal(0, 1, dims)
mag = sum(vec ** 2) ** .5
return vec / ma... | bigcode/self-oss-instruct-sc2-concepts |
def _ExpandTabs(text, column, tabsize, mark_tabs=False):
"""Expand tab characters in a string into spaces.
Args:
text: a string containing tab characters.
column: the initial column for the first character in text
tabsize: tab stops occur at columns that are multiples of tabsize
mark_tabs: if true,... | bigcode/self-oss-instruct-sc2-concepts |
def find_in_dict(obj, key):
"""
Recursively find an entry in a dictionary
Parameters
----------
obj : dict
The dictionary to search
key : str
The key to find in the dictionary
Returns
-------
item : obj
The value from the dictionary
"""
if key... | bigcode/self-oss-instruct-sc2-concepts |
def verify_dlg_sdk_proj_env_directory(path):
"""
Drive letter is not allowed to be project environment.
Script checks in parent of 'path': a drive letter like C: doesn't have a parent.
"""
if(path.find(":\\")+2 >= len(path)): # If no more characters after drive letter (f.e. "C:\\").
return False
else:
return ... | bigcode/self-oss-instruct-sc2-concepts |
def tagsDict_toLineProtocolString(pTagsDict:dict):
"""Converts a tags dictionnary to a valid LineProtocol string."""
retval = ''
for lTagName in pTagsDict:
lTagValue = pTagsDict[lTagName]
# See https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/#special-characters
if type(lTagV... | bigcode/self-oss-instruct-sc2-concepts |
def clean_refvar(refvar: str) -> str:
"""Cleans refvar string of characters that cause issues for filenames.
Args:
refvar: A string representing a refvar.
Returns:
A cleaned string.
"""
refvar = refvar.replace(" ", "_")
refvar = refvar.replace("/", "_")
return refvar | bigcode/self-oss-instruct-sc2-concepts |
def make_markdown_links(config):
"""Make Markdown links table from configuration."""
if not config.links_data:
return ""
return "\n\n" + "\n".join(
f"[{ln['key']}]: {ln['url']}" for ln in config.links_data
) | bigcode/self-oss-instruct-sc2-concepts |
def split_list(alist, wanted_parts=1):
"""Split a list to the given number of parts."""
length = len(alist)
# alist[a:b:step] is used to get only a subsection of the list 'alist'.
# alist[a:b] is the same as [a:b:1].
# '//' is an integer division.
# Without 'from __future__ import division' '/' ... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import Dict
def ploidy_file_to_dict(ploidy_file: Path) -> Dict[str, int]:
"""
Generates a dictionary from a ploidy tsv file
:param ploidy_file:
:return: A dictionary of contigs and their ploidy
"""
ploidy_dict = dict()
with ploidy_file.open("r") as file... | bigcode/self-oss-instruct-sc2-concepts |
def cube_contains_coords(cube, *coords):
"""Check whether the given cube contains all the requested coordinates."""
for coord in coords:
if not cube.coords(coord):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def find_argmax(topics_list):
""" returns the maximum probability topic id in a
[(topic_id, topic_prob)...] topics distribution """
m = -1.
r_tid = -1
for tid, tprob in topics_list:
if tprob > m:
m = tprob
r_tid = tid
return r_tid | bigcode/self-oss-instruct-sc2-concepts |
def _gtn_get_all_leaves(self):
"""
Get all the leaves under this node
"""
if '_children' not in self.__dict__:
return [self]
l = []
for n in self.children:
l.extend(n.get_all_leaves())
return l | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_movienames(theater_chain):
"""
Given a 'cadena' data structure, returns a set of (unique) movie names.
"""
data = set()
# We just need unique movie names, in no particular order
for theater in theater_chain.theaters:
for movie in theater.movies:
# print '-- %s'% movie.name
data.add(mov... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def html_fragment(source):
"""
Parse an HTML string representing a single element, and return that element
"""
return BeautifulSoup(source, 'html.parser').contents[0] | bigcode/self-oss-instruct-sc2-concepts |
def work_grid(grid, fig):
"""Take a two dimensional grid, add subplots to a figure for each cell and do layer work.
Parameters:
-----------
grid: a two dimensional grid of layers
fig: matplotlib figure to draw on
Returns:
--------
axes: a two dimensional list of matplotlib axes
"""... | bigcode/self-oss-instruct-sc2-concepts |
def get_bookmarks_slug_for(instance):
"""Returns the slug for a bookmark menu valid for the given model instance.
"""
kls = instance.__class__
return "%s_%d_bookmarks" % (kls.__name__.lower(), instance.pk) | bigcode/self-oss-instruct-sc2-concepts |
def count_bags(bags, bag):
"""Recursively count the bags of each type."""
if not bags.get(bag):
return 1
else:
counter = 0
for bag_a in bags[bag]:
counter += count_bags(bags, bag_a) * bags[bag][bag_a]
return counter + 1 | bigcode/self-oss-instruct-sc2-concepts |
def get_taxon_id(page):
"""Get the taxon ID from the page."""
taxon_id = page.select_one('#carregaTaxonGrupoIdDadosListaBrasil')
taxon_id = taxon_id['value']
return taxon_id | bigcode/self-oss-instruct-sc2-concepts |
def yen(value):
"""Format value as YEN."""
return f"¥{value:,}" | bigcode/self-oss-instruct-sc2-concepts |
import torch
def batch_lookup(M, idx, vector_output=True):
"""
Perform batch lookup on matrix M using indices idx.
:param M: (Variable) [batch_size, seq_len] Each row of M is an independent population.
:param idx: (Variable) [batch_size, sample_size] Each row of idx is a list of sample indices.
:p... | bigcode/self-oss-instruct-sc2-concepts |
def least_common(column):
"""
>>> least_common(["0", "0", "1"])
'1'
>>> least_common(["1", "1", "0", "0", "1"])
'0'
"""
occurs = {}
for bit in column:
occurs[bit] = occurs.get(bit, 0) + 1
if occurs["0"] == occurs["1"]:
return "0"
return min(occurs, key=lambda v: o... | bigcode/self-oss-instruct-sc2-concepts |
def soft_capitalize(string: str):
"""Capitalizes string without affecting other chars"""
return f"{string[0].upper()}{string[1:]}" | bigcode/self-oss-instruct-sc2-concepts |
def add_prefix(dic, prefix):
"""Adds a prefix to every key in given dictionary."""
return {f'{prefix}_{key}': value for key, value in dic.items()} | bigcode/self-oss-instruct-sc2-concepts |
from re import match
def introspect_file(file_path, re_term):
"""
Takes a (str) file_path and (str) re_term in regex format
Will introspect file_path for the existance of re_term
and return True if found, False if not found
"""
try:
ifile = open(file_path, "r")
except:
retu... | bigcode/self-oss-instruct-sc2-concepts |
import re
def IsJunk(contig):
"""returns true, if contigs is likely to be junk.
This is done by name matching. Junk contigs contain either
one of the following:
random, unknown, chrU, chU.
"""
c = contig.lower()
negative_list = "random", "unknown", "chru", "chu"
for x in negative_l... | bigcode/self-oss-instruct-sc2-concepts |
def gateway(arg):
"""Return a regex that captures gateway name"""
assert isinstance(arg, str)
return r"(?P<%s>[\w_\-@\' \.]+)" % (arg,) | bigcode/self-oss-instruct-sc2-concepts |
def last_posted_user_name(ticket):
"""
Get the username of the last post created
:param ticket: The requested ticket to get last post for
:return: username of last post
"""
last_post = ticket.posts.all().order_by('created_at').last()
return last_post.user.username | bigcode/self-oss-instruct-sc2-concepts |
def email_delete(imap, uid):
"""Flag an email for deletion.
"""
status, response = imap.store(str(uid), '+FLAGS', '\Deleted')
return status, response | bigcode/self-oss-instruct-sc2-concepts |
def backup_policy_filename(name):
""" Generate a .old file from a policy name or path """
return '{0}.old'.format(name) | bigcode/self-oss-instruct-sc2-concepts |
def countRun(s, c, maxRun, count):
"""parameter s: a string
parameter c: what we're counting
parameter maxRun: maximum length of run
returns: the number of times that string occurs in a row"""
"""
trial:
def countRunHelp(s,c,maxRun, count):
if count == maxRun:
return... | bigcode/self-oss-instruct-sc2-concepts |
def _tensors_names_set(tensor_sequence):
"""Converts tensor sequence to a set of tensor references."""
# Tensor name stands as a proxy for the uniqueness of the tensors.
# In TensorFlow 2.x one can use the `experimental_ref` method, but it is not
# available in older TF versions.
return {t.name for t in tenso... | bigcode/self-oss-instruct-sc2-concepts |
def compute_loss_ref_gen(generation, reflection):
"""
Compute loss percentage based on a generation count and a reflection count.
"""
if generation != 0:
loss = (1.0 - reflection / generation)*100
else:
loss = (1.0 - reflection / (generation+0.1))*100
return loss if loss >=0 el... | bigcode/self-oss-instruct-sc2-concepts |
def get_bin_number(bins, val):
"""
Gets the bin number of a value in a binspace
Parameters
==========
bins :: list
The bin edges
val :: real number
The value to get the bin number for
Returns
=======
The bin number of the test value. -1 if it is not within the binspace
"""
for i in range(l... | bigcode/self-oss-instruct-sc2-concepts |
def first_vs_rest(first_func, rest_func=lambda w: w):
"""Supply one or two transformer functions for the first and rest of
words respectively.
Leave second argument out if you want all but the first word to be passed
through unchanged.
Set first argument to None if you want the first word to be pas... | bigcode/self-oss-instruct-sc2-concepts |
def make_event_cname(ev_spec) -> str:
"""Create a transition connector name based on an event name and an optional signature"""
if not ev_spec.signature:
return ev_spec.name
else:
return ev_spec.name + '( ' + ', '.join( [f'{p.name}:{p.type}' for p in ev_spec.signature]) + ' )' | bigcode/self-oss-instruct-sc2-concepts |
def happy_color(health):
"""Return pyplot color for health percentage."""
if health > 0.8:
return 'g'
if health > 0.6:
return 'y'
return 'r' | bigcode/self-oss-instruct-sc2-concepts |
def remaining_evals(cur_step, epoch, train_steps_per_epoch, evals_per_epoch):
"""Helper function to calculate remaining evaluations for a trainer.
Args:
cur_step: current step of the supervised trainer
epoch: current epoch of the RL trainer
train_steps_per_epoch: supervised trainer steps per RL epoch
... | bigcode/self-oss-instruct-sc2-concepts |
import click
def serror(message, *args, **kwargs):
"""Print a styled error message."""
if args or kwargs:
message = message.format(*args, **kwargs)
return click.secho(message, fg='white', bg='red', bold=True) | bigcode/self-oss-instruct-sc2-concepts |
def check_script(script):
""" Checks if a given string is a script (hash160) (or at least if it is formatted as if it is).
:param script: Script to be checked.
:type script: hex str
:return: True if the signatures matches the format, raise exception otherwise.
:rtype: bool
"""
if not isins... | bigcode/self-oss-instruct-sc2-concepts |
def unquote_option_value(value):
"""Remove quotes from a string."""
if len(value) > 1 and value[0] in ('"', "'") and value[0] == value[-1]:
return value[1:-1]
return value | bigcode/self-oss-instruct-sc2-concepts |
def bisect_find(n, f, *args, **kw):
"""
Find largest `k` for which `f(k)` is true.
The k is integer in range 1 <= k <= n. If there is no `k` for which
`f(k)` is true, then return `0`.
:param n: Range for `k`, so :math:`1 <= k <= n`.
:param f: Invariant function accepting `k`.
:param *args... | bigcode/self-oss-instruct-sc2-concepts |
import re
def lineMatching(regexStr, lines):
""" Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified regex string, or None if no match was found
Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() ins... | bigcode/self-oss-instruct-sc2-concepts |
import smtplib
def connect(smtp_server, smtp_port, email, password):
"""
Connect to the SMTP server to send emails.
:param smtp_server: Hostname or IP Address of the SMTP server
:param smtp_port: Port number of the SMTP server.
:param email: Valid email address for authentication.
:param pass... | bigcode/self-oss-instruct-sc2-concepts |
def rgb_hex_to_rgb_list(hex_string):
"""Return an RGB color value list from a hex color string."""
return [int(hex_string[i:i + len(hex_string) // 3], 16)
for i in range(0,
len(hex_string),
len(hex_string) // 3)] | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_latest_hub_per_task(hub_module_paths):
"""Get latest hub module for each task.
The hub module path should match format ".*/hub/[0-9]*/module/.*".
Example usage:
get_latest_hub_per_task(expand_glob(["/cns/el-d/home/dune/representation/"
"xzhai/1899361/*... | bigcode/self-oss-instruct-sc2-concepts |
import time
def search_updated_intrusion_prevention_rules(api, configuration, api_version, api_exception, num_days):
""" Searches for Intrusion Prevention rules that have been updated within a specific number of days.
:param api: The Deep Security API modules.
:param configuration: Configuration object t... | bigcode/self-oss-instruct-sc2-concepts |
def sexp(self, labr="", lab1="", lab2="", exp1="", exp2="", **kwargs):
"""Forms an element table item by exponentiating and multiplying.
APDL Command: SEXP
Parameters
----------
labr
Label assigned to results. If same as existing label, the existing
values will be overwritten by t... | bigcode/self-oss-instruct-sc2-concepts |
import random
def get_random_integer(number):
"""
This function takes in a number and returns a random integer between 0 and that number
"""
return random.randint(0, number) | bigcode/self-oss-instruct-sc2-concepts |
def vectors_from_indices(bm, raw_vert_indices):
"""Return List of vectors from input Vertex Indices.
Args:
bm: Object Bmesh
raw_vert_indices: List of Chosen Vertex Indices
Returns:
List of Vertex coordinates.
"""
return [bm.verts[i].co for i in raw_vert_indices] | bigcode/self-oss-instruct-sc2-concepts |
def _has_matched_brackets(text: str) -> bool:
"""
Evaluate whether every opening bracket '[' in the 'text' has a matching closing bracket ']'.
:param text: the text.
:return: Boolean result, and associated message.
"""
open_bracket_stack = []
for index, _ in enumerate(text):
if text... | bigcode/self-oss-instruct-sc2-concepts |
def get_aliases(cur, cp):
"""get all aliases of a codepoint"""
cur.execute("SELECT alias FROM codepoint_alias WHERE cp = %s", (cp,))
return map(lambda s: s['alias'], cur.fetchall()) | bigcode/self-oss-instruct-sc2-concepts |
def select_matching_record(dataframe, linked_row, matching_col):
"""Return dataframe row based on matching column name"""
return dataframe[
dataframe[matching_col] == linked_row[matching_col]
].compute() | bigcode/self-oss-instruct-sc2-concepts |
import six
def column_info(df):
"""Returns a list of columns and their datatypes
Args:
df (`pandas.DataFrame`): The dataframe to get info for
Returns:
:type:`list` of :type:`dict`: A list of dicts containing column ids and their
Dtypes
"""
column_info = []
for co... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import tempfile
import gzip
def get_cif(code, mmol_number, outfile=None):
"""
Parameters
----------
code : str
PDB code.
mmol_number : int
mmol number (biological assembly number) of file to download. Numbers from PDBe.
If None, defaults to the preferred bio... | bigcode/self-oss-instruct-sc2-concepts |
import re
def read_data_table(filename: "str") -> "dict":
"""
Reads in a CSV file containing columnwise data for various elements, and returns a dictionary containing the data.
Lines beginning with "#" are ignored
:param filename: A valid filename for a csv file
:type filename: str
:return: A... | bigcode/self-oss-instruct-sc2-concepts |
def last_column_type(column_types):
"""Return the max order in the order types."""
return max([v['order'] for v in column_types.values()], default=0) | bigcode/self-oss-instruct-sc2-concepts |
def le16(data, start=0):
"""
Read value from byte array as a long integer
:param bytearray data: Array of bytes to read from
:param int start: Offset to start reading at
:return int: An integer, read from the first two bytes at the offset.
"""
raw = bytearray(data)
return raw[start] ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def svgparselength(lengthstr):
"""
Parse an SVG length string into a float and a units
string, if any.
:param lengthstr: SVG length string.
:return: Number and units pair.
:rtype: tuple(float, str|None)
"""
integer_re_str = r'[+-]?[0-9]+'
number... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_preamble(path):
"""
Parse preamble at path.
"""
with open(path, "r") as f:
preamble = f.read().split('\n')
return preamble | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def get_soup(url):
"""Given a url, returns a BeautifulSoup object of that page's html"""
web_page = requests.get(url)
return BeautifulSoup(web_page.text, "html.parser") | bigcode/self-oss-instruct-sc2-concepts |
def index_to_position(index, strides):
"""
Converts a multidimensional tensor `index` into a single-dimensional position in
storage based on strides.
Args:
index (array-like): index tuple of ints
strides (array-like): tensor strides
Return:
int : position in storage
"""
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Union
def ls_strip_elements(ls_elements: List[str], chars: Union[None, str] = None) -> List[str]:
"""
>>> ls_strip_elements([' a','bbb',' '])
['a', 'bbb', '']
>>> ls_strip_elements([])
[]
"""
if (not ls_elements) or (ls_elements is None):
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def get_scheduler_state(code: int) -> Optional[str]:
"""Translate an schduler state code to a human-readable state.
Official mapping is available
`here <https://github.com/BOINC/boinc/blob/master/py/Boinc/boinc_db.py>`.
Args:
code:
The code of scheduler stat... | bigcode/self-oss-instruct-sc2-concepts |
def _clean_join(content):
"""
Joins a list of values together and cleans (removes newlines)
:param content: A str or list of str to process
:return: The joined/cleaned str
"""
if not isinstance(content, str):
content = ''.join(content) if content else ''
return content.replace('\n', ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def py_is_none(x: Any) -> bool:
"""Check if x is None."""
return x is None | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.