content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_dataframe_from_table(table_name, con):
"""
put table into DataFrame
"""
df = pd.read_sql_table(table_name, con)
return df | 8,800 |
def linkcard():
"""
Linking bank card to refill
"""
print("Linking card...")
pass | 8,801 |
def qemu_pos_add(target_name,
nw_name,
mac_addr,
ipv4_addr,
ipv6_addr,
consoles = None,
disk_size = "30G",
mr_partsizes = "1:4:5:5",
sd_iftype = 'virtio',
extra_cmdlin... | 8,802 |
def _find_links_in_headers(*, headers, target_headers: List[str]) -> Dict[str, Dict[str, str]]:
"""Return a dictionary { rel: { url: 'url', mime_type: 'mime_type' } } containing the target headers."""
found: Dict[str, Dict[str, str]] = {}
links = headers.get("link")
if links:
# [{'url': 'https:/... | 8,803 |
def calc_word_frequency(my_string, my_word):
"""Calculate the number of occurrences of a given word in a given string.
Args:
my_string (str): String to search
my_word (str): The word to search for
Returns:
int: The number of occurrences of the given word in the given string.
"... | 8,804 |
def asyn_lpa_communities(G, weight=None, seed=None):
"""Returns communities in `G` as detected by asynchronous label
propagation.
The asynchronous label propagation algorithm is described in
[1]_. The algorithm is probabilistic and the found communities may
vary on different executions.
The al... | 8,805 |
def _make_warmstart_dict_env():
"""Warm-start VecNormalize by stepping through BitFlippingEnv"""
venv = DummyVecEnv([make_dict_env])
venv = VecNormalize(venv)
venv.reset()
venv.get_original_obs()
for _ in range(100):
actions = [venv.action_space.sample()]
venv.step(actions)
... | 8,806 |
def explore(graph: UndirectedGraph, reporter: Reporter) -> None:
"""Naive Bron-Kerbosch algorithm, optimized"""
if candidates := graph.connected_vertices():
visit(graph=graph,
reporter=reporter,
candidates=candidates,
excluded=set(),
clique=... | 8,807 |
def train_eval(
root_dir,
env_name='CartPole-v0',
num_iterations=1000,
# TODO(b/127576522): rename to policy_fc_layers.
actor_fc_layers=(100,),
value_net_fc_layers=(100,),
use_value_network=False,
# Params for collect
collect_episodes_per_iteration=2,
replay_buffer_capacity=2000,... | 8,808 |
def record_attendance(lesson_id):
"""
Record attendance for a lesson.
"""
# Get the UserLessonAssociation for the current and
# the given lesson id. (So we can also display attendance etc.)
lesson = Lesson.query.filter(Lesson.lesson_id == lesson_id).first()
# Ensure the lesson id/associatio... | 8,809 |
async def test_hassio_discovery_dont_update_configuration(hass):
"""Test we can update an existing config entry."""
await setup_deconz_integration(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data={
CONF_HOST: "1.2.3.4",
CONF_PORT: 80,
... | 8,810 |
async def websocket_device_automation_get_condition_capabilities(hass, connection, msg):
"""Handle request for device condition capabilities."""
condition = msg["condition"]
capabilities = await _async_get_device_automation_capabilities(
hass, DeviceAutomationType.CONDITION, condition
)
conn... | 8,811 |
def add_action(action):
"""Enregistre une action et programme son ouverture le cas échéant.
Args:
action (.bdd.Action): l'action à enregistrer
"""
if not action.active:
action.active = True
action.add()
# Ajout tâche ouverture
if action.base.trigger_debut == Acti... | 8,812 |
def ts_to_datestr(ts, fmt="%Y-%m-%d %H:%M"):
"""可读性"""
return ts_to_datetime(ts).strftime(fmt) | 8,813 |
def _ComplexAbsGrad(op, grad):
"""Returns the gradient of ComplexAbs."""
# TODO(b/27786104): The cast to complex could be removed once arithmetic
# supports mixtures of complex64 and real values.
return (math_ops.complex(grad, array_ops.zeros_like(grad)) *
math_ops.sign(op.inputs[0])) | 8,814 |
def so3_rotate(batch_data):
""" Randomly rotate the point clouds to augument the dataset
rotation is per shape based along up direction
Input:
BxNx3 array, original batch of point clouds
Return:
BxNx3 array, rotated batch of point clouds
"""
rotated_data = np.zero... | 8,815 |
def intmd5(source: str, nbytes=4) -> int:
"""
Generate a predictive random integer of nbytes*8 bits based on a source string.
:param source:
seed string to generate random integer.
:param nbytes:
size of the integer.
"""
hashobj = hashlib.md5(source.encode())
return int.from_bytes... | 8,816 |
def trisolve(a, b, c, y, inplace=False):
"""
The tridiagonal matrix (Thomas) algorithm for solving tridiagonal systems
of equations:
a_{i}x_{i-1} + b_{i}x_{i} + c_{i}x_{i+1} = y_{i}
in matrix form:
Mx = y
TDMA is O(n), whereas standard Gaussian elimination is O(n^3).
Argument... | 8,817 |
def calc_mean_pred(df: pd.DataFrame):
"""
Make a prediction based on the average of the predictions of phones
in the same collection.
from https://www.kaggle.com/t88take/gsdc-phones-mean-prediction
"""
lerp_df = make_lerp_data(df=df)
add_lerp = pd.concat([df, lerp_df])
# each time step =... | 8,818 |
def get_meals(v2_response, venue_id):
"""
Extract meals into old format from a DiningV2 JSON response
"""
result_data = v2_response["result_data"]
meals = []
day_parts = result_data["days"][0]["cafes"][venue_id]["dayparts"][0]
for meal in day_parts:
stations = []
for station... | 8,819 |
def replace_control_curves(control_names, control_type='circle', controls_path=None, keep_color=True, **kwargs):
"""
:param control_names:
:param control_type:
:param controls_path:
:param keep_color:
:return:
"""
raise NotImplementedError('Function set_shape not implemented for curren... | 8,820 |
async def async_setup(hass, config_entry):
""" Disallow configuration via YAML """
return True | 8,821 |
def blend(im1, im2, mask):
"""
Blends and shows the given images according to mask
:param im1: first image
:param im2: second image
:param mask: binary mask
:return: result blend
"""
res = []
for i in range(3):
res.append(pyramid_blending(im1[:, :, i], im2[:, :, i], mask, 7, ... | 8,822 |
def parse(fileName):
"""
Pull the EXIf info from a photo and sanitize it so for sending as JSON
by converting values to strings.
"""
f = open(fileName, 'rb')
exif = exifread.process_file(f, details=False)
parsed = {}
for key, value in exif.iteritems():
parsed[key] = str(value)
... | 8,823 |
def get_scenario():
"""
Get scenario
"""
try:
scenario = os.environ['DEPLOY_SCENARIO']
except KeyError:
logger.error("Impossible to retrieve the scenario")
scenario = "Unknown_scenario"
return scenario | 8,824 |
def test_MultiDAE():
"""Test the MultiDAE class
"""
net = MultiDAE_net([1, 2], [2, 1], dropout=.1)
model = MultiDAE(net)
assert hasattr(model, "network"), "model should have the attribute newtork"
assert hasattr(model, "device"), "model should have the attribute device"
assert hasattr(model... | 8,825 |
def create_data_locker_adapter(form, url, notify):
"""
Creates a Web Services Adapter in the form (self) and configures it to use
the Data Locker located at `url`
"""
data_locker = api.content.create(
type='FormWebServiceAdapter',
title='Data Locker',
url=url,
extraDa... | 8,826 |
def make_request(
endpoint: str, method: str = "get", data: Optional[dict] = None, timeout: int = 15
) -> Response:
"""Makes a request to the given endpoint and maps the response
to a Response class"""
method = method.lower()
request_method: Callable = getattr(requests, method)
if method not in ... | 8,827 |
def _is_rpc_timeout(e):
""" check whether an exception individual rpc timeout. """
# connection caused socket timeout is being re-raised as
# ThriftConnectionTimeoutError now
return isinstance(e, socket.timeout) | 8,828 |
def fake_quantize_with_min_max(inputs,
f_min,
f_max,
bit_width,
quant_zero=True):
"""The fake quantization operation kernel.
Args:
inputs: a tensor containing values to be quantized.
... | 8,829 |
def lorentzian(coordinates, center, fwhm):
"""
Unit integral Lorenzian function.
Parameters
----------
coordinates : array-like
Can be either a list of ndarrays, as a meshgrid coordinates list, or a
single ndarray for 1D computation
center : array-like
Center of the lorentzian. Should be the same sh... | 8,830 |
async def gspider(gspdr):
"""For .gmute command, globally mutes the replied/tagged person"""
# Admin or creator check
chat = await gspdr.get_chat()
admin = chat.admin_rights
creator = chat.creator
# If not admin and not creator, return
if not admin and not creator:
await gspdr.edit(... | 8,831 |
def _to_gzip_base64(self, **kwargs):
""" Reads the file as text, then turns to gzip+base64"""
data = self.read_text(**kwargs)
return Base.b64_gzip_encode(data) | 8,832 |
def HTunigramX1(outf, (prefixes,topics,segments)):
"""hierarchical topic-based unigram model that requires at most one occurence
of a topic word per sentence (all words share a common base Word distribution)"""
outf.write("1 1 Sentence --> Words\n")
outf.write("1 1 Words --> Words Word\n")
for ... | 8,833 |
def get_recipe_data(published=False, complete_data=False):
"""Return published or unpublished recipe data."""
try:
Changed = User.alias()
recipes = recipemodel.Recipe.select(
recipemodel.Recipe, storedmodel.Stored,
pw.fn.group_concat(tagmodel.Tag.tagname).alias("taglist")... | 8,834 |
def html_anchor_navigation(base_dir, experiment_dir, modules):
"""Build header of an experiment with links to all modules used for rendering.
:param base_dir: parent folder in which to look for an experiment folders
:param experiment_dir: experiment folder
:param modules: list of all loaded modules
... | 8,835 |
def connect_and_play(player, name, channel, host, port,
logfilename=None, out_function=None, print_state=True,
use_debugboard=False, use_colour=False, use_unicode=False):
"""
Connect to and coordinate a game with a server, return a string describing
the result.
"""
# Configure behavi... | 8,836 |
def _to_int_and_fraction(d: Decimal) -> typing.Tuple[int, str]:
"""convert absolute decimal value into integer and decimal (<1)"""
t = d.as_tuple()
stringified = ''.join(map(str, t.digits))
fraction = ''
if t.exponent < 0:
int_, fraction = stringified[:t.exponent], stringified[t.exponent:]
... | 8,837 |
def json_to_obj(my_class_instance):
"""
Получает на вход JSON-представление,
выдает на выходе объект класса MyClass.
>>> a = MyClass('me', 'my_surname', True)
>>> json_dict = get_json(a)
>>> b = json_to_obj(json_dict)
<__main__.MyClass object at 0x7fd8e9634510>
"""
some_dict = json.l... | 8,838 |
def all_tags(path) -> {str: str}:
"""Method to return Exif tags"""
file = open(path, "rb")
tags = exifread.process_file(file, details=False)
return tags | 8,839 |
def static(request):
"""
Backport django.core.context_processors.static to Django 1.2.
"""
return {'STATIC_URL': djangoSettings.STATIC_URL} | 8,840 |
def genBoard():
"""
Generates an empty board.
>>> genBoard()
["A", "B", "C", "D", "E", "F", "G", "H", "I"]
"""
# Empty board
empty = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
# Return it
return empty | 8,841 |
def delete_evaluation(EvaluationId=None):
"""
Assigns the DELETED status to an Evaluation , rendering it unusable.
After invoking the DeleteEvaluation operation, you can use the GetEvaluation operation to verify that the status of the Evaluation changed to DELETED .
The results of the DeleteEvaluation o... | 8,842 |
def extract_features(segment_paths,
output_dir,
workers=1,
sample_size=None,
old_segment_format=True,
resample_frequency=None,
normalize_signal=False,
only_missing_files=Tru... | 8,843 |
def snmp_set_via_cli(oid, value, type):
"""
Sets an SNMP variable using the snmpset command.
:param oid: the OID to update
:param value: the new value to set the OID to
:param type: a single character type as required by the snmpset command
(i: INTEGER, u: unsigned INTEGER, t: TIME... | 8,844 |
def _resize_sample(source_file_path, target_file_path, _new_dim = '256x256'):
"""
Resizes a sample to _new_dim.
This methods uses ResampleImage from the ANTs library, so you need to have it in your path environment.
Note:
The methods only works with two-dimensional images.
"""
from ... | 8,845 |
def _partition_at_level(dendrogram, level) :
"""Return the partition of the nodes at the given level
A dendrogram is a tree and each level is a partition of the graph nodes.
Level 0 is the first partition, which contains the smallest snapshot_affiliations, and the best is len(dendrogram) - 1.
The higher the level ... | 8,846 |
def filter_multi_copy_clusters(idx):
"""
{cluster_id : {taxonomy : {genomeid : [gene_uuid,...]}}}
"""
logging.info('Filtering out multi-copy genes...')
clust_cnt = collections.defaultdict(dict)
to_remove = []
for cluster_id,v in idx.items():
per_genome_copy = {}
for tax,vv in... | 8,847 |
def generate_ab_data():
"""
Generate data for a second order reaction A + B -> P
d[A]/dt = -k[A][B]
d[B]/dt = -k[A][B]
d[P]/dt = k[A][B]
[P] = ([B]0 - [A]0 h(t)) / (1 - h(t)) where
h(t) = ([B]0 / [A]0) e^(kt ([B]0 - [A]0))
Data printed in a .csv file
"""
times = np.linspace(0... | 8,848 |
def autocomplete(segment: str, line: str, parts: typing.List[str]):
"""
:param segment:
:param line:
:param parts:
:return:
"""
if parts[-1].startswith('-'):
return autocompletion.match_flags(
segment=segment,
value=parts[-1],
shorts=['f', 'a', '... | 8,849 |
def main():
""" main execution sequence """
from sklearn import __version__ as version
print('sklearn version:', version)
# setup DmimData instance (using MQNs)
mqn = DMD('DMIM_v1.0.db', SEED)
mqn.featurize('mqn')
mqn.train_test_split()
mqn.center_and_scale()
print('training SVR ... | 8,850 |
def elast_tri3(coord, params):
"""Triangular element with 3 nodes
Parameters
----------
coord : ndarray
Coordinates for the nodes of the element (3, 2).
params : tuple
Material parameters in the following order:
young : float
Young modulus (>0).
poisson ... | 8,851 |
def make_offgrid_patches_xcenter_xincrement(n_increments:int, n_centers:int, min_l:float, patch_dim:float, device):
"""
for each random point in the image and for each increments, make a square patch
return: I x C x P x P x 2
"""
patches_xcenter = make_offgrid_patches_xcenter(n_centers, min_l, patch... | 8,852 |
def load_gazes_from_xml(filepath: str) -> pd.DataFrame:
"""loads data from the gaze XML file output by itrace.
Returns the responses as a pandas DataFrame
Parameters
----------
filepath : str
path to XML
Returns
-------
pd.DataFrame
Gazes contained in the xml file
... | 8,853 |
def axis_rotation(points, angle, inplace=False, deg=True, axis='z'):
"""Rotate points angle (in deg) about an axis."""
axis = axis.lower()
# Copy original array to if not inplace
if not inplace:
points = points.copy()
# Convert angle to radians
if deg:
angle *= np.pi / 180
... | 8,854 |
async def unhandled_exception(request: Request, exc: UnhandledException):
"""Raises a custom TableKeyError."""
return JSONResponse(
status_code=400,
content={"message": "Something bad happened" f" Internal Error: {exc.message!r}"},
) | 8,855 |
def register_view(request):
"""Render HTTML page"""
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, "Account was cre... | 8,856 |
def test_e_mail(provider: str, user: str, password: str):
"""Function that performs test on all command of
EmailMessage and EmailServer class"""
# Test create EmailMessage object
message = EmailMessage('Test send email using python')
# Test add message
message.add_message('Test message')
#... | 8,857 |
def luv2rgb(luv, *, channel_axis=-1):
"""Luv to RGB color space conversion.
Parameters
----------
luv : (..., 3, ...) array_like
The image in CIE Luv format. By default, the final dimension denotes
channels.
Returns
-------
out : (..., 3, ...) ndarray
The image in R... | 8,858 |
def deposit_fetcher(record_uuid, data):
"""Fetch a deposit identifier.
:param record_uuid: Record UUID.
:param data: Record content.
:returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains
data['_deposit']['id'] as pid_value.
"""
return FetchedPID(
provider=Depos... | 8,859 |
def make_filename():
""""This functions creates a unique filename."""
unique_filename = time.strftime("%Y%m%d-%H%M%S")
#unique_filename = str(uuid.uuid1())
#unique_filename = str(uuid.uuid1().hex[0:7])
save_name = 'capture_ferhat_{}.png'.format(unique_filename)
return(save_name) | 8,860 |
def compareLists(sentenceList, majorCharacters):
"""
Compares the list of sentences with the character names and returns
sentences that include names.
"""
characterSentences = defaultdict(list)
for sentence in sentenceList:
for name in majorCharacters:
if re.search(r"\b(?=\w)... | 8,861 |
def is_live_site(url):
"""Ensure that the tool is not used on the production Isaac website.
Use of this tool or any part of it on Isaac Physics and related websites
is a violation of our terms of use: https://isaacphysics.org/terms
"""
if re.search("http(s)?://isaac(physics|chemistry|maths|bi... | 8,862 |
def generate_train_patch(image_path, mask_path,
crop_size=(3000, 3000),
steps=(2000, 2000),
save_dir=None):
"""
"""
fileid = image_path.split("/")[-1].split(".")[0]
save_path = os.path.join(save_dir, fileid)
os.makedirs(save_path, exist_ok=T... | 8,863 |
def create_test_list(root):
"""
Create test list.
"""
fw = open("test_list.txt", 'w')
for aoi in os.listdir(root):
if not os.path.isdir(os.path.join(root, aoi)):
continue
img_path = os.path.join(root, aoi, "images_masked_3x_divide")
for img_file in os.listdir(img_... | 8,864 |
def score_false(e, sel):
"""Return scores for internal-terminal nodes"""
return e*(~sel).sum() | 8,865 |
def Select_multi_items(list_item,mode='multiple', fact=2, win_widthmm=80, win_heightmm=100, font_size=16):
"""interactive selection of items among the list list_item
Args:
list_item (list): list of items used for the selection
Returns:
val (list): list of selected items witho... | 8,866 |
def retrieveXS(filePath, evMin=None, evMax=None):
"""Open an ENDF file and return the scattering XS"""
logging.info('Retrieving scattering cross sections from file {}'
.format(filePath))
energies = []
crossSections = []
with open(filePath) as fp:
line = fp.readline()
... | 8,867 |
def _parse_java_simple_date_format(fmt):
"""
Split a SimpleDateFormat into literal strings and format codes with counts.
Examples
--------
>>> _parse_java_simple_date_format("'Date:' EEEEE, MMM dd, ''yy")
['Date: ', ('E', 5), ', ', ('M', 3), ' ', ('d', 2), ", '", ('y', 2)]
"""
out = []... | 8,868 |
def rekey_by_sample(ht):
"""Re-key table by sample id to make subsequent ht.filter(ht.S == sample_id) steps 100x faster"""
ht = ht.key_by(ht.locus)
ht = ht.transmute(
ref=ht.alleles[0],
alt=ht.alleles[1],
het_or_hom_or_hemi=ht.samples.het_or_hom_or_hemi,
#GQ=ht.samples.GQ,
HL=ht.samples.HL,
S=ht.samples... | 8,869 |
async def test_coil_switch(hass, regs, expected):
"""Run test for given config."""
switch_name = "modbus_test_switch"
state = await base_test(
hass,
{
CONF_NAME: switch_name,
CALL_TYPE_COIL: 1234,
CONF_SLAVE: 1,
},
switch_name,
SWIT... | 8,870 |
def _sample_prior_fixed_model(formula_like, data=None,
a_tau=1.0, b_tau=1.0, nu_sq=1.0,
n_iter=2000,
generate_prior_predictive=False,
random_state=None):
"""Sample from prior for a fixed model."""... | 8,871 |
def init_keyspace():
"""Creates a `test_keyspace` keyspace with a sharding key."""
utils.run_vtctl(['CreateKeyspace', '-sharding_column_name', 'keyspace_id',
'-sharding_column_type', KEYSPACE_ID_TYPE,'test_keyspace']) | 8,872 |
def TestSConscript(scons_globals):
"""Test SConscript file.
Args:
scons_globals: Global variables dict from the SConscript file.
"""
# Get globals from SCons
scons_globals['Import']('env')
env = scons_globals['env']
# Build an object
a_obj = env.ComponentObject('a.cpp')
# Build a static library... | 8,873 |
async def validate_input(
hass: core.HomeAssistant, data: dict[str, Any]
) -> dict[str, str]:
"""Validate the user input allows us to connect.
Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
"""
zeroconf_instance = await zeroconf.async_get_instance(hass)
async_cli... | 8,874 |
def closeWindow(plotterInstance=None):
"""Close the current or the input rendering window."""
if not plotterInstance:
plotterInstance = settings.plotter_instance
if not plotterInstance:
return
if plotterInstance.interactor:
plotterInstance.interactor.ExitCallback()
... | 8,875 |
def _format_stages_summary(stage_results):
"""
stage_results (list of (tuples of
(success:boolean, stage_name:string, status_msg:string)))
returns a string of a report, one line per stage.
Something like:
Stage: <stage x> :: SUCCESS
Stage: <stage y> :: FAILED
Stage: <s... | 8,876 |
def pack(envelope, pack_info):
"""Pack envelope into a byte buffer.
Parameters
----------
envelope : data structure
pack_info : packing information
Returns
-------
packet : bytes
"""
ptype = pack_info.ptype
packer = packers[ptype]
payload = packer.pack(envelope)
hd... | 8,877 |
def initMP3():
""" Initialize the MP3 player
"""
mpc.stop() # stop what's playing
mpc.clear() # clear any existing playlists
mpc.repeat(True) | 8,878 |
def test_add_file_success(monkeypatch, capsys):
"""
Test successful adding of file
"""
db.initialize_database()
test_mount_1 = __make_temp_directory()
monkeypatch.setattr(utility, "get_device_serial", lambda path: "test-serial-1")
patch_input(monkeypatch, library, lambda message: "test-devi... | 8,879 |
def tmpnam_s():
"""Implementation of POSIX tmpnam() in scalar context"""
ntf = tempfile.NamedTemporaryFile(delete=False)
result = ntf.name
ntf.close()
return result | 8,880 |
def timezone_lookup():
"""Force a timezone lookup right now"""
TZPP = NSBundle.bundleWithPath_("/System/Library/PreferencePanes/"
"DateAndTime.prefPane/Contents/"
"Resources/TimeZone.prefPane")
TimeZonePref = TZPP.classNamed_('TimeZoneP... | 8,881 |
def rollingCPM(dynNetSN:DynGraphSN,k=3):
"""
This method is based on Palla et al[1]. It first computes overlapping snapshot_communities in each snapshot based on the
clique percolation algorithm, and then match snapshot_communities in successive steps using a method based on the
union graph.
[1] P... | 8,882 |
def penalty_eqn(s_m, Dt):
"""
Description:
Simple function for calculating the penalty for late submission of a project.
Args:
:in (1): maximum possible score
:in (2): difference between the date of deadline and the date of assignment of the project (in hours)
:out (1): rounded result of ... | 8,883 |
def stop(name=None, id=None):
"""
Stop (terminate) the VM identified by the given id or name.
When both a name and id are provided, the id is ignored.
name:
Name of the defined VM.
id:
VM id.
CLI Example:
.. code-block:: bash
salt '*' vmctl.stop name=alpine
"... | 8,884 |
def ky_att(xs, b, Mach, k0, Att=-20):
"""
Returns the spanwise gust wavenumber 'ky_att' with response at 'xs' attenuated by 'Att' decibels
Parameters
----------
xs : float
Chordwise coordinate of reference point, defined in interval (-b, +b].
b : float
Airfoil semi chord.
... | 8,885 |
def print_losses(loss, epoch, loss_val=None):
"""
Convenience function to print a set of losses. can be used by SVD
autoencoder.
Args:
loss (float): Loss value
epoch (int): Current epoch
"""
print("%d: [loss: %f, acc: %.2f%%]" %
(epoch, loss[0], 100*loss[1]))
if l... | 8,886 |
def test_alm_mean(get_covmats):
"""Test the ALM mean"""
n_matrices, n_channels = 3, 3
covmats = get_covmats(n_matrices, n_channels)
C_alm = mean_alm(covmats)
C_riem = mean_riemann(covmats)
assert C_alm == approx(C_riem) | 8,887 |
def has_multiline_items(strings: Optional[Strings]) -> bool:
"""Check whether one of the items in the list has multiple lines."""
return any(is_multiline(item) for item in strings) if strings else False | 8,888 |
def eval_ctx(
layer: int = 0, globals_: Optional[DictStrAny] = None, locals_: Optional[DictStrAny] = None
) -> Tuple[DictStrAny, DictStrAny]:
"""获取一个上下文的全局和局部变量
Args:
layer (int, optional): 层数. Defaults to 0.
globals_ (Optional[DictStrAny], optional): 全局变量. Defaults to None.
locals_... | 8,889 |
def find_ports(device):
"""
Find the port chain a device is plugged on.
This is done by searching sysfs for a device that matches the device
bus/address combination.
Useful when the underlying usb lib does not return device.port_number for
whatever reason.
"""
bus_id = device.bus
d... | 8,890 |
def extract_vcalendar(allriscontainer):
"""Return a list of committee meetings extracted from html content."""
vcalendar = {
'vevents': findall_events(allriscontainer),
}
if vcalendar.get('vevents'):
base_url = allriscontainer.base_url
vcalendar['url'] = find_calendar_url(base_ur... | 8,891 |
def rnn_helper(inp,
length,
cell_type=None,
direction="forward",
name=None,
reuse=None,
*args,
**kwargs):
"""Adds ops for a recurrent neural network layer.
This function calls an actual implementation of ... | 8,892 |
def test_get_arrival_jobs(demand_rate_fixture, add_max_rate_fixture, class_fixture):
"""Check that the sample average approximates the actual demand mean rate."""
np.random.seed(42)
buffer_processing_matrix = np.max(demand_rate_fixture) * 1.1 * np.eye(4)
job_gen = class_fixture(demand_rate=demand_rate_f... | 8,893 |
def get_data(dataset):
"""
:return: encodings array of (2048, n)
labels list of (n)
"""
query = "SELECT * FROM embeddings WHERE label IS NOT NULL"
cursor, connection = db_actions.connect(dataset)
cursor.execute(query)
result_list = cursor.fetchall()
encodings = np.zeros((2... | 8,894 |
def read_hdr(name, order='C'):
"""Read hdr file."""
# get dims from .hdr
h = open(name + ".hdr", "r")
h.readline() # skip line
l = h.readline()
h.close()
dims = [int(i) for i in l.split()]
if order == 'C':
dims.reverse()
return dims | 8,895 |
def IsTouchDevice(dev):
"""Check if a device is a touch device.
Args:
dev: evdev.InputDevice
Returns:
True if dev is a touch device.
"""
keycaps = dev.capabilities().get(evdev.ecodes.EV_KEY, [])
return evdev.ecodes.BTN_TOUCH in keycaps | 8,896 |
def load_users():
"""
Loads users csv
:return:
"""
with open(USERS, "r") as file:
# creates dictionary to separate csv values to make it easy to iterate between them
# the hash() function is used to identify the values in the csv, as they have their individual hash
... | 8,897 |
def main(argv):
"""
Push specified revision as a specified bookmark to repo.
"""
args = parse_arguments(argv)
pulled = check_output([args.mercurial_binary, 'pull', '-B', args.bookmark, args.repo]).decode('ascii')
print(pulled)
if re.match("adding changesets", pulled):
print("Unsee... | 8,898 |
def clustering_consistency_check(G):
""" Check consistency of a community detection algorithm by running it a number of times.
"""
Hun = G.to_undirected()
Hun = nx.convert_node_labels_to_integers(Hun,label_attribute='skeletonname')
WHa = np.zeros((len(Hun.nodes()),len(Hun.nodes())))
for i ... | 8,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.