content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_specific_url(url):
"""
This api has a tendency to give you the url for the general list of things
if there are no entries.
this separates "people/" from "people/123456"
"""
return url[-1] != '/' | 0d4842f4e4264d38350738d92060e0d2de0575c1 | 693,765 |
def conj(x):
"""Return conjugate of x."""
return x.conjugate() | d710ca7536775d26176d6a759cb072532ff9428d | 693,768 |
def fv_annuity(n,c,r):
"""
Objective: estimate future value of an annuity
n : number of payments
c : payment amount
r : discount
formula : c/r*((1+r)**n-1)
e.g.,
>>>fv_annuity(2,100,0.1)
210.0000000000002
"""
return c/r*((1+r)**n-1) | 312d4d5a8760d86dfb310c7527e02ae611500369 | 693,771 |
from typing import Iterable
from typing import Any
def _iterable_choices_metavar(iterable: Iterable[Any]) -> str:
"""Generates a string metavar from iterable choices.
Args:
iterable (Iterable[Any]): Iterable object to generate metavar for.
Returns:
str: Generated metavar
"""
# Generate and Return
return f"{{{', '.join(str(i) for i in iterable)}}}" | e556b62205904cb4c6ffb565f7dfe3c02f02a87d | 693,773 |
from datetime import datetime
def get_datetime(utc_time):
"""
Convert date string to datetime object
"""
utc = datetime.strptime(utc_time, '%Y-%m-%dT%H:%M:%S.%fZ')
return utc | a3626e9eef59a4c8d26944c4776dd6e6c30b21d8 | 693,779 |
def unique(v):
"""Generates a list from a sequence where each value appears only once, and the order is preserved."""
try:
sequence = list(v)
except:
return []
seen = set()
seen_add = seen.add
return [item for item in sequence if not (item in seen or seen_add(item))] | 3c314afeade3ef813ba4869d5017f395184508cb | 693,780 |
def get_audio_route(log, ad):
"""Gets the audio route for the active call
Args:
log: logger object
ad: android_device object
Returns:
Audio route string ["BLUETOOTH", "EARPIECE", "SPEAKER", "WIRED_HEADSET"
"WIRED_OR_EARPIECE"]
"""
audio_state = ad.droid.telecomCallGetAudioState()
return audio_state["AudioRoute"] | 2c6353a4f46523d947c949da36782316f8925ff1 | 693,782 |
import re
def FormatWikiLinks(html):
"""Given an html file, convert [[WikiLinks]] into *WikiLinks* just to ease
readability."""
wikilink = re.compile(r'\[\[(?:[^|\]]*\|)?([^\]]+)\]\]')
return wikilink.sub(r'*\1*', html) | e33203875579d1dccb9e09370205da63ff9b3b2c | 693,787 |
def increment_char(c):
"""
Increment an uppercase character, returning 'A' if 'Z' is given
"""
return chr(ord(c) + 1) if c != 'Z' else 'A' | 89c30f136acc05b289e61e0125ffe4ae3fcc213e | 693,796 |
def RGB(red, green, blue):
"""
Given integer values of Red, Green, Blue, return a color string "#RRGGBB"
:param red: (int) Red portion from 0 to 255
:param green: (int) Green portion from 0 to 255
:param blue: (int) Blue portion from 0 to 255
:return: (str) A single RGB String in the format "#RRGGBB" where each pair is a hex number.
"""
return '#%02x%02x%02x' % (red, green, blue) | cf2776f29e6b189de3ef8d18f025a40b47e505d0 | 693,797 |
import json
def get_data(file_name: str) -> dict:
"""
Simply getting data from specified json file name and returning them
in the form of a python dictionary
"""
with open(file_name, "r") as json_file:
content = json.load(json_file)
return content | d501d5162c58d2c24a1250e1623947d5f5c6d4bc | 693,799 |
from typing import Optional
def _get_bool(val) -> Optional[bool]:
"""
Converts val to bool if can be done with certainty.
If we cannot infer intention we return None.
"""
if isinstance(val, bool):
return val
elif isinstance(val, str):
if val.strip().lower() == 'true':
return True
elif val.strip().lower() == 'false':
return False
return None | da2562baeedd83454912745f1b436e1ae18562a4 | 693,803 |
def qw_not_found(arg1, arg2, path=None, headers=None, payload=None):
"""This function is used when a not found resource should be returned.
According arg2 argument, if "not_found" is detected as a string then
payload is returned directly or as part of "data" dictionnary.
"""
payload = {'errors': [{
'code': 'not_found',
'message': 'Resource not found'
}]
}
if arg2 == 'not_found':
return payload
return {'data': payload} | 243648edcada2d35baafeeedee80e7319bd8c115 | 693,807 |
def determine_spec_version(obj):
"""Given a STIX 2.x object, determine its spec version."""
missing = ("created", "modified")
if all(x not in obj for x in missing):
# Special case: only SCOs are 2.1 objects and they don't have a spec_version
# For now the only way to identify one is checking the created and modified
# are both missing.
return "2.1"
return obj.get("spec_version", "2.0") | 7c3df55c7e80a6823571aa1af8d77cfd9c67710f | 693,808 |
import re
def exemplar_unicodes_convert(text):
"""Convert \u1234 strings inside the exemplar text to real unicode characters
Args:
text (str): Raw exemplar string. Eg: "a b c \\u0041"
Returns:
[type]: Converted exemplar string: Eg: "a b c A"
"""
uni_chars = re.findall(r"\\u([0-9A-F]+)", text)
for uni_char in uni_chars:
text = text.replace("\\u" + uni_char, chr(int(uni_char, 16)))
return text | 47d0f1435839a8b47c199fa6f5a687694427860e | 693,809 |
import math
def luv_to_hcl(ell: float, u: float, v: float) -> tuple[float, float, float]:
"""Convert the color from CIELUV coordinates to HCL coordinates."""
h = math.atan2(v, u)
c = math.hypot(v, u)
h = h + math.tau if h < 0 else h
return h, c, ell | 569b51e1cf0155e06c34d6f1655e76cd2966243f | 693,811 |
def WebError(message=None, data=None):
"""
Unsuccessful web request wrapper.
"""
return {
"status": 0,
"message": message,
"data": data
} | 022d150fba82bbc1bd7ed425eb34c657d4c7c673 | 693,819 |
def generate_rearranged_graph(graph, fbonds, bbonds):
"""Generate a rearranged graph by breaking bonds (edge) and forming others
(edge)
Arguments:
graph (nx.Graph): reactant graph
fbonds (list(tuple)): list of bonds to be made
bbonds (list(tuple)): list of bonds to be broken
Returns:
nx.Graph: rearranged graph
"""
rearranged_graph = graph.copy()
for fbond in fbonds:
rearranged_graph.add_edge(*fbond)
for bbond in bbonds:
rearranged_graph.remove_edge(*bbond)
return rearranged_graph | 33f842cee6759f7a012c9806c67fdcee6797bd6c | 693,823 |
def create_html_url_href(url: str) -> str:
"""
HTML version of a URL
:param url: the URL
:return: URL for use in an HTML document
"""
return f'<a href="{url}">{url}</a>' if url else "" | 5c41f5035a2b549e9c969eccbcc960a100600e7e | 693,824 |
def tet_vector(i, num_tet):
"""
Gives the tet equation for the i^th tetrahedron.
"""
out = []
for j in range(num_tet):
if i == j: out.extend([1]*3)
else: out.extend([0]*3)
return out | 5470ee3873e76514c6c747a2066744669df837c0 | 693,825 |
from typing import Counter
from typing import Tuple
def _counter_key_vals(counts: Counter, null_sort_key="ø") -> Tuple[Tuple, Tuple]:
"""
Split counter into a keys sequence and a values sequence.
(Both sorted by key)
>>> tuple(_counter_key_vals(Counter(['a', 'a', 'b'])))
(('a', 'b'), (2, 1))
>>> tuple(_counter_key_vals(Counter(['a'])))
(('a',), (1,))
>>> tuple(_counter_key_vals(Counter(['a', None])))
(('a', None), (1, 1))
>>> # Important! zip(*) doesn't do this.
>>> tuple(_counter_key_vals(Counter()))
((), ())
"""
items = sorted(
counts.items(),
# Swap nulls if needed.
key=lambda t: (null_sort_key, t[1]) if t[0] is None else t,
)
return tuple(k for k, v in items), tuple(v for k, v in items) | 0965c7c7e5717c4daa48d3b9a188ad70283b41c7 | 693,827 |
def disable_event(library, session, event_type, mechanism):
"""Disables notification of the specified event type(s) via the specified mechanism(s).
Corresponds to viDisableEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be disabled.
(Constants.QUEUE, .Handler, .SUSPEND_HNDLR, .ALL_MECH)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viDisableEvent(session, event_type, mechanism) | 9bbaf57350e46dd3a6035b9f73c2c286821cb346 | 693,828 |
def autocast_value(value):
"""Cast string to string, float, bool or None. """
if value is None:
return
value_lcase = value.lower()
if value_lcase == "null":
return
if value_lcase == "false":
return False
if value_lcase == "true":
return True
try:
return float(value)
except ValueError:
return value | 0ed4ebcd64f2f9b2fd200d296d4e216a8eca73ac | 693,829 |
def fixture_sample_tag_name() -> str:
"""Return a tag named 'sample'"""
return "sample" | 1a5efe0fd71234333ceb778e05bec31315947b52 | 693,833 |
def version_is_available(request):
"""Return a boolean, whether we have the version they asked for.
"""
path = request.line.uri.path
version = request.website.version
return path['version'] == version if 'version' in path else True | 4c6e67153733b7d547423babc878ea4c71ab50f8 | 693,835 |
def is_tag_list(tag_name, conf):
"""
Return true if a XMP tag accepts list or not
"""
return tag_name in conf["list"] | 0dfcf08abcea9979129515b1a0dec22fae1ec46d | 693,836 |
import hashlib
def filehash(filepath):
"""
Compute sha256 from a given file.
Parameters
----------
filepath : str
File path.
Returns
-------
sha256 : str
Sha256 of a given file.
"""
BUF_SIZE = 65536
sha256 = hashlib.sha256()
with open(filepath, "rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha256.update(data)
return sha256.hexdigest() | 7e0af85ef132b19a18c4ba7956f58e46256d6445 | 693,838 |
from typing import List
def split_text(text: str) -> List[str]:
"""Split arbitrary text into words (str)."""
return text.split() | 4c48a604b1e76bd7d712cbbc670d9c8d3439e6e0 | 693,839 |
def get_uid_search_xpath(uid):
# type: (str) -> str
"""Method to get the XPath expression for a UID that might contain quote characters.
Parameters
----------
uid : str
Original UID string with XPath expression.
Returns
-------
str
Processed XPath expression to escape quote characters using "concat()".
"""
if '"' in uid or '"' in uid:
uid_concat = "concat('%s')" % uid.replace('"', "\',\'\"\',\'").replace('"',
"\',\'\"\',\'")
return './/*[@uID=' + uid_concat + ']'
else:
return './/*[@uID="' + uid + '"]' | f3626595b13a9a9cae44d7f5cb9729602e902db9 | 693,842 |
import math
def round_half_up(x):
"""
Return x rounded to the nearest integer, with halves rounded up to match
SLiM's behaviour. Python's round() function rounds halves to the nearest
even number.
"""
floor_x = math.floor(x)
if x - floor_x < 0.5:
return floor_x
else:
return math.ceil(x) | e670457f89a46fd560a08f3cbcb956a2a1f10d72 | 693,843 |
def DEFAULT_NULLVALUE(test):
"""
Returns a null value for each of various kinds of test values.
**Parameters**
**test** : bool, int, float or string
Value to test.
**Returns**
**null** : element in `[False, 0, 0.0, '']`
Null value corresponding to the given test value:
* if `test` is a `bool`, return `False`
* else if `test` is an `int`, return `0`
* else if `test` is a `float`, return `0.0`
* else `test` is a `str`, return `''`
"""
return False if isinstance(test,bool) \
else 0 if isinstance(test,int) \
else 0.0 if isinstance(test,float) \
else '' | ce9e4df2fc9b3b492bc3a4b3a98c96aa71eca3d0 | 693,847 |
import hashlib
def sha256_string(content: str) -> str:
"""
Hash a string using SHA256. Cache results for repeated use.
"""
h = hashlib.sha256()
h.update(content.encode("utf-8"))
return h.hexdigest() | a6cf8dfe6becc7ffb7d3e71c6bb50b6092f2480d | 693,851 |
import math
def get_bearing(origin_point, destination_point):
"""
Calculate the bearing between two lat-lng points.
Each argument tuple should represent (lat, lng) as decimal degrees.
Bearing represents angle in degrees (clockwise) between north and the
direction from the origin point to the destination point.
Parameters
----------
origin_point : tuple
(lat, lng)
destination_point : tuple
(lat, lng)
Returns
-------
bearing : float
the compass bearing in decimal degrees from the origin point to the
destination point
"""
if not (isinstance(origin_point, tuple) and isinstance(destination_point, tuple)):
raise TypeError("origin_point and destination_point must be (lat, lng) tuples")
# get latitudes and the difference in longitude, as radians
lat1 = math.radians(origin_point[0])
lat2 = math.radians(destination_point[0])
diff_lng = math.radians(destination_point[1] - origin_point[1])
# calculate initial bearing from -180 degrees to +180 degrees
x = math.sin(diff_lng) * math.cos(lat2)
y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) * math.cos(lat2) * math.cos(diff_lng))
initial_bearing = math.atan2(x, y)
# normalize initial bearing to 0-360 degrees to get compass bearing
initial_bearing = math.degrees(initial_bearing)
bearing = (initial_bearing + 360) % 360
return bearing | cfba6ccd27e0b2e2b8fa34f71611b061692f6dbf | 693,852 |
def parseRating(line):
"""
Parses a rating record in MovieLens format userId::movieId::rating::count .
"""
fields = line.strip().split("::")
return int(fields[3]), (int(fields[0]), int(fields[1]), float(fields[2])) | de5ee9c8bfc810aae08c27de650a003a9d69a790 | 693,856 |
import math
def get_MCC(mx):
""" Gets the Matthews Correlation Coefficient (MCC)"""
[tp, fp], [fn, tn] = mx
return (tp * tn - fp * fn) / math.sqrt(
(tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)
) | 59de25c96f75d02e8bf4283bfeeb909d2e9646a9 | 693,857 |
def format_list(resources):
"""
Format comma-separated list of IDs from Django queryset.
"""
return ', '.join(map(str, sorted(resources.values_list('id', flat=True)))) | 96b13f3fce990a0c6ec1dd8d75a0cddb8f4b3fa4 | 693,865 |
def to(act: bool, models):
"""Convert Uvicore Model or List[Model] to JSON"""
# Uvicore models already have a pydantic .json() method
# But if its a List of models, we must handle manually
if not act: return models
if not models: return '{}'
if type(models) == list:
results = []
for model in models:
results.append(model.json())
json_results = '['
for result in results:
json_results += result + ','
return json_results[0:-1] + ']'
# A single uvicore model
return models.json() | 766477a17aa6e0456c650d9dc6f1ad3545953f5b | 693,869 |
def getPath(keyword, topicNames, topicPaths, topicIDs):
"""
Function to get the path of a particular keyword in ACM Tree.
Parameters:
keyword (string) - the keyword for which we want the path.
topicNames (dictionary) - the name of the topic as the key and the topic ID number as value.
topicPaths (dictionary) - the topic ID as the key, and its parent as value.
topicIDs (dictionary) - the topic ID as the key, and the topic name as the value.
Returns:
path (list) - the path of that keyword (backwards)
"""
topicId = topicNames[keyword]
path = [keyword]
topicParent = topicPaths[topicId]
#Start from the keyword and backtrack until the first parent.
while topicParent != 0:
curr = topicIDs[topicParent]
path.append(curr)
topicParent = topicPaths[topicParent]
return path | 22dd07a92290c4a7b9e1baf70ef0cc98960b4520 | 693,871 |
def ort_categories(reisende):
"""Returns all unique location tuples in reisende"""
ort = reisende[["Linie", "Richtung", "Haltestelle"]].itertuples(
index=False, name=None
)
ort = list(set(ort))
return ort | e4637e36485632333d6b48fd415be155e300e1cb | 693,872 |
def get(name, default=None):
"""
Get the value of a variable in the settings module scope.
"""
return globals().get(name, default) | 15cb84209896fb39785f3e6014861fa9f74374a1 | 693,874 |
import json
def _get_group_code_names(fob_file_path):
"""Extract code names from first run in fobs file."""
with open(fob_file_path) as f:
data = json.load(f)[0]
return [r['name'] for r in data['runs']] | 82529c133a1a55092d0b629d01522487fcc8bdaf | 693,875 |
def process_index(index, intensity, interaction_symbol):
"""
Process index to get edge tuple. Disregard edge weight.
Args:
index (str): index of the edge list dataframe.
intensity (float): intensity of the edge.
interaction_symbol (str): symbol used to separate node labels.
Returns:
tuple: a tuple containing edge labels.
"""
return tuple(index.split(interaction_symbol)) | 923602fd8be1281b0d28769ccd38e95c03d645b1 | 693,877 |
def _profile_strings(base, tails):
"""Creates a list of profile strings by concatenating base with all
permutations of tails"""
return [base + level + tail[1] for tail in tails for level in tail[0]] | 9a6175d23a7ce89ca3f943a91749859137eb1a6f | 693,878 |
def get_tracks_in_frame(frame_ind, track_list):
""" Return list of all tracks present in frame ind. """
tracks_in_frame = []
for track in track_list:
if (track['last_frame'] >= frame_ind
and track['first_frame'] <= frame_ind):
tracks_in_frame.append(track)
return tracks_in_frame | dd0c76b3729d7ac427ff64be6121c9947af253c8 | 693,879 |
def callables(potential_callables):
"""Ensure that the callables are in fact a sequence."""
if callable(potential_callables):
return [potential_callables]
return potential_callables | 9ce117902deda63a5ed2c6546c418cbd700104c4 | 693,882 |
def get_new_board(dimension):
"""
Return a multidimensional list that represents an empty board (i.e. string with a space at every position).
:param: dimension: integer representing the nxn dimension of your board.
For example, if dimension is 3, you should return a 3x3 board
:return: For example if dimension is 3x3, you should return:
--> [[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]]
"""
result = []
for _ in range(dimension):
result.append([])
for _ in range(dimension):
result[-1].append(" ")
return result | 28e65a0d5eef00d9c27f1d915d41f9e16c3d9026 | 693,886 |
def jobs_with_duration(jobs_df):
"""Return the list of jobs that have a duration"""
return jobs_df[jobs_df.duration_m.notnull()] | 1900ec9f9ac61bc4313055f2d71bef20794bec08 | 693,887 |
from typing import List
from typing import Tuple
from typing import Union
import random
import math
def sampling(
same_name_different_cluster: List[Tuple[str, str, Union[int, float]]],
different_name_same_cluster: List[Tuple[str, str, Union[int, float]]],
same_name_same_cluster: List[Tuple[str, str, Union[int, float]]],
different_name_different_cluster: List[Tuple[str, str, Union[int, float]]],
sample_size: int,
balanced_homonyms_and_synonyms: bool,
random_seed: int,
) -> List[Tuple[str, str, Union[int, float]]]:
"""
Samples pairs from the input list of pairs computed exhaustively from pair_sampling.
Two criteria includes whether balance pairs based on positive/negative classes only
or also consider balancing homonyms and synonyms.
Parameters
----------
same_name_different_cluster: List
list of signature pairs (s1, s2) with same name,
but from different clusters--> (s1, s2, 0).
different_name_same_cluster: List
list of signature pairs (s1, s2) with different name,
but from same cluster--> (s1, s2, 1).
same_name_same_cluster: List
list of signature pairs (s1, s2) with same name,
also from same cluster--> (s1, s2, 1).
different_name_different_cluster: List
list of signature pairs (s1, s2) with different name,
also from different clusters--> (s1, s2, 0).
sample_size: int
The desired sample size
balanced_homonyms_and_synonyms: bool
False -- balance for positive and negative classes
True -- balance for homonyms and synonyms under positive and negative classes
as well (i.e., same_name_different_cluster, different_name_same_cluster,
same_name_same_cluster and different_name_different_cluster)
random_seed: int
random seed for sampling
Returns
-------
List: list of sampled signature pairs
"""
random.seed(random_seed)
if balanced_homonyms_and_synonyms:
same_name_different_cluster_pairs = random.sample(
same_name_different_cluster,
min(len(same_name_different_cluster), math.ceil(sample_size / 4)),
)
different_name_same_cluster_pairs = random.sample(
different_name_same_cluster,
min(len(different_name_same_cluster), math.ceil(sample_size / 4)),
)
same_name_same_cluster_pairs = random.sample(
same_name_same_cluster,
min(len(same_name_same_cluster), math.ceil(sample_size / 4)),
)
different_name_different_cluster_pairs = random.sample(
different_name_different_cluster,
min(len(different_name_different_cluster), math.ceil(sample_size / 4)),
)
pairs = (
same_name_different_cluster_pairs
+ different_name_same_cluster_pairs
+ same_name_same_cluster_pairs
+ different_name_different_cluster_pairs
)
else:
positive = same_name_same_cluster + different_name_same_cluster
negative = same_name_different_cluster + different_name_different_cluster
pairs = random.sample(positive, min(len(positive), math.ceil(sample_size / 2))) + random.sample(
negative, min(len(negative), math.ceil(sample_size / 2))
)
return random.sample(pairs, len(pairs)) | 8a5bef90b76b3d29f63fd7d8d510930671c78b7f | 693,890 |
def compare(
data_a: list,
data_b: list
):
""" Compares two sets of evaluated data with the same
Args:
data_a (list):
data set A
data_b (list):
data set B
Returns:
A String "Correct/Total Answers" and the percentage
"""
# asserts the number of questions is the same
assert len(data_a) == len(data_b)
cnt = 0
for i in range(len(data_a)):
if data_a[i] == data_b[i]:
cnt += 1
return (f"{cnt}/{len(data_a)}", cnt / len(data_a) * 100) | 6bb1ad3ab8a77c10a89174267e29e80bbc5f9ccd | 693,891 |
def minimus(*args):
"""Find the smallest number"""
print(min(*args))
return min(*args) | c94c4879abdd8d5bd5b252e72575efea4e5afff4 | 693,898 |
def _labels_to_state(scan_label, compscan_label):
"""Use scan and compscan labels to derive basic state of antenna."""
if not scan_label or scan_label == 'slew':
return 'slew'
if scan_label == 'cal':
return 'track'
return 'track' if compscan_label == 'track' else 'scan' | a5a6429fa7c7d108fff469b0efe0848e4eb02fcb | 693,902 |
from functools import reduce
def Sum(iterable):
"""Return the concatenation of the instances in the iterable
Can't use the built-in sum() on non-integers"""
it = [ item for item in iterable ]
if it:
return reduce(lambda x,y:x+y, it)
else:
return '' | 2a70a282771f5707a545a12c674f4602cd2f6d7c | 693,903 |
def read_def_file(def_file):
"""Read variables defined in def file."""
ret = {}
f = open(def_file, 'r')
for line_ in f:
if line_.startswith("#"):
continue
line = line_.rstrip()
if len(line) == 0:
continue
if "=" not in line:
continue
var_and_val = line.split("=")
var = var_and_val[0]
val = var_and_val[1].split()[0]
ret[var] = val
f.close()
return ret | 3999378bca9ad4cdccaa480a50635ad567473c66 | 693,905 |
from pathlib import Path
def compute_custom_vars(job_dict, dirs):
"""
DO NOT CHANGE THE NAME OR ARGS OF THIS FUNCTION!!!!!!
This function will receive as input a dictionary representing all
the run parameters for a given job, enhanced with all the keys
provided as global run parameters in your specification YAML file.
It will also receive as input a dictionary referencing various
helpful paths in your structure, for example:
{'base': '/home/fcmeyer/scratch-midway2/running',
'checks': '/home/fcmeyer/scratch-midway2/running/checks',
'slurm_scripts': '/home/fcmeyer/scratch-midway2/running/scripts/slurm',
'slurm_logs': '/home/fcmeyer/scratch-midway2/running/logs/slurm',
'job_scripts': '/home/fcmeyer/scratch-midway2/running/scripts/jobs',
'job_logs': '/home/fcmeyer/scratch-midway2/running/logs/jobs',
'job_inputs': '/home/fcmeyer/scratch-midway2/running/inputs',
'job_work': '/home/fcmeyer/scratch-midway2/running/work'}
If you are planning to have some job-specific stuff be computed,
then please ensure that the return of this function is a dict
including all the key:items in job_dict, plus the key:item pairs
you would like to estimate for a job.
NOTE: the parameters 'job_id', 'path_work' and 'path_inputs'
were already automatically calculated for you and added
to the dict you are getting. Please do NOT estimate them here!
If they are not needed for your spec, they will be cleared out :)
TIP: please include any non-base python imports within the scope of this
function (under the def: statement) since they might not be loaded in my
og code. Also, make sure you install them to your env!
:param job_dict: a dictionary representing a row. for example, if
you had a csv file with rows [sub,ses,task,run,order_id], and also
defined globals [conda_env_path, matlab_path], you would get a dict
{
sub: NIDA2322 ses: 1, task: 'rest', run: 2, order_id:5,
conda_env_path:'/project2/conda/myenv', matlab_path:'/usr/bin/matlab'
}
:param dirs: output of ..utils.io:calculate_directories()
:return: job_dict, plus keys you add!
"""
job_dict["run_inputs"] = str(
Path(dirs["job_work"])
.joinpath("%05d" % job_dict["order_id"])
.joinpath("derivatives")
)
# If you do not have anything to add, just return job_dict.
return job_dict | 17c010bb7d4871211707dac04e6b2d312b3aa233 | 693,906 |
def filter_issues_on_state(issues, value):
"""Filter issues based on the value of their state.
Parameters
----------
issues : list
Issue data.
value : str
Value required for the state, e.g. "open".
Returns
-------
filtered_issues : list
Filtered issues.
"""
filtered_issues = [issue for issue in issues if issue["state"] == value]
return filtered_issues | 3bbff601afb621a4b6cfe5caf89bd04aa6c85063 | 693,912 |
from pathlib import Path
def data_path(path):
"""Return a path inside the `data` folder"""
return Path(__file__).parent.parent.parent / 'tests' / 'data' / path | 37af3bde0869bd9746d9743d237b03b09373a408 | 693,915 |
def select_bin(bin_list, values):
""" Select a bin from a list of bins based on an array of values.
Args:
bin_list (arr): List of Bin objects
values (arr): Array of parameters.
Not that the parameters need to be in the same order that the bins were generated from.
Returns:
Bin corresponding to the appropriate parameters. If no bin exists for those parameters, returns None.
"""
for b in bin_list:
if b.values_in_bin(values):
return b
return None | 5ec77d2cddcf596e786467d96ce79ed3687515fc | 693,917 |
def slice_bounds(seq, slice_obj, allow_step=False):
"""Calculate the effective (start, stop) bounds of a slice.
Takes into account ``None`` indices and negative indices.
:returns: tuple ``(start, stop, 1)``, s.t. ``0 <= start <= stop <= len(seq)``
:raises ValueError: if slice_obj.step is not None.
:param allow_step: If true, then the slice object may have a non-None step.
If it does, then return a tuple (start, stop, step)."""
start, stop = (slice_obj.start, slice_obj.stop)
if allow_step:
slice_obj.step = 1 if slice_obj.step is None else slice_obj.step
# Use a recursive call without allow_step to find the slice
# bounds. If step is negative, then the roles of start and
# stop (in terms of default values, etc), are swapped.
if slice_obj.step < 0:
start, stop, _ = slice_bounds(seq, slice(stop, start))
else:
start, stop, _ = slice_bounds(seq, slice(start, stop))
return start, stop, slice_obj.step
elif slice_obj.step not in (None, 1):
raise ValueError('slices with steps are not supported by %s' %
seq.__class__.__name__)
start = 0 if start is None else start
stop = len(seq) if stop is None else stop
start = max(0, len(seq) + start) if start < 0 else start
stop = max(0, len(seq) + stop) if stop < 0 else stop
if stop > 0: # Make sure stop doesn't go past the end of the list.
try: # Avoid calculating len(seq), may be expensive for lazy sequences
seq[stop - 1]
except IndexError:
stop = len(seq)
start = min(start, stop)
return start, stop, 1 | 1005ce9eccaa078d057dfa1a07be5fbdba3611a7 | 693,918 |
def get_quota(trans, id):
"""Get a Quota from the database by id."""
# Load user from database
id = trans.security.decode_id(id)
quota = trans.sa_session.query(trans.model.Quota).get(id)
return quota | 3c989923e77a837541f414a3e54a7be8911e1faf | 693,920 |
import re
def REGEXMATCH(text, regular_expression):
"""
Returns whether a piece of text matches a regular expression.
>>> REGEXMATCH("Google Doc 101", "[0-9]+")
True
>>> REGEXMATCH("Google Doc", "[0-9]+")
False
>>> REGEXMATCH("The price today is $826.25", "[0-9]*\\.[0-9]+[0-9]+")
True
>>> REGEXMATCH("(Content) between brackets", "\\(([A-Za-z]+)\\)")
True
>>> REGEXMATCH("Foo", "Bar")
False
"""
return bool(re.search(regular_expression, text)) | d5625e9cd06bf3f05569892d09fe22c781f59c00 | 693,921 |
import json
def is_jsonable(obj):
"""
Checks if obj is JSONable (can be converted to JSON object).
Parameters
----------
obj : any
The object/data-type we want to know if it is JSONable.
Returns
-----
boolean
True if obj is JSONable, or False if it is not.
"""
try:
json.dumps(obj)
return True
except TypeError:
return False | 50a568b898c9609206993372983d40add0be4603 | 693,922 |
def get_el_config(charge):
""" Returns the electronic shell structure associated with a nuclear charge """
# Electronic shells: 1s, 2s, 2p, 3s, 3p, 4s, 3d, 4p, 5s, 4d, 5p, 6s, 4f, 5d, 6p, 7s, 5f, 6d, 7p
el_shell = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# Maximum number of electrons for each shell
max_el = [2, 2, 6, 2, 6, 2, 10, 6, 2, 10, 6, 2, 14, 10, 6, 2, 14, 10, 6]
# Set atomic charge as number of remaining electrons
rest_electrons = charge
# Start with first shell (1s)
shell = 0
# Until all electrons are depleted:
while rest_electrons != 0:
# Compare actual shell with maximum occupation number of current shell
if el_shell[shell] != max_el[shell]:
# If current shell is not full, add one electron and deplete it
el_shell[shell] += 1
rest_electrons -= 1
else: # If the shell is full go to the next one
shell += 1
# Return value(s)
return el_shell | db8a06ab5e277ce5468b0e6d43670d92d9a57580 | 693,923 |
from typing import List
import collections
def preprocess(tokens: List[str], fs=False):
"""Return text length, vocabulary size and optionally the frequency
spectrum.
:param fs: additionally calculate and return the frequency
spectrum
"""
txt_len = len(tokens)
vocab_size = len(set(tokens))
if fs:
frequency_list = collections.Counter(tokens)
freq_spectrum = dict(collections.Counter(frequency_list.values()))
return txt_len, vocab_size, freq_spectrum
return txt_len, vocab_size | 03a20358116b3a44791fff32641abe9508e7c233 | 693,927 |
from pathlib import Path
def get_run_number(run_path: Path) -> int:
"""Get the "run number" of a specific run.
Parameters
----------
run_path : Path
Path to the run directory
Returns
-------
int
"run number"
"""
run_info = run_path.name.split("_")[3]
run_num_str = run_info.split("of")[0]
run_num = int(run_num_str)
return run_num | 08946b69bd2b4be818b2fbce2136c04f004bcf05 | 693,928 |
def find_winner_line(line):
"""Return the winner of the line if one exists.
Otherwise return None.
A line is a row, a column or a diagonal.
"""
if len(line) != 3:
raise ValueError('invalid line')
symbols = set(line)
if len(symbols) == 1:
# All equal.
return line[0] # Could be None.
return None | c83bd89a601eacf0ef1d9cfc40ec895b39f18f40 | 693,929 |
def unique(o, idfun=repr):
"""Reduce a list down to its unique elements."""
seen = {}
return [seen.setdefault(idfun(e),e) for e in o if idfun(e) not in seen] | 9cc1d629e7b084acc838b4672dafd0af4df25298 | 693,933 |
import random
def random_text(size):
"""Randomly generate text"""
alphabet_and_numbers = 'abcdefghijklmnopqrstuvwqyz1234567890'
return(''.join(random.choice(alphabet_and_numbers) for _ in range(size))) | fe72e51479756da32456a57c671d51ccee067d72 | 693,935 |
import torch
def get_device(is_gpu=True):
"""Return the correct device"""
return torch.device(
'cuda' if torch.cuda.is_available() and is_gpu else 'cpu') | 30a3389fb165d4dfb6719a50432d4576885461ba | 693,937 |
def isnumeric(x):
"""Test whether the value can be represented as a number"""
try:
float(x)
return True
except:
return False | d98817a855e31ea90a9c26e71f60327217c3323d | 693,938 |
def dict_equal(first, second):
"""
This is a utility function used in testing to determine if two dictionaries are, in a nested sense, equal (ie they have the same keys and values at all levels).
:param dict first: The first dictionary to compare.
:param dict second: The second dictionary to compare.
:return: Whether or not the dictionaries are (recursively) equal.
:rtype: bool
"""
if not set(first.keys()) == set(second.keys()):
return False
for k1, v1 in first.items():
if isinstance(v1, dict) and isinstance(second[k1], dict):
if not dict_equal(v1, second[k1]):
return False
elif not isinstance(v1, dict) and not isinstance(second[k1], dict):
if v1 != second[k1]:
return False
else:
return False
return True | 269ae3059462155e812ff1a5337f59845cfa86d2 | 693,944 |
import math
def ln(input):
"""Logaritmo natural
Devuelve el logaritmo base e de un número.
Args:
input(Number): valor real
Returns:
Number
"""
return math.log(input,math.e) | aca994104608bca957cd0ab4edfc9e7d42c0800b | 693,947 |
def merge(left_array, right_array):
"""
1. Compare first element of both arrays and append the smaller element
2. Increment the index for the array whose element has been pushed to merged array
3. Follow steps 1 and 2 till either of two array is completely merged
4. Whichever array has remaining elements merge that directly as that is already sorted.
:param left_array: one part of array
:param right_array: other part of array
:return: merged_array in sorted form
"""
left_n = len(left_array)
right_n = len(right_array)
i = 0
j = 0
merged_array = list()
while True:
if left_array[i] <= right_array[j]:
merged_array.append(left_array[i])
i += 1
else:
merged_array.append(right_array[j])
j += 1
if i == left_n:
merged_array += right_array[j:right_n]
break
elif j == right_n:
merged_array += left_array[i:left_n]
break
return merged_array | f4997c3e7a4d67b3dd8f2f0c86335b28e29d9450 | 693,952 |
def get_dat_id(datnum, datname):
"""Returns unique dat_id within one experiment."""
name = f'Dat{datnum}'
if datname != 'base':
name += f'[{datname}]'
return name | 4505b1932e89c6e76073605011aa6260563daa84 | 693,956 |
import ctypes
def _IsStructType(t):
"""Tests if a type is a structure."""
return type(t) is type(ctypes.Structure) | 7815d9fc840d3fbd29625404b96fa60eb209dd85 | 693,957 |
def asini_c(pb, mf):
"""
asini_c(pb, mf):
Return the orbital projected semi-major axis (lt-sec) given:
'pb' is the binary period in sec.
'mf' is the mass function of the orbit.
"""
return (mf * pb * pb / 8015123.37129)**(1.0 / 3.0) | 1dd86e3619f2334d6d11c14bc2a7b28c9edb9dcb | 693,961 |
async def root():
"""
Useful for health checks
:return: a simple static JSON object
"""
return {"status": "ok"} | c49c7b99ce096692f3fe5f97e198697fc61c4ccb | 693,962 |
def argkvpair(val):
"""Splitting key value pair"""
k, v = val.split("=", 1)
return k, v | 9da942bbc32b402217cebcbc1a39d637c15f835b | 693,967 |
from typing import Any
from typing import List
from typing import Dict
def check_is_list_of_dicts(x: Any) -> List[Dict[Any, Any]]:
"""Return `x` if it is `List[Dict[Any, Any]]`, raise `ValueError`."""
if not isinstance(x, list):
raise ValueError()
for element in x:
if not isinstance(element, dict):
raise ValueError()
return x | b9c0c09607543e52f29ab678a4a27198e2f8642e | 693,969 |
def php_str_repeat(_input, _multiplier):
"""
>>> php_str_repeat('*', 10)
'**********'
>>> php_str_repeat('xyz', 3)
'xyzxyzxyz'
>>> php_str_repeat('xyz', 0)
''
"""
return _input * _multiplier | f083f3041c324001caa4791e0fda61aaedb9aa50 | 693,970 |
def header_translate_inverse(header_name):
"""Translate parameter names back from headers."""
name_dict = {'XCENREF': 'xcen_ref',
'YCENREF': 'ycen_ref',
'ZENDIR': 'zenith_direction',
'ZENDIST': 'zenith_distance',
'FLUX': 'flux',
'BETA': 'beta',
'BCKGRND': 'background',
'ALPHAREF': 'alpha_ref',
'TEMP': 'temperature',
'PRESSURE': 'pressure',
'VAPPRESS': 'vapour_pressure'}
return name_dict[header_name] | ffd333d190530a70aca014438cb3b49eab032e42 | 693,972 |
def tsne_kwargs(n_dims, initial_dims, perplexity=25.0, n_epochs=1000):
"""Argument options for t-SNE.
Args:
n_dims (int): Number of dimensions to reduce the data down to.
initial_dims (int): Initial number of dimensions of the input data.
perplexity (float): Related to number of nearest neighbors parameter used in other manifold learning algorithms. Larger datasets usually require a larger perplexity. Consider selecting a value between 5 and 50.
n_epochs (int): Number of epochs to fit for.
Returns:
dict: Dictionary for kwargs for t-SNE.
"""
return {
"no_dims": n_dims,
"initial_dims": initial_dims,
"perplexity": perplexity,
"n_epochs": n_epochs
} | 4899997827237b383efb60eb6a2b2b230b879170 | 693,976 |
def restriction(d, keys):
"""Return the dictionary that is the subdictionary of d over the specified
keys"""
return {key: d.get(key) for key in keys} | 9fdb2d2e5bea0d96380e592ffc6d7720b32ade30 | 693,979 |
import re
def is_valid_phone(phone_number: str):
"""Return if the phone_number is valid or not."""
if phone_number:
phone_number = phone_number.replace(' ', '').replace('(', '').replace(')', '')
return re.match(
r'[\+\d]?(\d{2,3}[-\.\s]??\d{2,3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})',
phone_number) is not None
return False | d9837f9a53a59fdbf92f2c16325a6c4a7c61e1c6 | 693,980 |
def binary_to_int(value):
"""Convert binary number to an integer."""
return int(value, 2) | 792b9a01883dc460fb23d10f8415fa6656918c56 | 693,984 |
def mul_with_none(v1,v2):
""" Standard mul treating None with zero """
if v1 is None:
return None
elif v2 is None:
return None
else:
return v1 * v2 | 7065344b6b0efa29cbca14a7ddf85a3ade245fa1 | 693,988 |
def root_node(tree, level):
"""
:param tree: a tree node
:param level: level of the subtree (0 for the tree root)
:return: subtree root at level
"""
root = tree
while root.level > level:
root = root.parent
return root | ae41c019e6e2c395343aa64d32ac6a700e451a24 | 693,989 |
def StringsContainSubstrings(strings, substrings):
"""Returns true if every substring is contained in at least one string.
Looks for any of the substrings in each string. Only requires each substring
be found once.
Args:
strings: List of strings to search for substrings in.
substrings: List of strings to find in `strings`.
Returns:
True if every substring is contained in at least one string.
"""
needles = set(substrings)
for s in strings:
if not needles:
break
for substr in needles:
if substr in s:
needles.remove(substr)
break
if not needles:
return True
return False | 52c4bf8b4b57a9ebb619c71276881668b6b2a1d8 | 693,993 |
def normalize_url(url):
"""If passed url doesn't include schema return it with default one - http."""
if not url.lower().startswith('http'):
return 'http://%s' % url
return url | b957056e8ca32f6294c85466b6e52c56bb1dba84 | 693,995 |
def singleGridIndexToGridIndex(i, nx, ny, nz):
"""
Convert a single into a grid index (3 indices):
:param i: (int) single grid index
:param nx, ny, nz: (int) number of grid cells in each direction
:return: ix, iy, iz:
(3-tuple) grid index in x-, y-, z-axis direction
Note: i can be a ndarray, then
ix, iy, iz in output are ndarray (of same shape)
"""
nxy = nx*ny
iz = i//nxy
j = i%nxy
iy = j//nx
ix = j%nx
return ix, iy, iz | 12b3b69318437d66007fd5295ae209f8186f8b36 | 693,997 |
import inspect
def _get_not_annotated(func, annotations=None):
"""Return non-optional parameters that are not annotated."""
argspec = inspect.getfullargspec(func)
args = argspec.args
if argspec.defaults is not None:
args = args[:-len(argspec.defaults)]
if inspect.isclass(func) or inspect.ismethod(func):
args = args[1:] # Strip off ``cls`` or ``self``.
kwonlyargs = argspec.kwonlyargs
if argspec.kwonlydefaults is not None:
kwonlyargs = kwonlyargs[:-len(argspec.kwonlydefaults)]
annotations = annotations or argspec.annotations
return [arg for arg in args + kwonlyargs if arg not in annotations] | b16e9a2f1e7b71a1b9e4df303a01e67b7eea5482 | 693,998 |
def keysplit(strng):
"""Split an activity key joined into a single string using the magic sequence `⊡|⊡`"""
return tuple(strng.split("⊡|⊡")) | eb1b965843b602410010337f23ea8d0053f2f4b6 | 693,999 |
def flatten_list(list_):
"""
Turn list of lists into list of sublists' elements.
Args:
list_ (list): List to flatten.
Returns:
Flattened list.
"""
return [item for sublist in list_ for item in sublist] | d42e5ef6e2333cbce13e6c4294f8b6b2c8a8ca70 | 694,001 |
def get_close_descriptions(get_close, initial_state, current_state):
"""
Get all 'close' descriptions from the current state (if any).
Parameters
----------
get_close: function
Function that gets the drawer or the door which is closed.
initial_state: nd.array
Initial state of the environment.
current_state: nd.array
Current state of the environment.
Returns
-------
descr: list of str
List of 'close' descriptions satisfied by the current state.
"""
close_descriptions = []
close_thing = get_close(initial_state, current_state)
for c in close_thing:
close_descriptions.append('Close the {}'.format(c))
return close_descriptions.copy() | 54181292066c58968d00e4d8e3d98ec584338e18 | 694,003 |
import torch
def l1_penalty(model, l1_coef):
"""Compute L1 penalty. For implementation details, see:
https://discuss.pytorch.org/t/simple-l2-regularization/139
"""
reg_loss = 0
for param in model.pcca.parameters_('y2'):
reg_loss += torch.norm(param, 1)
return l1_coef * reg_loss | 3a2ddc8bd1eeb64e9ba94ce009e2e621677242e2 | 694,007 |
def list_parameters_from_groups(parameter_groups, groups):
"""Return a list of all the parameters in a list of groups
"""
return [
p for group in groups
for p in parameter_groups[group].values()
] | 2ea08013616fd978a49f8d2d5fa2c233a17fabfc | 694,008 |
def unhex(s):
"""unhex(s) -> str
Hex-decodes a string.
Example:
>>> unhex("74657374")
'test'
"""
return s.decode('hex') | dcf2d6cd9c317b5eafd77e969272fcf753556403 | 694,014 |
import json
def get_features(geojson_file, nl=False):
"""
Get a list of features from something resembling geojson.
Note that if the `nl` option is True, this will return a generator
that yields a single feature from each line in the source file.
"""
if nl:
return (json.loads(line) for line in geojson_file if line.strip())
# if not nl, load the whole file
geojson = json.load(geojson_file)
if not isinstance(geojson, dict):
raise TypeError("GeoJSON root must be an object")
if geojson.get("type") not in ("Feature", "FeatureCollection"):
raise ValueError("GeoJSON must be a Feature or a FeatureCollection")
if geojson["type"] == "Feature":
return [geojson]
return geojson.get("features", []) | 4c3b5bb6011968d3361b44b358a846b51d4fe404 | 694,016 |
def _find_test_plugins(paths_file):
"""
One plugin path per line in a file
Lines starting with a # are considered comments and ignored
:type paths_file: str
:return: List[str]
"""
with open(paths_file) as f:
path = f.read().strip()
lines = path.split('\n')
lines = [x.strip() for x in lines]
lines = [x for x in lines if not x.startswith('#')]
return lines | 85b62e7ab41ea02f8d123379c7b0ed2b96c46566 | 694,019 |
def sort_population(population):
"""
Sorts the population based on fitness values
:param population: population to be sorted
:return: sorted population
"""
return sorted(population, key=lambda tup: float(tup[1]), reverse=True) | b368bcec27cb4162a464260895bfa463729b4df1 | 694,020 |
import hashlib
def block_compute_raw_hash(header):
"""
Compute the raw SHA256 double hash of a block header.
Arguments:
header (bytes): block header
Returns:
bytes: block hash
"""
return hashlib.sha256(hashlib.sha256(header).digest()).digest()[::-1] | 4d6a13316aeda0ec42ca1904ba91170ca0220aae | 694,021 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.