content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def wallet_opened(func):
"""
:param func:
:return:
"""
@wraps(func)
def wapper(self, *args, **kwargs):
if not self.Wallet:
console_log.error("No opened wallet, please open wallet first")
return None
else:
return func(self, *args, **kwargs)
... | 57,000 |
def yamllint(context):
"""Run yamllint to validate formatting adheres to NTC defined YAML standards."""
exec_cmd = "yamllint ."
run_cmd(context, exec_cmd) | 57,001 |
def subtract_electron_shells(s1, s2, rel_tol=0.0):
"""
Returns the difference between two lists of electron shells (s1 - s2)
This will remove any shells from s1 that are also in s2, within a tolerance
"""
diff_shells = []
for sh1 in s1:
for sh2 in s2:
if compare_electron_sh... | 57,002 |
def is_enabled_path(path):
"""
Determine whether or not the path matches one or more paths
in the ENABLED_PATHS setting.
:param path: A string describing the path to be matched.
"""
for enabled_path in ENABLED_PATHS:
match = re.search(enabled_path, path[1:])
if match:
... | 57,003 |
def insert_context(session, run_id: str, algorithm: str, parameters: str) -> Contexts:
"""
method to insert values to the events table
:param session: database session
:param run_id: run_id
:param algorithm: algorithm
:param parameters: parameters
:return: models.Cont... | 57,004 |
def find_matched_pos(str, pattern):
""" Find all positions (start,end) of matched characters
>>> find_matched_pos('ss12as34cdf', '\d')
[(2, 3), (3, 4), (6, 7), (7, 8)]
"""
match_objs = re.finditer(pattern ,str)
match_pos = [match_obj.span() for match_obj in match_objs]
return match_pos | 57,005 |
def clear():
"""Clear all Sessions that are currently not in use."""
from .ovpn import SessionManager
sm = SessionManager()
total, gen = sm.clearer()
for c in range(total):
click.echo(f"\033[?25lDeleting session {c+1}/{total}...\r", nl=False)
next(gen)
if total > 0:
# ... | 57,006 |
def reccyl(rectan1):
"""reccyl(ConstSpiceDouble [3] rectan1)"""
return _cspyce0.reccyl(rectan1) | 57,007 |
def create_tensorboard_visualizations(model, loc, labels=None, write_metadata=True, export_tsv_embeddings=True):
"""Export embeddings to Tensorboard.
This function exports embeddings to disk in a format used by
`TensorBoard <https://www.tensorflow.org/tensorboard>`_ and
`TensorBoard Embedding Projector... | 57,008 |
def get_message_from_dict(d):
"""Create a TAXIIMessage object from a dictonary.
This function automatically detects which type of Message should be created
based on the 'message_type' key in the dictionary.
Args:
d (dict): The dictionary to build the TAXII message from.
Example:
.... | 57,009 |
def diff_files(initial_path, new_path):
"""
Given two files, open them to variables and pass them to diff_strings
for diffing.
:type initial_path: object
:param initial_path: initial file to diff against
:type new_path: object
:param new_path: new file to compare to f1
:returns: string ... | 57,010 |
def script(
description: str = "",
category: Optional[str] = None,
gesture: Optional[str] = None,
gestures: Optional[Iterator[str]] = None,
canPropagate: bool = False,
bypassInputHelp: bool = False,
allowInSleepMode: bool = False,
resumeSayAllMode: Optional[int] = None
):
"""Define metadata f... | 57,011 |
def update():
"""
Stub function for updating app-specific data.
"""
#update_featured_social()
update_songs() | 57,012 |
def write_timestream(Session, records, t_name):
"""This method write records on AWS timestream
Args:
Session: boto3 Session that allows to create service clients and
resources
records: data to be stored in AWS timestream
t_name: table name to be created in AWS timestream inside
... | 57,013 |
def get_doc_vec_keyedvectors(kv_obj, doc_counter, dict_df, avg_scheme):
"""
Calculates a document embedding via weighted averaging
Parameters
----------
kv_obj: KeyedVectors-like object
doc_counter: Counter() that contains the same information as an entry in VowpalWabbit file
dict_df: panda... | 57,014 |
def iterate_drug_info() -> Iterable[Mapping[str, Any]]:
"""Iterate over DrugBank records."""
root = get_xml_root()
for drug_xml in tqdm(root, desc='Drugs'):
yield _extract_drug_info(drug_xml) | 57,015 |
def main(args):
"""
Main entry point
"""
jseddon = User.objects.get(username='jseddon')
years = list(range(1950, 2015))
for year in years:
logger.debug('Processing year {}'.format(year))
ds = DataSubmission.objects.get_or_create(
status='ARRIVED',
incoming... | 57,016 |
def shift_right(shift_register, bit_count):
"""Shifts the least significant bits out of the shift register by the given
amount.
Parameters:
shift_register (ShiftRegister): The shift register to operate on.
bit_count (int): The number of bits to shift out.
Returns:
(ShiftRegister, int): New... | 57,017 |
def mark_corners(image, harris_scores, settings, progress_consumer, progress):
"""
A helper method we use to make the marks of corner as rectangles or bold circles, rather than single pixels.
Use a blank image (black), then light up the pixels that have been found by Harris Detector
This way we crea... | 57,018 |
def _raw_reader(trainFile, countFile, weightFile, raw_queue, batch_size):
"""
"""
batch = []
for item, count, weight in zip(trainFile, countFile, weightFile):
batch.append((item, count, weight))
if len(batch) == batch_size:
raw_queue.put(batch)
batch = []
if l... | 57,019 |
def build_fairseq_vocab(
vocab_file: str,
dictionary_class: Dictionary = Dictionary,
special_token_replacements: Dict[str, str] = None,
unk_token: str = "<unk>",
max_vocab: int = -1,
min_count: int = -1,
tokens_to_add: Optional[List[str]] = None,
):
"""Function builds a torchtext Vocab f... | 57,020 |
def print_board(board):
"""
prints a two-dimensional tictactoe board
"""
for row in board:
print(convert_row(row))
print('______') | 57,021 |
def score_density(leaderboard):
"""Create a density esitmate figure for each user
It will be useful to keep track of how much each user's score's
vary over time. This will give us a density estimate for each
user's scores.
"""
board = leaderboard.drop(['Submission Time', 'counter'], axis=1)
... | 57,022 |
def getSplunkVersion(sessionKey):
""" function to obtain the Splunk software version. This is used to determine parsing of the sessionKey """
from xml.dom import minidom
base_url = 'https://localhost:8089'
request = urllib2.Request(base_url + '/services/server/info',None,headers = { 'Authorization': ... | 57,023 |
def preprocessing(filepath,files,product,attr):
"""
ๆๆฌ้ขๅค็
:return:
"""
#with open(text_path) as f:
# content = readtxtline(text_path)
# print(content)
content = readexcel(filepath)[product][attr]
return clean_using_stopword(content,files)
return content | 57,024 |
def fetch_fhpg(code):
"""่ก็ฅจๅ็บข้
่กๆฐๆฎ
่ฟๅ๏ผ
list
0๏ผ ๅ็บข้
่ก
1๏ผ ้
่กไธ่ง
2๏ผ ๅขๅไธ่ง
3๏ผ ๅๅนด่่ต่ฎกๅ
"""
url = f'http://quotes.money.163.com/f10/fhpg_{code}.html#01d05'
r = requests.get(url)
attrs = {'class': 'table_bg001 border_box limit_sale'}
dfs = pd.read_html(r.text, at... | 57,025 |
def run_launcher(config: Configuration) -> Dict[str, Any]:
"""Runs the launcher.
Returns the dict with two entries:
"artifacts" - contain a mapping `Artifact` => `bool denoting if artifact is deploted`
"instances" - contain a mapping `Instance` => `Optional[InstanceId]`.
"""
with Launcher(conf... | 57,026 |
def black_payers_swaption_value_fprime_by_strike(
init_swap_rate,
option_strike,
swap_annuity,
option_maturity,
vol):
"""black_payers_swaption_value_fprime_by_strike
First derivative of value of payer's swaption with respect to strike
under black model.
See :py:fu... | 57,027 |
def utc2localdatetime(naive):
""" input: naive utc timestamp from dataframe
output: timestamp in local tz """
#print("naive=", naive)
utc = naive.tz_localize(utctz)
#print('utc=', utc)
pac = utc.astimezone(pactz)
#print('pac=', pac)
return pac | 57,028 |
def ensure_dir(directory):
"""Ensures that the path specified is an existing directory.
If not, create it"""
if not os.path.exists(directory):
os.makedirs(directory) | 57,029 |
def delete(file_name: str) -> None:
"""Removes file at path specified by ``file_name``"""
if path.exists(file_name):
os.remove(file_name) | 57,030 |
def box_area(box):
"""
Calculates the area of a bounding box.
Source code mainly taken from:
https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/
`box`: the bounding box to calculate the area for with the format ((x_min, x_max), (y_min, y_max))
return: the b... | 57,031 |
def dsigmoid(sigmoid_x):
"""
dSigmoid(x) = Sigmoid(x) * (1-Sigmoid(x)) = Sigmoid(x) - Sigmoid(x)^2
"""
return sigmoid_x - sigmoid_x**2 | 57,032 |
def clip(agera5_dir, day, bbox, add_gridid=False):
"""Extracts a portion of agERA5 for the given bounding box and returns a Xarray dataset.
:param agera5_dir: the path to AgERA5
:param day: the date for which to clip
:param bbox: a BoundingBox object
:param add_idgrid: Add a grid ID (True) or not (... | 57,033 |
def shortcut_url(url, name):
"""
:param url:
:param name:
:return:
"""
# remove slash at the end
if url.endswith('/'):
url = url[:-1]
# gitlab
gl_prefix = 'https://gitlab.com/'
if url.startswith(gl_prefix):
return [make_icon('gitlab', css='is-link'), make_text(u... | 57,034 |
def _get_modules(package, attr_name, constants_attr_name):
"""Get list of TF API modules.
Args:
package: We only look at modules that contain package in the name.
attr_name: Attribute set on TF symbols that contains API names.
constants_attr_name: Attribute set on TF modules that contains
API con... | 57,035 |
def get_day(game):
"""Return single day"""
payload = PAYLOAD_SAMPLE
payload["gameID"] = game.game_id
payload["stateType"] = 12
request = requests.post(game.game_host, headers=HEADERS, json=payload)
text = json.loads(request.text)
if not check_response(game.game_id, text):
return ge... | 57,036 |
def compose_text_context_menu_click (selectedtext) :
"""Translate selected text to LOLSPAEK"""
return translate_to_lolspeak(selectedtext) | 57,037 |
def find_blobs(
key:typing.Tuple[int, int, int],
x0s:int, x1s:int, y0s:int, y1s:int, z0s:int, z1s:int) -> \
typing.Tuple[np.ndarray, np.ndarray]:
"""
Find blobs in a volume
:param volume: the volume in question
:param x0s: the starting x coordinate in global coordinates
:par... | 57,038 |
def progress_bar(iteration, total):
"""
entertain the user with a simple yet exquisitely designed progress bar and %
:param iteration:
:param total:
:return:
"""
try:
perc = round((iteration/total)*100, 2)
bar = ('โ'*19).replace('โ','โ',int(round(perc/5,0))) + 'โ'
ret... | 57,039 |
def check_privileges(privilege_names: list, session, user) -> bool:
"""
Function for checking a user's privileges match requirements.
Authorised if no privilege names in argument and user is logged in.
Authorised if user has listed privilege or admin.
:param: List of names of privileges with acces... | 57,040 |
def dreaming(agent, cameras, lidars, occupancies, actions, obstype, basedir):
""" Given observation, actions, camera and map images
run 'dreaming' in latent space and store the real observation and the reconstructed one.
"""
data = {'lidar': np.stack(np.expand_dims(lidars, 0)),
'action':... | 57,041 |
def make_tensor_seed(seed):
"""Converts a seed to a `Tensor` seed."""
if _is_stateful_seed(seed):
iinfo = np.iinfo(np.int32)
return tf.random.uniform([2],
minval=iinfo.min,
maxval=iinfo.max,
dtype=tf.int32,
... | 57,042 |
def do_setup_gae(path, runtime):
"""write fake GAE ``app.yaml`` to current directory so nosegae will work"""
from passlib.tests.utils import set_file
set_file(os.path.join(path, "app.yaml"), """\
application: fake-app
version: 2
runtime: %s
api_version: 1
threadsafe: no
handlers:
- url: /.*
script: dummy... | 57,043 |
def _validate_same_ids_and_types(
predictor_table_path, scenario_predictor_table_path):
"""Ensure both tables have same ids and types.
Assert that both the elements of the 'id' and 'type' fields of each table
contain the same elements and that their values are the same. This
ensures that a use... | 57,044 |
def test_method_validation_not_a_docker_tar(submission_file):
"""Upload something that isn't a docker file should be invalid."""
method = MethodFactory(image__from_path=submission_file)
assert method.ready is False
with pytest.raises(ValidationError):
validate_docker_image(
pk=metho... | 57,045 |
def par_auteur(name):
"""
Add 'par' to the author names
"""
author_phrase = ''
if name:
author_phrase = " par {},".format(name)
return author_phrase | 57,046 |
def remove_items(item_capacities:Dict[str,int], items_to_remove:List[str])->Dict[str,int]:
"""
Remove the given items from the given dict.
>>> stringify(remove_items({"x":3, "y":2, "z":1, "w":0}, ["x","y"]))
'{x:2, y:1, z:1}'
>>> stringify(remove_items({"x":3, "y":2, "z":1, "w":0}, ["y","z"]))
... | 57,047 |
def split_results(result: Result, agg_info:Dict[Any, Any]) -> List[Result]:
"""Retrieve the results of the initial quantum circuits from the aggregated result
Args:
result (Result): Result of the aggregated QuantumCircuit
agg_info (Dict[Any, Any]): aggregation information as Dict
Returns:
... | 57,048 |
def text_value(value):
"""Force a value to text, render None as an empty string."""
if value is None:
return ""
return force_text(value) | 57,049 |
def train(fcstnet, train_x, train_y, validation_x=None, validation_y=None, restore_session=False):
"""
Train the ForecastNet model on a provided dataset.
In the following variable descriptions, the input_seq_length is the length of the input sequence
(2*seasonal_period in the paper) and output_seq_len... | 57,050 |
def get_networks_for_instance(context, instance):
"""Returns a prepared nw_info list for passing into the view builders
We end up with a data structure like::
{'public': {'ips': [{'address': '10.0.0.1',
'version': 4,
'mac_address': 'aa:aa:aa:aa... | 57,051 |
def load_article_from_nif_file(nif_file, corpus_name, limit=1000000):
"""
Load a dataset in NIF format.
"""
print(f'NOW LOADING THE NIF FILE {nif_file}')
g = Graph()
#for nif_file in glob.glob('%s/*.ttl' % nif_dir):
g.parse(nif_file, format="n3")
print(f'THE FILE {nif_file} IS LOADED. N... | 57,052 |
def patch_docutils(confdir: str = None) -> Generator[None, None, None]:
"""Patch to docutils temporarily."""
with patched_get_language(), using_user_docutils_conf(confdir):
yield | 57,053 |
def _draw_equal_dataset(
target: np.ndarray, num_samples: int = 1000, allowed_classes: List[int] = None
) -> np.ndarray:
"""
given the `target` and `num_samples`, return the labeled_index`
:param target: target
:param num_samples: 4000
:param allowed_classes: None or list of targets like [0, 1, ... | 57,054 |
def firstof(parser, token):
"""
Outputs the first variable passed that is not False.
Outputs nothing if all the passed variables are False.
Sample usage::
{% firstof var1 var2 var3 as myvar %}
This is equivalent to::
{% if var1 %}
{{ var1 }}
{% elif var2 %}
... | 57,055 |
def canPickupPile(top_card, prepared_cards, played_cards, round_index):
"""Determines if the player can pick up the pile with their suggested play"""
top_key = None
try:
key_opts = getKeyOptions(top_card)
except:
raise Exception("Cannot pickup the pile on 3s because you cannot play 3s")
... | 57,056 |
def cli_xml(argv: Optional[List[str]] = None):
"""Cmdline entrypoint for converting MyST to XML."""
_run_cli("xml", "Docutils-native XML", argv) | 57,057 |
def loadSubscriptions():
"""Load subscription functionality"""
ret = sqlQuery("SELECT label, address, enabled FROM subscriptions")
for row in ret:
label, address, enabled = row
subscriptions.append([label, address, enabled])
subscriptions.reverse() | 57,058 |
def _valid_arg(*args, src=None):
"""Return some data, possibly extracted from an AxisManager (or
dict...), based on the arguments args. This is to help with
processing function arguments that override a default behavior
which is to look up a thing in axisman. For example::
signal = _valid_arg(s... | 57,059 |
def find_nearest_store(lat_lng, stores, units):
"""Finds store from list of stores that is closest to a given set of coords.
Args:
lat_lng (list(float)): Latitude and longitude being compared to.
stores (list(dict)): List of stores to search against.
units (str): Distance metric used fo... | 57,060 |
def load_environment_auth_vars() -> tuple:
"""Attempts to load authentication information from environment variables if none is given, looks for a username
under "FHIR_USER", password under "FHIR_PW" and the token under "FHIR_TOKEN"
Returns:
Tuple containing username, password and token if they wer... | 57,061 |
def aumentar(p, tax):
"""
-> Aumenta o valor inicial em uma porcentagem definida pelo usuรกrio
:param p: valor inicial
:param tax: valor da taxa
:return: valor inicial somada a taxa
"""
res = p + (p * tax/100)
return res | 57,062 |
def test_get_observed_property_variables():
"""Test that all of the observed property variable are returned"""
catalog = CatalogDjango()
plugins = [alpha.AlphaSourcePlugin(catalog)]
catalog.initialize(plugins)
basin3d_variable = [i.basin3d_id for i in catalog.find_observed_property_variables()]
... | 57,063 |
def spatial_mass(I_s: array[spatial_matrix], joint_start: int32, joint_count: int32, M_start: int32, M: array[float32]):
"""
"""
... | 57,064 |
def _stringify_ast(
node: Union[ast.AST, ast3.AST, ast27.AST], depth: int = 0
) -> Iterator[str]:
"""Simple visitor generating strings to compare ASTs by content."""
node = _fixup_ast_constants(node)
yield f"{' ' * depth}{node.__class__.__name__}("
for field in sorted(node._fields): # noqa: F40... | 57,065 |
def greenfield_5g_sa(region, strategy, costs,
global_parameters, core_lut, country_parameters):
"""
Get the cost structure for a greenfield 5G SA asset.
Parameters
----------
region : dict
The region being assessed and all associated parameters.
strategy : dict
The strategy ... | 57,066 |
def predict_landmarks(param, bbox, dense=False):
""" Predicts the 68 face landmarks from a 3D face, scaling them by the face bounding box.
Parameters:
param (ndarray): Contains 3DMM params (12-pose, 40-shape, 10-expression).
bbox (array): The face bounding box.
dense (bool): Predic... | 57,067 |
def get_completed_ids():
"""
returns list of stellar IDs that have been fit
"""
return np.loadtxt(os.path.join(DATADIR, 'completed.list'), dtype=int) | 57,068 |
def EVLASrvrEdt(uv, err, minOK=[0.1,0.1], flagTab=2, target=None, \
doCalib=0, gainUse=0, doBand=0, BPVer=0, flagVer=-1, \
nThreads=1, check=False, debug=False, logfile = ""):
"""
Survivor editing
See documentation for task Obit/UVFlag for details
Returns tas... | 57,069 |
def cleanup_file_from_option(option, bootflash_root=False):
"""
Removes a file (indicated by the option in the POAP options) and removes it
if it exists.
We handle the cases where the variable is unused (defaults to None) or
where the variable is not set yet (invoking this cleanup before we init)
... | 57,070 |
def calculate_engine_path(ctx):
"""
Determine the engine root path from SetupAssistantUserPreferences. if it exists
:param conf Context
"""
def _make_engine_node_lst(node):
engine_node_lst = []
cur_node = node
while cur_node.parent:
if ' ' in cur_node.name:
... | 57,071 |
def _robust_extract(to_dir, *args, **kwargs):
"""For some obscure reason this operation randomly fails.
Try to make it more robust.
"""
def func():
with tarfile.open(*args, **kwargs) as tf:
if not len(tf.getnames()):
raise RuntimeError("Empty tarfile")
t... | 57,072 |
def calculate_directions_single_track(
single_traj: pd.DataFrame, dt: int = 1, time_step: float = 10
):
"""Calculate distribution of angles for a particular dt.
dt in arbitrary units.
If an appropriate frame is missing than simply do not
calculate any angle.
inputs:
single track in a Da... | 57,073 |
def markdown(value):
"""
Run Markdown over a given value.
"""
return mark_safe(markdown_func(value)) | 57,074 |
def post_messages():
"""
Post message here..
returns the message passed if authorized!
"""
# check api_key header
current_api_key = request.headers.get('api_key')
if current_api_key is None \
or not api_key_exists(current_api_key):
return jsonify({'message': 'Una... | 57,075 |
def get_min_freeboard(fjord):
"""
Get a required minimum median freeboard for filtering out icebergs
"""
minfree = {"JI": 15, "KB":5}
try:
return minfree.pop(fjord)
except KeyError:
print("The current fjord does not have a minimum freeboard median entry - using a default value!... | 57,076 |
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm, extra_context=None):
"""
Displays the login form and handles the login action.
"""
if request.method == "POST":
redirect_to = request.GET.get(red... | 57,077 |
def view_assignments(id, course_id):
"""Single page view of all the assignments in a session."""
con = db.get_db()
cur = con.cursor()
cur.execute("""SELECT sessions.id, sessions.course_id, courses.course_id,
courses.teacherid, courses.name
AS class_name FROM sessions JO... | 57,078 |
def test_update_sandbox_ride(authorized_sandbox_client):
"""Test to update sandbox ride status with access token."""
response = authorized_sandbox_client.update_sandbox_ride(
ride_id=RIDE_ID,
new_status='accepted',
)
assert response.status_code == codes.no_content | 57,079 |
def bufr_surface_parser(config, model, stid, forecast_date, bufr_file_name):
"""
By Luke Madaus. Modified by jweyn and joejoezz.
Parse surface data from a bufkit file.
"""
# Open bufkit file
infile = open(bufr_file_name, 'r', newline='')
# define variables
dateTime = []
temperature... | 57,080 |
def encode(args, files):
"""
Encode form (name, value) and (name, filename, type) elements into
multi-part/form-data. We don't actually need to know what we are
uploading here, so just claim it's all text/plain.
"""
boundary = '----------=_DQM_FILE_BOUNDARY_=-----------'
(body, crlf) = ('', '\r\n')
... | 57,081 |
def name_indel_mutation(sbjct_seq, indel, sbjct_rf_indel, qry_rf_indel, codon_no, mut, start_offset):
"""
This function serves to name the individual mutations dependently on
the type of the mutation.
"""
# Get the subject and query sequences without gaps
sbjct_nucs = sbjct_rf_indel.replace("-"... | 57,082 |
def clone_or_construct(estimator):
"""
Clone an estimator, or construct a default one from a class or function.
Parameters
----------
estimator : sklearn estimator instance, class, or a function returning same.
Returns
-------
estimator
"""
try:
return clone(estimator)
except TypeError:
if inspect.iscl... | 57,083 |
def setup_mixins(
policy: Policy,
obs_space: gym.spaces.Space,
action_space: gym.spaces.Space,
config: TrainerConfigDict,
) -> None:
"""Call mixin classes' constructors before Policy's loss initialization.
Args:
policy (Policy): The Policy object.
obs_space (gym.spaces.Space): T... | 57,084 |
def _upsampled_dft(data, upsampled_region_size,
upsample_factor=1, axis_offsets=None):
"""
Upsampled DFT by matrix multiplication.
This code is intended to provide the same result as if the following
operations were performed:
- Embed the array "data" in an array that is ``up... | 57,085 |
def extract_text(pdf_file, password='', page_numbers=None, maxpages=0,
caching=True, codec='utf-8', laparams=None):
"""Parse and return the text contained in a PDF file.
:param pdf_file: Either a file path or a file-like object for the PDF file
to be worked on.
:param password: For... | 57,086 |
def write_group(pf, tag,mdef):
"""
This function is implements the repetitious task of creating a
csv file of attributes that have some kind of logical or required
grouping in MsPASS. The tag argument is used to create a csv
file of the same name for output. e.g. if tag is 'source' the
functi... | 57,087 |
def server_add_and_update_opts(f: Optional[Callable] = None, *, add=False):
"""
shared collection of options for `globus transfer endpoint server add` and
`globus transfer endpoint server update`.
Accepts a toggle to know if it's being used as `add` or `update`.
usage:
>>> @server_add_and_upda... | 57,088 |
def richicon_src(icon):
"""
Returns link to the icon.
"""
src = richtemplates_settings.ICONS_URL + icon
return src | 57,089 |
def stanley_control(
state, cx, cy, cyaw, last_target_idx=0, k=0.7, params=VehicleParams()
):
"""
Stanley steering control.
:param state: (State object)
:param cx: [m] x-coordinates of (sampled) desired trajectory
:param cy: [m] y-coordinates of (sampled) desired trajectory
:param cyaw: [ra... | 57,090 |
def test_perihelion_attr():
"""
Checks various attributes of perihelion()
"""
p = perihelion()
assert isinstance(p, Timelike)
assert p.state.shape[0] == 8
assert p.trajectory.shape[1] == 8
assert isinstance(p.metric, Schwarzschild) | 57,091 |
def dumps(obj: dict, encoding=None, iso_config=None, hex_bitmap=False):
"""
Serialize obj to a ISO8583 message byte string
:param obj: dict containing message data
:param encoding: python text encoding scheme
:param iso_config: iso8583 message configuration dict
:param hex_bitmap: bitmap in hex... | 57,092 |
def pixel_to_cube(p, size):
"""
Converts pixel position to cube coords.
:param p: The point x, y.
:param size: The size of each hex.
:return: The cube coord x, y, z of the pixel.
"""
return cube_round(axial_to_cube(pixel_to_axial(p, size))) | 57,093 |
def test_unicode_fields(filename, attribute):
"""All parsers should return text fields as unicode"""
rep = report.parse(os.path.join(os.path.dirname(__file__),
'data', filename))
assert isinstance(getattr(rep.pubs[0], attribute), text_type) | 57,094 |
def mock_pydicom_config_data_element_callback(mocker: MockerFixture):
"""
Mocking pydicom config
"""
return mocker.patch.object(pydicom.config, 'data_element_callback') | 57,095 |
def kwp_edge_disjoint(graph, node_start, node_end, max_k, credit_mat):
""" compute k edge disjoint widest paths """
""" using http://www.cs.cmu.edu/~avrim/451f08/lectures/lect1007.pdf """
graph = copy.deepcopy(graph)
capacity_mat = credit_mat
A = []
try:
path = nx.shortest_path(graph, ... | 57,096 |
def test_sepia() -> None:
""" Developed by Trong Nguyen, 100848232
Reviewed by Ahmed Abdellah, 101163588
Test whether sepia function pass or fail.
>>> test_sepia()
"""
original = create_image(6, 1)
set_color(original, 0, 0, create_color(0, 0, 0))
set_color(... | 57,097 |
def build_tag_regex(plugin_dict):
"""Given a plugin dict (probably from tagplugins) build an 'or' regex
group. Something like: (?:latex|ref)
"""
func_name_list = []
for func_tuple in plugin_dict:
for func_name in func_tuple:
func_name_list.append(func_name)
regex = '|'.joi... | 57,098 |
def is_html_like(text):
"""
Checks whether text is html or not
:param text: string
:return: bool
"""
if isinstance(text, str):
text = text.strip()
if text.startswith("<"):
return True
return False
return False | 57,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.