content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def delete_user_feed(user_id, feed_url_to_delete):
"""Удаление отслеживаемого источника пользователя из базы данных"""
try:
for source_name in sources_names:
cursor.execute(f'DELETE FROM {source_name}_sources WHERE user_id = ? and feed_url = ?',
(user_id, feed_url_... | 5,300 |
def extend_blob_sentiment_database(company_name, client_address):
"""
Calculate the 3 days and 7 days textblob sentiment scores based on 1 day sentiment average.
Perform this operation only after 1 day sentiment score is obtained.
:param company_name: the name of the company. Used as the entry in the d... | 5,301 |
def transform_pairwise(X, y):
"""Transforms data into pairs with balanced labels for ranking
Transforms a n-class ranking problem into a two-class classification
problem. Subclasses implementing particular strategies for choosing
pairs should override this method.
In this method, all pairs are choos... | 5,302 |
def run_process(args, palette):
"""Process qrc files."""
# Generate qrc file based on the content of the resources folder
id_ = palette.ID
# Create palette and resources png images
print('Generating {} palette image ...'.format(id_))
create_palette_image(palette=palette)
print('Generating... | 5,303 |
def handle_in(distance):
"""Within range
:param distance: Distance
"""
print("in range", distance) | 5,304 |
def delete_volume(volid, region):
"""
Delete a volume
"""
Dryrun = True
if GOLIVE.lower() == 'true':
Dryrun = False
else:
print('Running in Dryrun mode')
ec2 = connect('ec2', region)
response = ec2.delete_volume(
VolumeId=volid,
DryRun=Dryrun
)
r... | 5,305 |
def format_project_title(rank: int, project_id: str, status: str) -> str:
"""Formats a project title for display in Slack.
Args:
rank: The rank of in the list. Will be prepended to the title.
project_id: The project ID.
status: The status of the project. This is used to determine which
... | 5,306 |
def fake_3dimage_vis():
"""
:return: a Nifti1Image (3D) in RAS+ space
Following characteristics:
- shape[LR] = 7
- shape[PA] = 8
- shape[IS] = 9
Visual thing using voxel art...
"""
shape = (7,8,9)
data = np.zeros(shape, dtype=np.float32, order="F")
# "L"
indices =np... | 5,307 |
def watch_dependencies(dependency, func, time_execution=15000, registry=None, app=current_app):
"""
Register dependencies metrics up
"""
if not registry:
registry = app.extensions.get("registry", CollectorRegistry())
app.extensions["registry"] = registry
# pylint: disable=invalid-n... | 5,308 |
def view_cache_key(func, args, kwargs, extra=None):
"""
Calculate cache key for view func.
Use url instead of not properly serializable request argument.
"""
if hasattr(args[0], 'build_absolute_uri'):
uri = args[0].build_absolute_uri()
else:
uri = args[0]
return 'v:' + func_c... | 5,309 |
def get_filter(sampling_freq, f_pass, f_stop, taps):
"""Get FIR filter coefficients using the Remez exchange algorithm.
Args:
f_pass (float): Passband edge.
f_stop (float): Stopband edge.
taps (int): Number of taps or coefficients in the resulting filter.
Returns:
(numpy.nd... | 5,310 |
def errorcode_from_error(e):
"""
Get the error code from a particular error/exception caused by PostgreSQL.
"""
return e.orig.pgcode | 5,311 |
def _comp_point_coordinate(self):
"""Compute the point coordinates needed to plot the Slot.
Parameters
----------
self : SlotW28
A SlotW28 object
Returns
-------
point_dict: dict
A dict of the slot point coordinates
"""
Rbo = self.get_Rbo()
# alpha is the angle... | 5,312 |
def save_expected_plot(series: pd.Series, colour="C0") -> IO:
"""Return an image of the plot with the given `series` and `colour`."""
fig, ax = plt.subplots()
ax.add_line(mpl_lines.Line2D(series.index, series.values, color=colour))
return _save_fig(fig, ax) | 5,313 |
def GRU_architecture(
GRU_layers,
GRU_neurons,
Dense_layers,
Dense_neurons,
add_Dropout,
Dropout_rate,
data_shape,
):
"""
Parameters
----------
GRU_layers : int
Number of GRU layers.
GRU_neurons : list
List with the numbers of GRU cells in each GRU layer.
... | 5,314 |
def _responds_plaintext(response):
"""sichert zu, dass die Antwort plaintext war."""
response.responds_http_status(200)
response.responds_content_type('text/plain') | 5,315 |
def test_message():
"""Test converting value and coords to message."""
shape = (10, 2)
np.random.seed(0)
data = 20 * np.random.random(shape)
data[-1] = [0, 0]
layer = Points(data)
msg = layer.get_message()
assert type(msg) == str | 5,316 |
def create_lock(name):
"""Creates a file in the /locks folder by the given name"""
lock_path = get_lock_path(name)
if not check_lock(lock_path):
return touch_file(lock_path)
else:
return False | 5,317 |
def gen_rigid_tform_rot(image, spacing, angle):
"""
generate a SimpleElastix transformation parameter Map to rotate image by angle
Parameters
----------
image : sitk.Image
SimpleITK image that will be rotated
spacing : float
Physical spacing of the SimpleITK image
angle : flo... | 5,318 |
def get_param_response(param_name, dict_data, num=0, default=None):
"""
:param param_name: 从接口返回值中要提取的参数
:param dict_data: 接口返回值
:param num: 返回值中存在list时,取指定第几个
:param default: 函数异常返回
:return: 提取的参数值
"""
if isinstance(dict_data, dict):
for k, v in dict_data.items():
if... | 5,319 |
def _strict_conv1d(x, h):
"""Return x * h for rank 1 tensors x and h."""
with ops.name_scope('strict_conv1d', values=[x, h]):
x = array_ops.reshape(x, (1, -1, 1, 1))
h = array_ops.reshape(h, (-1, 1, 1, 1))
result = nn_ops.conv2d(x, h, [1, 1, 1, 1], 'SAME')
return array_ops.reshape(result, [-1]) | 5,320 |
def explorer():
"""Explorer"""
pass | 5,321 |
def timed_zip_map_agent(func, in_streams, out_stream,
call_streams=None, name=None):
"""
Parameters
----------
in_streams: list of Stream
The list of input streams of the agent.
Each input stream is timed, i.e. the elements
are pairs (timestam... | 5,322 |
def get_repository_ids_requiring_prior_install( trans, tsr_ids, repository_dependencies ):
"""
Inspect the received repository_dependencies and determine if the encoded id of each required repository is in the received tsr_ids. If so,
then determine whether that required repository should be installed prio... | 5,323 |
def get_words_and_spaces(
words: Iterable[str], text: str
) -> Tuple[List[str], List[bool]]:
"""Given a list of words and a text, reconstruct the original tokens and
return a list of words and spaces that can be used to create a Doc. This
can help recover destructive tokenization that didn't preserve an... | 5,324 |
def parse_names(source: str) -> List['Name']:
"""Parse names from source."""
tree = ast.parse(source)
visitor = ImportTrackerVisitor()
visitor.visit(tree)
return sum([split_access(a) for a in visitor.accessed], []) | 5,325 |
def get_supported_language_variant(lang_code, strict=False):
"""
Returns the language-code that's listed in supported languages, possibly
selecting a more generic variant. Raises LookupError if nothing found.
If `strict` is False (the default), the function will look for an alternative
country-spec... | 5,326 |
def mean_square_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""
Calculate MSE loss
Parameters
----------
y_true: ndarray of shape (n_samples, )
True response values
y_pred: ndarray of shape (n_samples, )
Predicted response values
Returns
-------
MSE of g... | 5,327 |
def gmail_auth(logfile, mode):
"""Handles Gmail authorization via Gmail API."""
creds = None
# the file .token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time
pickled_token = "../conf/.token.pickle"
... | 5,328 |
def graduation_threshold(session):
"""get graduation threshold
url : "/user/graduation-threshold"
Args:
session ([requests.session]): must be login webap!
Returns:
[requests.models.Response]: requests response
other error will return False
"""
# post it, it will re... | 5,329 |
def q_conjugate(q):
"""
quarternion conjugate
"""
w, x, y, z = q
return (w, -x, -y, -z) | 5,330 |
def finalize_schemas(fields_nested):
"""Clean up all schema level attributes"""
for schema_name in fields_nested:
schema = fields_nested[schema_name]
schema_cleanup_values(schema) | 5,331 |
def put_data(
click_ctx,
mount_dir,
project,
source,
source_path_file,
break_on_fail,
overwrite,
num_threads,
silent,
):
"""Upload data to a project.
Limited to Unit Admins and Personnel.
To upload a file (with the same name) a second time, use the `--overwrite` flag.
... | 5,332 |
def displayMetaDataSubWindow(weasel, tableTitle, dataset):
"""
Creates a subwindow that displays a DICOM image's metadata.
"""
try:
logger.info('ViewMetaData.displayMetaDataSubWindow called.')
title = "DICOM Image Metadata"
widget = QWidget()
widget.... | 5,333 |
def row_r(row, boxsize):
"""Cell labels in 'row' of Sudoku puzzle of dimension 'boxsize'."""
nr = n_rows(boxsize)
return range(nr * (row - 1) + 1, nr * row + 1) | 5,334 |
def send_warning_mail_patron_has_active_loans(patron_pid):
"""Send email to librarians user cannot be deleted because active loans.
:param patron_pid: the pid of the patron.
:param message_ctx: any other parameter to be passed as ctx in the msg.
"""
Patron = current_app_ils.patron_cls
patron = ... | 5,335 |
def get_set_from_word(permutation: Sequence[int], digit: Digit) -> set[int]:
"""
Returns a digit set from a given digit word,
based on the current permutation.
i.e. if:
permutation = [6, 5, 4, 3, 2, 1, 0]
digit = 'abcd'
then output = {6, 5, 4, 3}
"""
return {permutation[ord(char) -... | 5,336 |
def get_avg_sentiment(sentiment):
"""
Compiles and returnes the average sentiment
of all titles and bodies of our query
"""
average = {}
for coin in sentiment:
# sum up all compound readings from each title & body associated with the
# coin we detected in keywords
averag... | 5,337 |
def is_valid(url):
"""
Checks whether `url` is a valid URL.
"""
parsed = urlparse(url)
return bool(parsed.netloc) and bool(parsed.scheme) | 5,338 |
def data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_total_size_put(uuid, tapi_common_capacity_value=None): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_total_size_put
creates or updates tapi.common.CapacityValue # noqa: E501
:... | 5,339 |
def statistics_power_law_alpha(A_in):
"""
Compute the power law coefficient of the degree distribution of the input graph
Parameters
----------
A_in: sparse matrix or np.array
The input adjacency matrix.
Returns
-------
Power law coefficient
"""
degrees = A_in.sum(ax... | 5,340 |
def does_file_exist(path):
""" Checks if the given file is in the local filesystem.
Args:
path: A str, the path to the file.
Returns:
True on success, False otherwise.
"""
return os.path.isfile(path) | 5,341 |
def common_gnuplot_settings():
""" common gnuplot settings. """
g_plot = Gnuplot.Gnuplot(persist=1)
# The following line is for rigor only. It seems to be assumed for .csv files
g_plot('set datafile separator \",\"')
g_plot('set ytics nomirror')
g_plot('set xtics nomirror')
g_plot('set xtics ... | 5,342 |
def video_feed_cam1():
"""Video streaming route. Put this in the src attribute of an img tag."""
cam = Camera(0)
return Response(gen(cam), mimetype='multipart/x-mixed-replace; boundary=frame') | 5,343 |
def listDatasets(objects = dir()):
"""
Utility function to identify currently loaded datasets.
Function should be called with default parameters,
ie as 'listDatasets()'
"""
datasetlist = []
for item in objects:
try:
if eval(item + '.' + 'has_key("DATA")') == Tru... | 5,344 |
def test_asynchronous_ops(sut: SystemUnderTest):
"""Perform asynchronous operation tests"""
# TODO(bdodd): At this time, there seems to be no async operation that
# would be implemented by many vendors and be non-invasive to test.
# Revisit in future.
pass | 5,345 |
def _(node: FromReference, ctx: AnnotateContext) -> BoxType:
"""Check that the parent node had {node.name} as a valid reference. Raises
an error if not, else copy over the set of references.
"""
t = box_type(node.over)
ft = t.row.fields.get(node.name, None)
if not isinstance(ft, RowType):
... | 5,346 |
def save_to_file(log_file):
"""
Change default output to be SaveFile()
"""
if len(log_file) is not 0:
sys.stdout = SaveFile(log_file) | 5,347 |
def invert(d: Mapping):
"""
invert a mapper's key and value
:param d:
:return:
"""
r: Dict = {}
for k, v in d.items():
r[v] = of(r[v], k) if v in r else k
return r | 5,348 |
def data_dir() -> str:
"""The directory where result data is written to"""
return '/tmp/bingads/' | 5,349 |
def intensity_weighted_dispersion(data, x0=0.0, dx=1.0, rms=None,
threshold=None, mask_path=None, axis=0):
"""
Returns the intensity weighted velocity dispersion (second moment).
"""
# Calculate the intensity weighted velocity first.
m1 = intensity_weighted_velocit... | 5,350 |
def vrtnws_api_request(service, path, params=None):
"""Sends a request to the VRTNWS API endpoint"""
url = BASE_URL_VRTNWS_API.format(service, path)
try:
res = requests.get(url, params)
try:
return res.json()
except ValueError:
return None
except requests... | 5,351 |
def test_coreapi_schema(sdk_client_fs: ADCMClient, tested_class: Type[BaseAPIObject]):
"""Test coreapi schema"""
def _get_params(link):
result = {}
for field in link.fields:
result[field.name] = True
return result
schema_obj = sdk_client_fs._api.schema
with allure.s... | 5,352 |
def augment_tensor(matrix, ndim=None):
"""
Increase the dimensionality of a tensor,
splicing it into an identity matrix of a higher
dimension. Useful for generalizing
transformation matrices.
"""
s = matrix.shape
if ndim is None:
ndim = s[0]+1
arr = N.identity(ndim)
arr[:... | 5,353 |
def ping_redis() -> bool:
"""Call ping on Redis."""
try:
return REDIS.ping()
except (redis.exceptions.ConnectionError, redis.exceptions.ResponseError):
LOGGER.warning('Redis Ping unsuccessful')
return False | 5,354 |
def test_scenario_tables_are_solved_against_outlines():
"""Outline substitution should apply to tables within a scenario"""
expected_hashes_per_step = [
# a = 1, b = 2
(
{"Parameter": "a", "Value": "1"},
{"Parameter": "b", "Value": "2"},
), # Given ...
(... | 5,355 |
def createDataset(outputPath, path,images_train, labels_train, lexiconList=None, checkValid=True):
"""
Create LMDB dataset for CRNN training.
ARGS:
outputPath : LMDB output path
imagePathList : list of image path
labelList : list of corresponding groundtruth texts
lexi... | 5,356 |
def calculate_pool_reward(height: uint32) -> uint64:
"""
Returns the pool reward at a certain block height. The pool earns 7/8 of the reward in each block. If the farmer
is solo farming, they act as the pool, and therefore earn the entire block reward.
These halving events will not be hit at the exact t... | 5,357 |
def get_argument(index, default=''):
"""
取得 shell 參數, 或使用預設值
"""
if len(sys.argv) <= index:
return default
return sys.argv[index] | 5,358 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
username = request.form.get("username").strip()
password = request.form.get("password")
# Ensure username was subm... | 5,359 |
def test_list_g_month_length_4_nistxml_sv_iv_list_g_month_length_5_2(mode, save_output, output_format):
"""
Type list/gMonth is restricted by facet length with value 10.
"""
assert_bindings(
schema="nistData/list/gMonth/Schema+Instance/NISTSchema-SV-IV-list-gMonth-length-5.xsd",
instance... | 5,360 |
def get_string_property(device_t, property):
""" Search the given device for the specified string property
@param device_t Device to search
@param property String to search for.
@return Python string containing the value, or None if not found.
"""
key = cf.CFStringCreateWithCString(
... | 5,361 |
def gamma_from_delta(
fn: Callable[..., Tensor], *, create_graph: bool = False, **params: Any
) -> Tensor:
"""Computes and returns gamma of a derivative from the formula of delta.
Note:
The keyword argument ``**params`` should contain at least one of
the following combinations:
- `... | 5,362 |
def clean_filename(string: str) -> str:
"""
清理文件名中的非法字符,防止保存到文件系统时出错
:param string:
:return:
"""
string = string.replace(':', '_').replace('/', '_').replace('\x00', '_')
string = re.sub('[\n\\\*><?\"|\t]', '', string)
return string.strip() | 5,363 |
def homework(request, id_class):
"""
View for listing the specified class' assignments
"""
cl = Classes.objects.get(pk=id_class)
assm = Assignments.objects.all().filter(a_class=cl)
return render_to_response("assignments.html", {"assignments": assm, "class": cl}, context_instance=RequestContext(r... | 5,364 |
def build_model(master_config):
"""
Imports the proper model class and builds model
"""
available_models = os.listdir("lib/classes/model_classes")
available_models = [i.replace(".py", "") for i in available_models]
model_type = master_config.Core_Config.Model_Config.model_type
model_class =... | 5,365 |
def read_video_txt(path_in,frame_per_video):
"""
read txtfile
Parameters:
---------
name : str
txtfile path
frame_per_video:int
frame per video
Returns:
---------
[index,image_path,label] as iterator
"""
num_index=0
with open(path_in) as fin:
whil... | 5,366 |
def test_extract_command_list_zsh():
"""Test the extract_command_list command with a zsh like input."""
content = """ 9597 5.1.2020 11:23 git status
9598 5.1.2020 11:23 cd .idea
9599 5.1.2020 11:23 ls
9600 5.1.2020 11:23 ..
9601 5.1.2020 11:23 rm -rf .idea
9602 5.1.2020 11:24 rm n26-csv-transac... | 5,367 |
def get_digits_from_right_to_left(number):
"""Return digits of an integer excluding the sign."""
number = abs(number)
if number < 10:
return (number, )
lst = list()
while number:
number, digit = divmod(number, 10)
lst.insert(0, digit)
return tuple(lst) | 5,368 |
def p_attr_def(p):
"""
attr_def : OBJECT_ID COLON type
| OBJECT_ID COLON type ASSIGN expr
"""
if len(p) == 4:
p[0] = ast.AttrDeclarationNode(p[1], p[3])
else:
p[0] = ast.AttrDeclarationNode(p[1], p[3], p[5]) | 5,369 |
def make_diamond(block):
"""
Return a block after rotating counterclockwise 45° to form a diamond
"""
result = []
upper = upper_triangle(block)
upper = [i.rjust(size-1) for i in upper]
upper_form = []
upper_length = len(upper)
for i in range(upper_length):
upper_form.append... | 5,370 |
def do_sitelist(parser, token):
"""
Allows a template-level call a list of all the active sites.
"""
return SitelistNode() | 5,371 |
def default_model_uk_ifriar(
data,
ep,
intervention_prior=None,
basic_R_prior=None,
r_walk_noise_scale_prior=0.15,
r_walk_period=7,
n_days_seeding=7,
seeding_scale=3.0,
infection_noise_scale=5.0,
output_noise_scale_prior=5.0,
**kwargs,
):
"""
Identical to base model, ... | 5,372 |
def events_from_file(filepath):
"""Returns all events in a single event file.
Args:
filepath: Path to the event file.
Returns:
A list of all tf.Event protos in the event file.
"""
records = list(tf_record.tf_record_iterator(filepath))
result = []
for r in records:
event = event_pb2.Event()
... | 5,373 |
def build_null_stop_time_series(feed, date_label='20010101', freq='5Min',
*, split_directions=False):
"""
Return a stop time series with the same index and hierarchical columns
as output by :func:`compute_stop_time_series_base`,
but fill it full of null values.
"""
start = date_label
end =... | 5,374 |
def yulewalk(order, F, M):
"""Recursive filter design using a least-squares method.
[B,A] = YULEWALK(N,F,M) finds the N-th order recursive filter
coefficients B and A such that the filter:
B(z) b(1) + b(2)z^-1 + .... + b(n)z^-(n-1)
---- = -------------------------------------
A(z) ... | 5,375 |
async def get_user_from_event(event):
""" Get the user from argument or replied message. """
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
user_obj = await tbot.get_entity(previous_message.sender_id)
else:
user = event.pattern_match.group(1)
if... | 5,376 |
def test_linear_chain_crf(document):
"""Linear chain CRF, with only emission and transition scores.
"""
crf_builder = SeqTagCRFBuilder(skip_chain_enabled=False)
graph = crf_builder(document)
assert len(graph) == 2
check_unary_factors(graph["unary"])
check_transition_factors(graph["transitio... | 5,377 |
def parse_contest_list(json_file):
"""Parse a list of Contests from a JSON file.
Note:
Template for Contest format in JSON in contest_template.json
"""
with open(json_file, 'r') as json_data:
data = json.load(json_data)
contests = []
for contest in data:
contest_ballot... | 5,378 |
def get_image_blob(roidb, mode):
"""Builds an input blob from the images in the roidb at the specified
scales.
"""
if mode == 'train' or mode == 'val':
with open(roidb['image'], 'rb') as f:
data = f.read()
data = np.frombuffer(data, dtype='uint8')
img = cv2.imdecode(d... | 5,379 |
def test_db_reuse(django_testdir):
"""
Test the re-use db functionality. This test requires a PostgreSQL server
to be available and the environment variables PG_HOST, PG_DB, PG_USER to
be defined.
"""
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
py.test.sk... | 5,380 |
def setTimeCallback(timefunc=None):
"""Sets a function that will return the window's global time. This
will be used by the animation timing, visualization plots, and movie-saving
functions.
Args:
timefunc (callable): returns a monotonically non-decreasing float.
If None, revert... | 5,381 |
def rx_weight_fn(edge):
"""A function for returning the weight from the common vertex."""
return float(edge["weight"]) | 5,382 |
def image_inputs(images_and_videos, data_dir, text_tmp_images):
"""Generates a list of input arguments for ffmpeg with the given images."""
include_cmd = []
# adds images as video starting on overlay time and finishing on overlay end
img_formats = ['gif', 'jpg', 'jpeg', 'png']
for ovl in images_and_videos:
... | 5,383 |
def generate_graph(data_sets: pd.DataFrame, data_source: str, data_state: str, toggle_new_case: bool, year: int) -> tuple[px.line, px.bar]:
"""Takes in the inputs and returns a graph object. The inputs are the source, data, location and year.
The graph is a prediction of the sentiment from the comments as a fun... | 5,384 |
def f_not_null(seq):
"""过滤非空值"""
seq = filter(lambda x: x not in (None, '', {}, [], ()), seq)
return seq | 5,385 |
def alignObjects(sources, target, position=True, rotation=True, rotateOrder=False, viaRotatePivot=False):
"""
Aligns list of sources to match target
If target has a different rotation order,
sources rotation order will be set to that of the target
"""
rotateOrderXYZ = pmc.getAttr(target + '.rot... | 5,386 |
def _update_settings(option):
"""Update global settings when qwebsettings changed."""
_global_settings.update_setting(option)
default_profile.setter.update_setting(option)
if private_profile:
private_profile.setter.update_setting(option) | 5,387 |
def flickr(name, args, options, content, lineno,
contentOffset, blockText, state, stateMachine):
""" Restructured text extension for inserting flickr embedded slideshows """
if len(content) == 0:
return
string_vars = {
'flickid': content[0],
'width': 400,
'height'... | 5,388 |
def serialize(key):
"""
Return serialized version of key name
"""
s = current_app.config['SERIALIZER']
return s.dumps(key) | 5,389 |
def init_db():
"""
init_db()
Initializes the database.
If tables "books" and "authors" are already in the database, do nothing.
Return value: None or raises ValueError
The error value is the QtSql error instance.
"""
def check(func, *args):
if not func(*args):
raise V... | 5,390 |
def draw_cross(bgr_img, (x, y), color=(255, 255, 255), width=2, thickness=1):
""" Draws an "x"-shaped cross at (x,y)
"""
x, y, w = int(x), int(y), int(width / 2) # ensure points are ints for cv2 methods
cv2.line(bgr_img, (x - w , y - w), (x + w , y + w), color, thickness)
cv2.line(bg... | 5,391 |
def calc_disordered_regions(limits, seq):
"""
Returns the sequence of disordered regions given a string of
starts and ends of the regions and the sequence.
Example
-------
limits = 1_5;8_10
seq = AHSEDQNAAANTH...
This will return `AHSED_AAA`
"""
seq = seq.replace(' ', '... | 5,392 |
def live_chart_edicts(edicts):
"""
plot all orders in edicts; a list of dicts
op key of each dict is "buy" or "sell"
"""
now = int(time.time())
for edict in edicts:
print("edict", edict)
if edict["op"] == "buy":
plt.plot(now, edict["price"], color="lime", marker="^", ... | 5,393 |
def find_repos():
"""
Finds all repos matching the search criteria for a number of different package manager.
Note that this queues up 1000s of search queries which can take days to work through. This query should only be run periodically to capture newly
created projects.
:return:
"""
logg... | 5,394 |
def person_attribute_string_factory(sqla):
"""Create a fake person attribute that is enumerated."""
create_multiple_attributes(sqla, 5, 1)
people = sqla.query(Person).all()
if not people:
create_multiple_people(sqla, random.randint(3, 6))
people = sqla.query(Person).all()
current_per... | 5,395 |
def forward_pass(log_a, log_b, logprob_s0):
"""Computing the forward pass of Baum-Welch Algorithm.
By employing log-exp-sum trick, values are computed in log space, including
the output. Notation is adopted from https://arxiv.org/abs/1910.09588.
`log_a` is the likelihood of discrete states, `log p(s[t] | s[t-1... | 5,396 |
def TonnetzToString(Tonnetz):
"""TonnetzToString: List -> String."""
TonnetzString = getKeyByValue(dictOfTonnetze, Tonnetz)
return TonnetzString | 5,397 |
def get_mc_calibration_coeffs(tel_id):
"""
Get the calibration coefficients from the MC data file to the
data. This is ahack (until we have a real data structure for the
calibrated data), it should move into `ctapipe.io.hessio_event_source`.
returns
-------
(peds,gains) : arrays of the ped... | 5,398 |
def bryc(K):
"""
基于2002年Bryc提出的一致逼近函数近似累积正态分布函数
绝对误差小于1.9e-5
:param X: 负无穷到正无穷取值
:return: 累积正态分布积分值的近似
"""
X = abs(K)
from math import exp, pi, sqrt
cnd = 1.-(X*X + 5.575192*X + 12.77436324) * exp(-X*X/2.)/(sqrt(2.*pi)*pow(X, 3) + 14.38718147*pow(X, 2) + 31.53531977*X + 2*12.77436324... | 5,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.