content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def compare(gene, classes):
""" Compare the distribution of two or more groups and automatically selects
the proper statistical test
Args:
gene (string): feature to be compared.
classes (list of pandas dataframe): list of groups (classes) to compare.
... | 5,310,100 |
def test_descendants_to_path():
"""Test descendants to path."""
path = "a.b.c.d.e"
assert descendants_to_path(path) == ["a", "a.b", "a.b.c", "a.b.c.d", "a.b.c.d.e"] | 5,310,101 |
def get_powersph_errorbars(k, psph, params):
"""
Calculate the error bars on spherically-averaged P(k) (1-sigma uncertainty) as a function of k.
This is a convenience method, which calls the internal method.
Parameters
----------
k : 1D array
Values of k at which to calculate error bar... | 5,310,102 |
def encrypt_file(password, in_file, out_file):
""" Encrypt the contents of the given file.
Encrypts the contents of the in_file into the out_file.
:param password: The password for the file being encrypted.
:type password: str
:param in_file: The name of the file to encrypt.
:type in_file: str... | 5,310,103 |
def check_guide_input(df):
"""Check whether input DataFrame has expected format
- Column 1: first guide identifier
- Column 2: second guide identifier
- Column 3: first gene identifier
- Column 4: second gene identifier
- Column 5+: LFC values from different conditions
Parameters
-----... | 5,310,104 |
def test_save_load(tmp_path, model_class):
"""
Test if 'save' and 'load' saves and loads model correctly
and if 'get_parameters' and 'set_parameters' and work correctly.
''warning does not test function of optimizer parameter load
:param model_class: (BaseAlgorithm) A RL model
"""
env = D... | 5,310,105 |
def sum_poly_areas(lop: List[shapely.geometry.Polygon],) -> float:
"""
Returns a float representing the total area of all polygons
in 'lop', the list of polygons.
"""
sum_acc = 0
for poly in lop:
sum_acc += poly.area
return sum_acc | 5,310,106 |
def test_remove_trader_from_market_when_round_number_bigger_than_0(client, logged_in_user):
""" Testing the remove trader functionality when round number bigger than 0"""
market = MarketFactory(
round=7, created_by=logged_in_user)
trader = TraderFactory(market=market)
# Trader is not removed by... | 5,310,107 |
def writeMarkdown_p (html, output):
"""Writes the `html` `<p>` to `output` stream as Markdown text."""
output.write(f'{textwrap.fill( replace_inline(html) )}\n\n') | 5,310,108 |
def build_importer_component_spec(
importer_base_name: str,
input_name: str,
input_type_schema: pipeline_spec_pb2.ArtifactTypeSchema,
) -> pipeline_spec_pb2.ComponentSpec:
"""Builds an importer component spec.
Args:
importer_base_name: The base name of the importer node.
dependent_task: The tas... | 5,310,109 |
def hpat_pandas_series_max(self, axis=None, skipna=None, level=None, numeric_only=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.max
Limitations
-----------
Parameters ``axis``, ``level`` and ``numeric_only`` a... | 5,310,110 |
def train_predictor(predictor,
train_data,
train_target,
hyperparameter,
metric='accuracy',
n_folds=5):
"""
Cross validation training in order to find best parameter.
:param predictor:
:param train_data:... | 5,310,111 |
def make_vector_laplace(bcs: Boundaries) -> Callable:
"""make a discretized vector laplace operator for a cylindrical grid
{DESCR_CYLINDRICAL_GRID}
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
{ARG_BOUNDARIES_INSTANCE}
Returns:
A function that can be applied... | 5,310,112 |
def test_Bernoulli():
"""Tests Bernoulli distribution"""
# Create the distribution
dist = pfd.Bernoulli(0)
# Check default params
assert dist.logits == 0
assert dist.probs is None
# Call should return backend obj
assert isinstance(dist(), tfd.Bernoulli)
# Test methods
assert ... | 5,310,113 |
def test_detail_view_shows_journal_detail(dummy_request, new_journal):
"""Test detail view show journal details."""
dummy_request.dbsession.add(new_journal)
dummy_request.dbsession.commit()
dummy_request.matchdict['id'] = 1
response = detail_view(dummy_request)
assert response['Journal'] == new_... | 5,310,114 |
def extract_keys(key: bytes) -> str:
"""Derive a key1,key2, key3 from a password str and returns a hex tuple (key1, key2, key3) """
digest = hashlib.sha256(key).digest()
key1 = hexlify(digest)
key2 = hashlib.sha256(digest).hexdigest()
key3 = hashlib.sha256(hashlib.sha256(digest).digest()).hexdigest(... | 5,310,115 |
def XX_using_param_ISWAP(q0, q1, angle):
"""
Return a generator that executes e^{i angle XX} using the
parameterized ISWAP gate
Args:
q0: qubit 0
q1: qubit 1
Returns:
Generator for a cirq.Operation implementings e^{i angle XX}
"""
iswap = cirq.ISWAP.on(q0, q1) *... | 5,310,116 |
def add_user(user):
""" Add a user in the database
return Boolean
"""
try:
with session_scope() as session:
u = User(**user)
session.add(u)
return True, None
except exc.IntegrityError as e:
return False, str(e) | 5,310,117 |
def _port_speed_prices_table(port_speeds, prices=False):
"""Shows Server Port Speeds prices cost and capacity restriction.
:param [] port_speeds: List of Hardware Server Port Speeds.
:param prices: Create a price table or not
"""
if prices:
table = formatting.Table(['Key', 'Speed', 'Hourly'... | 5,310,118 |
def conversion(pid, offset, sequences, directory, file_count):
"""
This function calls all functions required for the full latex to png conversion for a subset of the sequences.
It is meant to be called for a single process. The respective subset depends on the given offset.
:param pid: The identifier ... | 5,310,119 |
def create_javadoc(self):
"""
Creates a javadoc task (feature 'javadoc')
"""
tsk = self.create_task('javadoc')
tsk.classpath = getattr(self, 'classpath', [])
self.javadoc_package = Utils.to_list(self.javadoc_package)
if not isinstance(self.javadoc_output, Node.Node):
self.javadoc_output = self.bld.path.find_or... | 5,310,120 |
def conv_nested(image, kernel):
"""A naive implementation of convolution filter.
This is a naive implementation of convolution using 4 nested for-loops.
This function computes convolution of an image with a kernel and outputs
the result that has the same shape as the input image.
Args:
ima... | 5,310,121 |
def get_cheque_code(cheque: str):
"""Get code"""
if (
re.search(r'BTC_CHANGE_BOT\?start=', cheque)
or not re.search(r'BTC_CHANGE_BOT\?start=', cheque)
and re.search(r'Chatex_bot\?start=', cheque)
):
return re.findall(r'c_\S+', cheque)[0]
elif re.search(r'Getwa... | 5,310,122 |
def findKthLargest(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# sol 1
# nums.sort()
# return nums[-k]
# sol 2
# return select(nums, 0, len(nums)-1, k)
# sol 3
return search(nums,k) | 5,310,123 |
def check_round_change(fromBlock, toBlock):
"""Checks for round initilized txs between blockOld and block.
If an event exists, get the blocknumber of this tx and the round number
"""
round_filter = w3.eth.filter({
"fromBlock": fromBlock,
"toBlock": toBlock,
"address": ROUND_MANAGER_PROX... | 5,310,124 |
def chown_repo(cx, spec=DEFAULT_USER_SPEC):
"""Give dev group access to repo"""
spec = toml.load(spec)
cx.sudo(f"chown :{spec['dev_group']} -R .") | 5,310,125 |
def check_online(stream):
"""
Used to check user's online opponents and show their online/offline status on page on init
"""
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
opponent_username = packet.get('username')
if session_id and op... | 5,310,126 |
def async_phonology(args, task_key, cache_kwargs, storage, sqlalchemy_url):
"""
Asynchronous phonology compilation.
"""
# This is a no-op with current settings, we use it to enable logging inside celery tasks, because
# somehow this does it, and otherwise we couldn't set it up.
logging.debug('... | 5,310,127 |
def dice_coef_loss(target, prediction, axis=(1,2,3), smooth=1.0):
"""
Sorenson Dice loss
Using -log(Dice) as the loss since it is better behaved.
Also, the log allows avoidance of the division which
can help prevent underflow when the numbers are very small.
"""
intersection = tf.reduce_sum(... | 5,310,128 |
def enable_server_reflection(service_names, server, pool=None):
"""Enables server reflection on a server.
Args:
service_names: Iterable of fully-qualified service names available.
server: grpc.Server to which reflection service will be added.
pool: DescriptorPool object to use (descriptor_poo... | 5,310,129 |
def option_names_not_in_cfg(cfg, options):
"""
Returns names of *options* not seen in the *cfg* dictionary, typically
parsed from an external configuration file.
Parameters
----------
cfg : dict
options : :py:class:`~enrich2.plugins.options.Options`
Returns
-------
`list`
... | 5,310,130 |
def _unpack_data(buffer):
"""Unpack received data
>>> d = _unpack_data(bytes.fromhex('AA 11 00 08 00 BC 6E 00 3E 9C 01 89 00 00 1E 26 0F 0F 08 13 9E'))
>>> d == {"datetime": "2019-08-15 15:38:30", "V": 105.534, "mA": 221.46875, "W": 0.685}
True
Args:
buffer (bytes): Data received from ... | 5,310,131 |
def fit_mgauss(x, y, x0, n, c=(-np.inf, np.inf), thresh=-1, ftol=1e-4, xtol=1e-4, scale=0, maxiter=100, verbose=False):
"""
Fit a symmetric multigauss to the provided 1-D data.
*Arguments*:
- x = x values of data to fit.
- y = y values of data to fit.
- x0 = the initial guess as a stacked (1... | 5,310,132 |
def list_files_with_extension(root_path, extension, full_path=True,
recursively=True):
"""List all files paths in a folder, filtered by a given suffix.
Parameters
----------
root_path : Path
Top level folder, start search here.
extension : str
Extension... | 5,310,133 |
def get_power_online(signal: ComplexTensor) -> torch.Tensor:
"""Calculates power for `signal`
Args:
signal : Single frequency signal
with shape (F, C, T).
axis: reduce_mean axis
Returns:
Power with shape (F, )
"""
power = signal.real ** 2 + signal.imag ** 2
... | 5,310,134 |
def transform(model, pretrained=False, gamma=0.9, mem=False):
"""Return the MomentumNet counterpart of the model
Parameters
----------
model : a torchvision model
The resnet one desires to turn into a momentumnet
pretrained : bool (default: False)
Whether using a pretrained resnet ... | 5,310,135 |
def iam_user_list(aws_config=None):
"""
@type aws_config: Config
"""
iam_client = get_client(client_type='iam', config=aws_config)
users_response = iam_client.list_users()
mfa_devices_response = iam_client.list_virtual_mfa_devices(AssignmentStatus='Assigned')
mfa_devices = mfa_devices_respon... | 5,310,136 |
def test_method__change_tab(config_multiple, capsys, random_string):
"""Tests menu._change_tab"""
c = deepcopy(config_multiple)
c["tabs"][1]["tab_header_input"] = random_string[:3]
c["tabs"][1]["tab_header_description"] = random_string[3:7]
c["tabs"][1]["tab_header_long_description"] = random_string... | 5,310,137 |
def getListArrayDim(self, ainput, dim=0):
"""
get the dimension of a list
returns -1 if it is no list at all, 0 if list is empty
and otherwise the dimensions of it
"""
if isinstance(ainput, (list, np.ndarray)):
if ainput == []:
return dim
dim = dim + 1
dim =... | 5,310,138 |
def exp_two(arg1, arg2):
""" (float, float) -> float
Exponentiates two numbers (arg1 ** arg2)
Returns the exponent
"""
try:
return arg1 ** arg2
except TypeError:
return 'Unsupported operation: {0} ** {1} '.format(type(arg1), type(arg2)) | 5,310,139 |
def crud_exceptions(fn):
"""A decorator designed to catch exceptions from the crud api methods."""
@wraps(fn)
def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except:
a = [x for x in (args or [])]
kw = {k : v for k, v in (kwargs or {}).items()... | 5,310,140 |
def test_branched_history(pytester):
"""Branched history can be navigated, when there's no mergepoint present."""
run_pytest(pytester, passed=4) | 5,310,141 |
def train_opts(parser: argparse.ArgumentParser, require: bool = True) -> None:
# pylint: disable=unused-argument
"""Add options specific to a training task."""
group = parser.add_argument_group("Training options")
group.add_argument(
"--char-features",
default="lstm",
type=str,
... | 5,310,142 |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
return [len(p) for p in lines] | 5,310,143 |
def decode_trace_resp(payload, offset, trace_resp_header_values):
"""Decode headers for a OAM Trace Response"""
sf_type = None
sf_name = None
trace_header = payload[offset:offset+NSH_OAM_TRACE_HDR_LEN]
_header_values = struct.unpack('!B B H I I I I', trace_header)
trace_resp_header_values.oam_... | 5,310,144 |
def standard_lv(env_name, remove_q=True, static_feeds_new=None, clear_loads_sgen=False, clear_gen=True,
battery_locations=None, percent_battery_buses=0.5, batteries_on_leaf_nodes_only=True, init_soc=0.5,
energy_capacity=20.0, gen_locations=None, gen_p_max=0.0, gen_p_min=-50.0,
... | 5,310,145 |
def oauth_require_read_schema_scope(f: 'Callable[..., Any]'):
"""(User以外の)メタデータを読むだけのScopeデコレータ.
:param Callable f: Function
"""
from .authorize import oauth
return oauth.require_oauth(CRScope.SCHEMA_R.value, CRScope.SCHEMA_RW.value)(f) | 5,310,146 |
def load_content(site, host, links):
"""Tests a site."""
# Security: Verified HTTPS with SSL/TLS
http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED', # Force certificate check.
ca_certs=certifi.where(), # Path to the Certifi bundle.
)
start_page_search = """https://startpage.com/d... | 5,310,147 |
def include(node):
"""Add armadillo to header"""
program = node.program
includes = program[0]
arma = "#include <armadillo>"
namespace = "using namespace arma ;"
if arma in includes and namespace in includes:
return
if arma not in includes:
include = matlab2cpp.collection.... | 5,310,148 |
def flag(request, comment_id, next=None):
"""
Flags a comment. Confirmation on GET, action on POST.
Templates: :template:`comments/flag.html`,
Context:
comment_id
The id of the comment the user is flagging.
"""
comment = get_object_or_404(
get_comment_model(),
... | 5,310,149 |
def decodeGsm7(encodedText):
""" GSM-7 text decoding algorithm
Decodes the specified GSM-7-encoded string into a plaintext string.
@param encodedText: the text string to encode
@type encodedText: bytearray or str
@return: A string containing the decoded text
@rtype: str
"""
... | 5,310,150 |
def test_atomic_date_time_min_inclusive_nistxml_sv_iv_atomic_date_time_min_inclusive_1_4(mode, save_output, output_format):
"""
Type atomic/dateTime is restricted by facet minInclusive with value
1970-01-01T00:00:00.
"""
assert_bindings(
schema="nistData/atomic/dateTime/Schema+Instance/NISTS... | 5,310,151 |
def Setup_Meta():
"""Setup_Meta() -> MetaObject"""
return _DataModel.Setup_Meta() | 5,310,152 |
def get_types_dict():
"""
:return: type name read in as string to type method mapping
"""
return {"str": str, "float": float, "int": int} | 5,310,153 |
def key_pressed(key):
"""
Takes a key, that's either a keycode or a character,
and says if it was pressed down this frame.
"""
keycode = _to_keycode(key)
return (keycode in current_frame_held_buttons) and \
(keycode not in last_frame_held_buttons) | 5,310,154 |
def makeDir(path, name):
""" create dir for the generation process"""
print "path", path
print "name",name
dirname = path + os.sep + name
try:
os.makedirs(dirname)
return dirname
except:
print "makeDir> ERROR creating dir [%s]: %s" % (dirname, exc_info()[1])
retur... | 5,310,155 |
def load_gp(param_file=None, **kwargs):
"""Return two Gaussian Processes objects, either using BSFH's internal GP
objects or George.
:returns gp_spec:
The gaussian process object to use for the spectroscopy.
:returns gp_phot:
The gaussian process object to use for the photometry.
"... | 5,310,156 |
def monte_carlo(model, num, qobs=None, **kwargs):
"""Perform Monte-Carlo-Simulation.
This function performs a Monte-Carlo-Simulation for any given hydrological
model of this repository.
Args:
model: Any instance of a hydrological model of this repository.
num: Number of simulations.
... | 5,310,157 |
def read_file_sql(
path: Union[str, "os.PathLike[Any]"],
sql_stmt: str,
sql_dialect: str = "SQLITE",
layer: Optional[str] = None,
ignore_geometry: bool = False,
) -> Union[pd.DataFrame, gpd.GeoDataFrame]:
"""
Reads a file to a GeoPandas GeoDataFrame, using an sql statement to filter
the ... | 5,310,158 |
def create_class_hierarchy_dict(cls):
"""Returns the dictionary with all members of the class ``cls`` and its superclasses."""
dict_extension_order = cls.__mro__[-2::-1] # Reversed __mro__ without the 'object' class
attrs_dict = {}
for base_class in dict_extension_order:
attrs_dict.update(vars(... | 5,310,159 |
def get_column_selection(summary_set):
"""
Given a analysis_settings summary definition, return either
1. the set of OED columns requested to group by
2. If no information key 'oed_fields', then group all outputs into a single summary_set
:param summary_set: summary group dictionary from th... | 5,310,160 |
def randomForestSearch(
operations: OperatorSet,
output: List[Individual],
start_candidates: List[Individual],
max_evaluations: Optional[int] = None,
) -> List[Individual]:
""" Perform random search over all possible pipelines.
Parameters
----------
operations: OperatorSet
An op... | 5,310,161 |
def month_to_date(month):
"""
Convert month to date format.
Keyword arguments:
month -- the month to convert to date format
"""
month = datetime.strptime(month, '%Y-%m')
date = month.strftime('%Y-%m-%d') # eg 2018-02-01
date = datetime.strptime(date, '%Y-%m-%d') # return datetime ob... | 5,310,162 |
def test_keystore(tmpdir):
""" Test functionality of the keystore
"""
key = 'ABC'
store_path = tmpdir.mkdir('key').join('store')
key_path = tmpdir.join('key').join('key1')
utils.save_key(key, key_path)
store = utils.Keystore(store_path)
assert store.add_key('TEST', key_path)[1]
... | 5,310,163 |
def exact_cftime_datetime_difference(a, b):
"""Exact computation of b - a
Assumes:
a = a_0 + a_m
b = b_0 + b_m
Here a_0, and b_0 represent the input dates rounded
down to the nearest second, and a_m, and b_m represent
the remaining microseconds associated with date a and
date ... | 5,310,164 |
def encode(string):
"""Encode some critical characters to html entities."""
return string.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>') \
.replace(' ', ' ') \
.replace('\n', ... | 5,310,165 |
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
return rem(x-a, a) | 5,310,166 |
def update_movie(movie_id):
"""Route handler for endpoint updating a single movie.
Args:
movie_id: An int representing the identifier for the movie to update
Returns:
response: A json object representing info about the updated movie
"""
movie = Movie.query.get(movie_id)
if mov... | 5,310,167 |
def match_char_style(a, b):
"""
Name: match_char_style
Inputs: - docx.text.run.Run, run from original document (a)
- docx.text.run.Run, run for new document (b)
Outputs: None
Features: Edits a run object with the same font styles, including:
- bold, italic, underli... | 5,310,168 |
def note_list(request):
"""Notes list view
"""
notes = NoteTable(Note.objects.all())
RequestConfig(request).configure(notes)
return render(request, 'note_list.html', {'notes': notes}) | 5,310,169 |
def getDateTimeFromLocalTimeStamp(ts):
"""
Get a datetime structure from a timestamp.
"""
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
return st | 5,310,170 |
def c_roots(n, mu=False):
"""Gauss-Chebyshev (first kind) quadrature
Computes the sample points and weights for Gauss-Chebyshev quadrature.
The sample points are the roots of the `n`th degree Chebyshev polynomial of
the first kind, :math:`C_n(x)`. These sample points and weights correctly
integrat... | 5,310,171 |
def lamost(dr=2,cat='all'):
"""
NAME:
lamost
PURPOSE:
Load the LAMOST data
INPUT:
dr= (2) data release
cat= ('all') 'all', 'A', 'M', 'star' (see LAMOST docs)
OUTPUT:
data table
HISTORY:
2016-10-13 - Written - Bovy (UofT)
"""
filePath= path.lamost... | 5,310,172 |
def send_aws_email(recipient, email, question, url):
"""send email using SES, need to update so it can send to anyone"""
content = email_content(recipient, question, url)
email = Email(to=email, subject='Its been a while...')
email.text(content)
email.html(content)
email.send() | 5,310,173 |
def get_env_prefix():
"""
Automatically identify os_type information which use for
install path of bash_completion.d
"""
TARGET_BIN_PATH = '/usr/local/bin/'
os_type = platform.system()
cygwin = r'CYGWIN|cygwin'
if os_type == "Linux":
TARGET_COMPLETION_PATH = "/etc/bash_completio... | 5,310,174 |
def find_instance_nested(item, instances, match_key=None):
"""
Recursively find instances from lists, dicts, tuples.
`instances` should be a tuple of valid instances
If match_key is given the key must match for an instance to be added to the list of found instances.
"""
matches = []
def v... | 5,310,175 |
def get_filer_image(image_name="test_file.jpg", name="", original_filename=True):
"""
Creates and stores an image to filer and returns it
:param image_name: the name for the file (default "test_file.jpg")
:returns: filer image instance
"""
image = get_image(image_name)
filename = None
i... | 5,310,176 |
def check_output(args):
"""
Delegates to subprocess.check_output() if it is available, otherwise
provides a reasonable facsimile.
"""
if 'check_output' in dir(subprocess):
out = subprocess.check_output(args)
else:
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
out,... | 5,310,177 |
def import_table(file, sep = ","):
"""[Import table (csv or xlsx) into memory]
Args:
file ([string]): [file path]
sep (str, optional): [separator character that should be used]. Defaults to ",".
Returns:
[dataframe]: [the table imported]
"""
file_path = path_checker(file)
... | 5,310,178 |
def cli(ctx, dialect, driver, host, port, username, password, database):
"""Management of database for vmail-setup.
User config is loaded from ~/.config/vmail-manager/config.yaml.
Priority of options are OPTIONS > USER-CONFIG > DEFAULTS.
"""
for param in [
("dialect", dialect),
("d... | 5,310,179 |
def check_frequency(input):
"""
Perform counting based on input queries and return queries result.
Na wejściu otrzymujemy parę liczb całkowitych - operacja, wartość.
Możliwe operacje:
1, x: zlicz x
2, x: usuń jedno zliczenie x jeżeli występuje w zbiorze danych
3, x: wypisz liczbę zliczeń x ... | 5,310,180 |
def unixtime(tz = None):
"""
:param tz: [optional] tzinfo
:return: int
"""
return int(dt.datetime.now(tz).strftime('%s')) | 5,310,181 |
def demo7(response):
"""在每次请求后运行"""
# eg:修改响应头
print(response)
print('=========== after func run =============')
# response.headers['Content-Type'] = 'application/json;charset=utf-8;'
return response | 5,310,182 |
def build_distance_layers(cyt_coord, nuc_coord, rna_coord, normalized=True):
"""Compute distance layers as input for the model.
Parameters
----------
cyt_coord : np.ndarray, np.int64
Array of cytoplasm boundaries coordinates with shape (nb_points, 2).
nuc_coord : np.ndarray, np.int64
... | 5,310,183 |
def one_hot_encode(arr, classes=None):
"""
One-hot encode a 1D array.
Based on this StackOverflow answer: https://stackoverflow.com/a/29831596/5863503
Parameters:
-----------
arr : array-like
An array to be one-hot encoded. Must contain only non-negative integers
classes : int or No... | 5,310,184 |
def sql_connection():
"""
Establishes a connection to the SQL file database
:return connection object:
"""
path = os.path.abspath('./Twitter_Scraper_without_API/TwitterDatabase.db')
con = sqlite3.connect(path)
return con | 5,310,185 |
def _inc_service_counter(source_service, dest_service, count) -> None:
"""
_inc_service_counter increments Prometheus byte counters for traffic
between gateway and cloud Magma services
Args:
source_service: traffic source service name used as label
dest_service: traffic destination serv... | 5,310,186 |
def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,
select='a', select_range=None, max_ev=0, check_finite=True):
"""
Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
Find eigenvalues w and optionally right eigenvectors v of a::
a ... | 5,310,187 |
def identity(value):
"""
Node returning the input value.
"""
return value | 5,310,188 |
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
if CONFIG_MAIN_API_KEY in entry.data:
target_domain = "sensor"
elif CONFIG_TARGET_NAME in entry.data:
target_domain = "binary_sensor"
unload_ok = all(
await asyncio.gather(
*[hass.config_entries.asyn... | 5,310,189 |
def strip(input_file_name):
"""
Remove all leading and trailing white-spaces, from 'input_file_name'.
And output result into into current directory.
Args:
input_file_name (str): path to input file
Returns:
int : number of modified lines.
"""
modified_lines = 0
pattern = re.... | 5,310,190 |
def InsertVideoGame(cur, con):
""" Inserts a new Video Game into the database """
# Get information about the video game
print("Enter new Video Game's details:")
row = {}
row["Name"] = input("Enter the name of the Video Game: ") or None
row["ReleaseDate"] = input(
"Enter the release date... | 5,310,191 |
def render_post_ioc_init_elements(ioc: IOC) -> str:
"""
Render all of the post-iocInit elements for a given IOC instance
"""
return render_elements(ioc, "render_post_ioc_init") | 5,310,192 |
def getZnProjectors(xform_op, n_xforms, print_results=False):
"""
Returns operators which project on to symmetry subspaces associated with a given
symmetry transformation if the symmetry group is a cyclic group. Examples of appropriate
symmetries are translational or pure rotational symmetry.
... | 5,310,193 |
def test_page_attrs_from_content_path_(tmp_path, content):
"""Tests when given a file as the content_path, parse it into data """
fake_path = tmp_path / 'fake_path.md'
fake_path.write_text(content)
class TestPage(Page):
content_path = fake_path
t = TestPage()
assert t.title== 'Test T... | 5,310,194 |
def small_caves_multigraph():
"""
For each `big_cave` in `big_caves` and for each u, v in the neighborhood of `big_cave`,
add an edge (u, v) to `caves`. Afterwards, remove all big caves. The remaining
edges between the small caves now have multiplicity that can be used to count paths.
"""
caves... | 5,310,195 |
def train_model():
"""Train for a fixed number of steps and decode during training."""
rng = jax.random.PRNGKey(0)
model = create_model(rng)
optimizer = create_optimizer(model, FLAGS.learning_rate)
for step in range(FLAGS.num_train_steps):
batch = get_batch(FLAGS.batch_size)
optimizer, metrics = trai... | 5,310,196 |
def rescale(arr, low=0, high=1, axis=None):
"""Return rescaled array, with values scaled between ``low`` and ``high``
Parameters
----------
arr : ndarray
numpy array to be rescaled
low : float (array scalar) or ndarray, optional
specifies the lower value(s) of the rescaled array
... | 5,310,197 |
def named_numbers(token_vector):
""" Function to remove numbers out of an array of sentences.
Args:
token_vector (array): Array containing tokenized, lowercased sentence.
Returns:
array: Array containing tokenized sentence removed numbers.
"""
return token_vect... | 5,310,198 |
def parse_members_for_workspace(toml_path):
"""Parse members from Cargo.toml of the worksapce"""
with open(toml_path, mode='rb') as f:
data = f.read()
manifest = data.decode('utf8')
regex = re.compile(r"^members\s*=\s*\[(.*?)\]", re.S | re.M)
members_block = regex.findall(manifest)[0]
... | 5,310,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.