content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def map2central(cell, coordinates, pbc):
"""Map atoms outside the unit cell into the cell using PBC.
Arguments:
cell (:class:`torch.Tensor`): tensor of shape (3, 3) of the three
vectors defining unit cell:
.. code-block:: python
tensor([[x1, y1, ... | 5ab75804efa182516ec4e99ec6707e65f205b842 | 698,553 |
def get_left_strip(chonk):
"""
Compute the left vertical strip of a 2D list.
"""
return [chonk[_i][0] for _i in range(len(chonk))] | dfc57a0776e5ab97a808a75170634fa6a072d9d3 | 698,554 |
def _shift_num_right_by(num: int, digits: int) -> int:
"""Shift a number to the right by discarding some digits
We actually use string conversion here since division can provide
wrong results due to precision errors for very big numbers. e.g.:
6150000000000000000000000000000000000000000000000 // 1e27
... | ba459cb419ef19ac2884d8299d4f1a9213832fa3 | 698,556 |
def handle_extends(tail, line_index):
"""Handles an extends line in a snippet."""
if tail:
return 'extends', ([p.strip() for p in tail.split(',')],)
else:
return 'error', ("'extends' without file types", line_index) | 3b20cc5719d123e36db954c5ffc4537df64f268a | 698,560 |
import torch
def repackage_hidden(h):
"""Wraps hidden states in new Tensors,
to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h) | b435d7537e4418d3877db55077285d35a24e46b3 | 698,563 |
def minus(evaluator, ast, state):
"""Evaluates "-expr"."""
return -evaluator.eval_ast(ast["expr"], state) | bf945c368e84d3badd7a90bfce74cb3c89b6890a | 698,564 |
def angle_M(M_r: float, n: float, t_r: float, t: float) -> float:
"""
M = Mr + n * (t - tr)
:param M_r: mean anomaly at tr
:type M_r: float
:param n: mean movement
:type n: float
:param t_r: reference time
:type t_r: float
:param t: time
:type t: float
:return: mean anomaly ... | c99e5dacffea44fa7fadfaebaf6ce734eea81e16 | 698,565 |
import re
def is_transaction_expired_exception(e):
"""
Checks if exception occurred for an expired transaction
:type e: :py:class:`botocore.exceptions.ClientError`
:param e: The ClientError caught.
:rtype: bool
:return: True if the exception denote that a transaction has expired. False other... | c836521a7137b61ad8443157824ca5da59de65e3 | 698,567 |
def parse_int(sin):
"""A version of int but fail-safe"""
return int(sin) if sin.isdigit() else -99 | 204cbcb01b6df1bbdd09af318fdfe90feb5fe68f | 698,570 |
def check_read(read):
"""
a callback function for pysam.count function, returns true if the read should be included in the count
:param read: the read to check
:return: True of False whether the read should be included in the count
"""
return read.is_proper_pair | 1bc80c9156bdeb0bc34b2724da8d0147a435b3dd | 698,571 |
def createAggregatedTestCase(doc, parent_node, testclass_name):
"""
Create a node which represents a single aggregated testcase.
Aggregated testcase sums the result of all test cases that
belong to the speified classname. If one of these test cases
fails, the aggregated test case's status is set to ... | a6cfaa405464a09e76d3e4840f99a3d5ff9a87b1 | 698,572 |
def enable_cdc(client):
"""Utility method to enable Change Data Capture for Contact change events in an org.
Args:
client (:py:class:`simple_salesforce.Salesforce`): Salesforce client
Returns:
(:obj:`str`) Event channel Id
"""
payload = {
"FullName": "ChangeEvents_ContactCh... | 2c7bc57f33e83029caea542db9daeaa81f6661cc | 698,579 |
import yaml
def load_config_from_yaml(filename='fsm.yaml'):
"""
Returns the current fsm configuration dictionary, loaded from file.
:return: a dict.
"""
yaml_file = open(filename, 'r')
yaml_dict = yaml.safe_load(yaml_file.read())
return yaml_dict | e1ff03a8fcc2a77288d8971cd76fd17e7a30f65a | 698,584 |
import torch
def atanh(x, eps=1e-2):
"""
The inverse hyperbolic tangent function, missing in pytorch.
:param x: a tensor or a Variable
:param eps: used to enhance numeric stability
:return: :math:`\\tanh^{-1}{x}`, of the same type as ``x``
"""
x = x * (1 - eps)
return 0.5 * torch.log(... | 27b0e8de0eeceb44d739f686ca22d616bc8f75de | 698,585 |
def index_names_from_symbol(symbol):
"""
Return the domain names of a GAMS symbol,
except ['*'] cases are replaced by the name of the symbol
and ['*',..,'*'] cases are replaced with ['index_0',..'index_n']
"""
index_names = list(symbol.domains_as_strings)
if index_names == ["*"]:
return [symbol.name]
... | dc4acc473eaf13d18f553abd722384bf4fe3115a | 698,586 |
from pathlib import Path
import json
def read_description(filename):
"""Read the description from .zenodo.json file."""
with Path(filename).open() as file:
info = json.load(file)
return info['description'] | 0568aa956f3b0c3f5be4ba75ea8e6b98e08c469e | 698,588 |
import importlib
def get_func(func_name):
"""Helper to return a function object by name. func_name must identify a
function in this module or the path to a function relative to the base
'modeling' module.
"""
if func_name == '':
return None
try:
parts = func_name.split('.')
... | da95b0933ce60cd55049c13ef198eba4d9d0b0ee | 698,600 |
def MTFfreq(MTFpos, MTF, modulation=0.2):
""" Return the frequency for the requested modulation height. """
mtf_freq = 0
for f in range(len(MTFpos)):
if MTF[f] < modulation:
if f > 0:
# Linear interpolation:
x0 = MTFpos[f-1]
x1 = MTFpos[f]... | fadec075afaffa405ef4135f714be6e2bceb71c7 | 698,603 |
def allStudentsMajoringIn(thisMajor,listOfStudents):
"""
return a list of the students with the major, thisMajor
>>> majorToLNames("MATH",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")])
[Student(fName='MARY',lName='KAY',major="MATH")]
>>>
""... | ad32dfd68b2daa4aa3e46ff8563e4575bd940336 | 698,606 |
def bounding_box(ptlist):
"""
Returns the bounding box for the list of points, in the form
(x1, y1, x2, y2), where (x1, y1) is the top left of the box and
(x2, y2) is the bottom right of the box.
"""
xs = [pt[0] for pt in ptlist]
ys = [pt[1] for pt in ptlist]
return (min(xs), max(ys), ma... | cd27b3e5783ee7dd8c5960389079b32768516e4d | 698,611 |
def is_good(filename: str, force: bool = False) -> bool:
"""
Verify whether a file is good or not, i.e., it does not need
any shape or illumination modification. By default a file is
good if it is a pdf.
Parameters
----------
filename
The file name.
force
Wether to forc... | acaee589288db3eb48bd7bc89dc21c0a7d75822c | 698,613 |
import re
def all_whitespace(string):
""" all_whitespace(string : str) -> bool
>>> all_whitespace(' ')
True
Returns True if a string has only whitespace.
"""
return re.search('^[ \t]*(\r|\n|$)', string) | 766b92da0b6e91fbcd05eed408cb5651cdf42b4e | 698,622 |
import copy
import uuid
import collections
def deep_copy(item_original):
"""Return a recursive deep-copy of item where each copy has a new ID."""
item = copy.copy(item_original)
item._id = uuid.uuid4().hex
if hasattr(item, '_children') and len(item._children) > 0:
children_new = collections.Or... | 83c8ee5dd620e30a518391752905ba1966d27aa4 | 698,623 |
def string_empty(string):
"""Return True if the input string is None or whitespace."""
return (string is None) or not (string and string.strip()) | fddb1e639a57b29674ce6d0a101e875272731d77 | 698,628 |
import imghdr
def detect_image_type(filename):
"""
获取图像文件类型
:param filename:
:return: jpge|png|gif|tiff等。失败返回None
"""
return imghdr.what(filename) | a4701aa60927e730899ed8036d6f2d875aa0524a | 698,631 |
from typing import Dict
def _results_data_row(row: Dict[str, str]):
"""
Transform the keys of each CSV row. If the CSV headers change,
this will make a single place to fix it.
"""
return {
"k": row["Key"],
"v": row["Content"],
} | 97dc7f9842d7e6a564cbe66fd93e3dbaeca08517 | 698,635 |
from typing import List
def _split_inputs(inputs: str, named_groups: dict) -> List[str]:
"""
Identify and split inputs for torch operations.
This assumes that no quotes, apostrophes, or braces show up in the operation string.
Currently, items in lists that are not within functions will be broken up in... | 5edc3c53fb9b7a19557504335eb04eb15dd3c932 | 698,639 |
def jsdate(d):
"""formats a python date into a js Date() constructor.
"""
try:
return "new Date({0},{1},{2})".format(d.year, d.month - 1, d.day)
except AttributeError:
return 'undefined' | 0c8331f928cf26e4cac7663dd6619c62cfff0fae | 698,644 |
import random
def mutate(chromosome):
"""
Pick a random bit to mutate by XOR and shifting the selected bit. This
ensures diversity in the population.
"""
altered_bit_position = random.randint(0, 31)
mutation = chromosome ^ (1 << altered_bit_position)
return mutation | ff93fb19d7d83c558172d005fbd140284e2b16c2 | 698,646 |
def mileage_format(value):
""" Custom formatting for mileage. """
return "{:,} miles".format(value) | 056f5fbf5d291ac892bd8f2c16cda16937f758da | 698,648 |
def _list(key: str, vals: dict) -> list:
"""Get a key from a dictionary of values and ensure it is a list."""
result = vals.get(key, [])
if not isinstance(result, list):
result = [result]
return result | cf8a5da580dc4d95f83f18a92f82f646be5c4cb3 | 698,649 |
def contrast_color(hex_color):
"""
Util function to know if it's best to use a white or a black color on the foreground given in parameter
:param str hex_color: the foreground color to analyse
:return: A black or a white color
"""
r1 = int(hex_color[1:3], 16)
g1 = int(hex_color[3:5], 16)
... | 470f713af48673d7b9fb8aa3bb30f7e1498da9b5 | 698,651 |
import itertools
def get_common_base(files):
"""Find the common parent base path for a list of files.
For example, ``["/usr/src/app", "/usr/src/tests", "/usr/src/app2"]``
would return ``"/usr/src"``.
:param files: files to scan.
:type files: ``iterable``
:return: Common parent path.
:rty... | bb6c7fde6a9e2f9c620febf52047b547cf24e602 | 698,655 |
def comment(src_line: str) -> list:
"""Returns an empty list."""
return [] | c7e584811b899ae4a17ba4c9fd0debbc97e0a5cc | 698,657 |
def hidden_loc(obj, name):
"""
Generate the location of a hidden attribute.
Importantly deals with attributes beginning with an underscore.
"""
return ("_" + obj.__class__.__name__ + "__" + name).replace("___", "__") | 5a8c3d066cb96cf282c1b8814ac1302bd68111c0 | 698,660 |
def find_neighbors_hexagonal_grid(map_coordinates: list, current_position: tuple) -> list:
"""Finds the set of adjacent positions of coordinates 'current_position' in a hexagonal grid.
Args:
map_coordinates (list): List of map coordinates.
current_position (tuple): Current position of the hexag... | 2a6071d59a69b828eb252504508fa3f706969e1b | 698,662 |
from pathlib import Path
def openW2wFile(path, mode):
"""
Helper function to read/write all files with same encoding and line endings
:param str|Path path: full path to file
:param str mode: open mode: 'r' - read, 'w' - write, 'a' - append
:return TextIO:
"""
if isinstance(path, Path):
... | 6e42a26d2262ed10d15e19292e7b32fffd14aeb8 | 698,663 |
def ugly_numbers(n: int) -> int:
"""
Returns the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(0)
1
>>> ugly_numbers(20)
36
>>> ugly_numbers(-5)
1
>>> ugly_numbers(-5.5)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be ... | 69c92c8eea98b6d8d869f0725c49d6b164d24480 | 698,664 |
from typing import Iterable
def make_conda_description(summary: str, conda_channels: Iterable[str] = ()) -> str:
"""
Create a description for the Conda package from its summary and a list of channels required to install it.
The description will look like::
This is my fancy Conda package. Hope you like it 😉.
... | b275e3bfcb67da33a4c7a34d7801a0cb4144527a | 698,665 |
import hashlib
def sha1(text):
"""
Calculate the SHA1 fingerprint of text.
:param text: The text to fingerprint (a string).
:returns: The fingerprint of the text (a string).
"""
context = hashlib.sha1()
context.update(text.encode('utf-8'))
return context.hexdigest() | 43473e9cc22b6cbe072170244b56b831f0cc88ee | 698,666 |
def ifirst_is_not(l, v):
"""
Return index of first item in list which is not the specified value.
If the list is empty or if all items are the specified value, raise
a ValueError exception.
Parameters
----------
l : sequence
The list of elements to be inspected.
v : object
... | fef5ae1a512772cf4df75a294057330280047f88 | 698,668 |
def format_date_ihme(date_in):
"""
Formats "m/d/yyy" to "yyyymmdd"
"""
try:
month, day, year = date_in.split('/')
return '%s%02i%02i' % (year, int(month), int(day))
except:
return date_in.replace('-', '') | 166739b2245833c6dddf35fcde87433648697277 | 698,670 |
def reverse_map(dict_of_sets):
"""Reverse a map of one-to-many.
So the map::
{
'A': {'B', 'C'},
'B': {'C'},
}
becomes
{
'B': {'A'},
'C': {'A', 'B'},
}
Args:
dict_of_sets (dict[set]): A dictionary of sets, mapping
one value ... | 87b0679a0ebd00c3dbdcafc89fd2644b21ecbc85 | 698,671 |
import functools
def expand_args(function):
"""Expand arguments passed inside the CallContext object.
Converts internal method signature 'method(ctx)' to whatever
is appropriate to the client code.
Args:
function: Async function expecting CallContext as a last argument.
Returns:
A... | 72e7de46684b2c02d958fad7f9ded71e653bb811 | 698,674 |
def derivative_of_binary_cross_entropy_loss_function(y_predicted, y_true):
"""
Use the derivative of the binary cross entropy (BCE) loss function.
Parameters
----------
y_predicted : ndarray
The predicted output of the model.
y_true : ndarray
The actual output value.
Return... | 7803c852f794ab9eae165c639bfb7a04cd0c1028 | 698,675 |
def api_failed(response, endpoint, exit_on_error=True):
"""
Check if api request failed
Can raise exception
"""
if 200 <= response.status_code < 300:
return False
if exit_on_error:
raise Exception("Status code {0} calling {1}".format(
response.status_code, endpoint... | 6a9d803444c4be09806eb6c5b588e1e04062c431 | 698,680 |
def select_field(X, cols=None, single_dimension=False):
"""
Select columns from a pandas DataFrame
Args:
X (pandas DataFrame): input data
cols (array-like): list of columns to select
single_dimension (bool): reduce data to
one dimension if only one column
i... | 4f80af3621af5e0c622f2c880e88d95a6e93034e | 698,681 |
def get_pathless_file_size(data_file):
"""
Takes an open file-like object, gets its end location (in bytes),
and returns it as a measure of the file size.
Traditionally, one would use a systems-call to get the size
of a file (using the `os` module). But `TemporaryFileWrapper`s
do not feature a ... | df1edfa6cb7b97c6abbdb2252b7dd8d505931768 | 698,682 |
from functools import reduce
import operator
def factorial(n):
"""Calculate n factorial"""
return reduce(operator.mul, range(2, n+1), 1) | a58e0aad4e3a8baf06bbd1a6929a3aab2ab4e66e | 698,685 |
from typing import Optional
from typing import Tuple
from typing import Match
import re
def is_conversion_err(error: Exception) -> Optional[Tuple[str, int]]:
"""Check if error is caused by generic conversion error.
Return a tuple of the converter type and parameter name if True,
otherwise return None.
... | 2e53420bb8a5715c75ee30a549453f40202d4ff7 | 698,687 |
def txt_file_to_list(genomes_txt):
"""
Read ids from a one column file to a list
Args:
genomes_txt:str: Path to file with the ids.
"""
with open(genomes_txt, 'r') as fin:
genomes_list = [line.strip() for line in fin]
return genomes_list | f79874dfbcb6a2a71be87b180e80513d480fcc8e | 698,688 |
def dense_rank(x, na_option = "keep"):
"""Return the dense rank.
This method of ranking returns values ranging from 1 to the number of unique entries.
Ties are all given the same ranking.
Example:
>>> dense_rank(pd.Series([1,3,3,5]))
0 1.0
1 2.0
2 2.0
... | 53bd64e112741f20c0e62f44ba7f5bcf8cdb2f83 | 698,692 |
from unittest.mock import Mock
def mock_channel_file(
offered_by, channel_id, playlist_id, create_user_list=False, user_list_title=None
):
"""Mock video channel github file"""
content = f"""---
offered_by: {offered_by}
channel_id: {channel_id}
playlists:
- id: {playlist_id}
{"create_user_list: true... | 3042a7fc6f0fb622db8bf035a408672ddd6408ab | 698,695 |
from functools import wraps
def run_only_once(resolve_func):
"""
Make sure middleware is run only once,
this is done by setting a flag in the `context` of `ResolverInfo`
Example:
class AuthenticationMiddleware:
@run_only_once
def resolve(self, next, root, info, *args, *... | 9742318ca44ec92d7826d561968c87cea62db1bf | 698,696 |
import re
def get_input_size(filename):
"""Gets input size and # of channels."""
with open(filename) as input_file:
for line in input_file:
match = re.match(r'^input.*\(None, (\d*), (\d*), (\d*)\)', line)
if match is not None:
x = int(match.group(1))
... | 3e753e5ac74babcbe4f48830cfde7a3002f7cc37 | 698,698 |
def indexOfSmallestInt(listOfInts):
"""
return index of smallest element of non-empty list of ints, or False otherwise
That is, return False if parameter is an empty list, or not a list
parameter is not a list consisting only of ints
By "smallest", we mean a value that is no larger than any other
... | 63afb453b13ad4da75c83e9a7f6b409f58739d7e | 698,700 |
def field_with_classes(field, *classes):
"""
Adds the specified classes to the HTML element produced for the field.
"""
return field.as_widget(attrs = { 'class': ' '.join(classes) }) | 2b9929b2629fafaafbe1d2537afc0a9a601eed53 | 698,701 |
import tkinter as Tkinter
import tkinter.filedialog as tkFileDialog
def directory_from_gui(
initialdir='.',
title='Choose directory'): # pragma: no cover
"""
Opens dialog to one select directory
Parameters
----------
initialdir : str, optional
Initial directory, in which ... | e0b43a044c0e05815023de2275cc0ff1ffb01d8e | 698,702 |
def create_model_name(src):
"""Generate a name for a source object given its spatial/spectral
properties.
Parameters
----------
src : `~fermipy.roi_model.Source`
A source object.
Returns
-------
name : str
A source name.
"""
o = ''
spatial_type = src['S... | d305dd26bc6017f3fce5db2a5267fa6e74df3bc6 | 698,705 |
def csv_to_list(value):
"""
Converts the given value to a list of strings, spliting by ',' and removing empty strings.
:param str value: the value to split to strings.
:return: a list of strings.
:rtype: List[str]
"""
return list(filter(None, [x.strip() for x in value.split(',')])) | dbfb90dccf8d48a46f528ca02e958306e8dcc266 | 698,707 |
def swapaxes(dat, ax1, ax2):
"""Swap axes of a Data object.
This method swaps two axes of a Data object by swapping the
appropriate ``.data``, ``.names``, ``.units``, and ``.axes``.
Parameters
----------
dat : Data
ax1, ax2 : int
the indices of the axes to swap
Returns
---... | 576ec10826c3ab92465052edcadf38cf04952c02 | 698,714 |
import re
def is_url(value):
"""Return whether or not given value is a valid URL."""
regex = re.compile(
r"^"
# startchar <
r"<?"
# protocol identifier
r"(?:(?:https?|ftp)://)"
r"(?:"
r"(localhost)"
r"|"
# host name
r"(?:(?:[a-z\... | 3a50e541a9e62156a89693d15d248080abb3718f | 698,716 |
def remote_call(method):
"""Decorator to set a method as callable remotely (remote call)."""
method.remote_call = True
return method | ab276cbdb190185c7e46c5205df25f022a56a097 | 698,719 |
from pathlib import Path
def node(ph5, path, class_name):
"""
Get the node handle of a given path and class name
:param ph5: an open ph5 object
:type ph5: ph5 object
:param path: path to node
:type path: string
:param class_name: name of class to get
:type class_name: st... | 2a8090952fdec3dda7490844990f41c8e154c3af | 698,721 |
def txfDate(date):
"""Returns a date string in the TXF format, which is MM/DD/YYYY."""
return date.strftime('%m/%d/%Y') | fd1f19b4080447379ec3ec57be0f2af047099673 | 698,726 |
from typing import Union
def get_json_url(year: Union[str, int], kind: str = "photos") -> str:
"""Returns url for the json data from news-navigator for given `year` and `kind`"""
return f"https://news-navigator.labs.loc.gov/prepackaged/{year}_{kind}.json" | 0c7650f667cb1fceebbd73e7a6eaf00145061d38 | 698,729 |
def vdecomp(v, m=None, minlen=None, maxlen=None):
"""
Decompose a vector into components. an nD stack of m-element vectors will return a tuple with up to m elements,
each of which will be an nD stack of scalars
:param v: nD stack of m-element vectors, a numpy (n+1)D array with shape
(n_stack0,n... | cbc846be6a07082711e5c9faa191181c8cdc75f8 | 698,736 |
def get_max_table_size(final_tables):
"""
Compute the maximum number of elements that appear in one of the table generated inside the main process.
Parameters
----------
final_tables : list
list of the tables generated inside the loop for each bucket.
Returns:
--------
... | a562d6f944a03785034028e8b2e83bdb19a8d9aa | 698,740 |
import itertools
def next_bigger(n: int) -> int:
"""
A function that takes a positive integer number
and returns the next bigger number formed by the same digits.
If no bigger number can be composed using those digits, return -1
"""
numbers = sorted(set(sorted(int(''.join(i)) for i in iterto... | 8800040f3e88054bcacdb432131f8a9e0a872277 | 698,741 |
def get_mac_addr_from_datapath(datapath):
"""
Return the MAC address from the datapath ID.
According to OpenFlow switch specification, the lower 48 bits of the datapath
ID contains the MAC address.
"""
mac_addr_int = datapath.id & 0x0000ffffffffffff
mac_addr = format(mac_addr_int, '02x')
return... | 539c0b0a92f3eead947aed65ed62a1e630dcb30f | 698,745 |
def create_empty(val=0x00):
"""Create an empty Userdata object.
val: value to fill the empty user data fields with (default is 0x00)
"""
user_data_dict = {}
for index in range(1, 15):
key = "d{}".format(index)
user_data_dict.update({key: val})
return user_data_dict | 55e614059940b7eda5a0684dd105a60dbc7f1549 | 698,746 |
import re
def remove_tags(text):
"""
remove html style tags from some text
"""
cleaned = re.sub('<[^>]+>', '', text)
return re.sub('\s+',' ', cleaned).strip() | 5bbce34ca179f871eca6306f7fbe50b5cc1ee893 | 698,747 |
def get_note_type(syllables, song_db) -> list:
"""
Function to determine the category of the syllable
Parameters
----------
syllables : str
song_db : db
Returns
-------
type_str : list
"""
type_str = []
for syllable in syllables:
if syllable in song_db.motif:
... | 621448603581a56af22ec9c559f9854c62073318 | 698,749 |
def get_plain_text(values, strip=True):
"""Get the first value in a list of values that we expect to be plain-text.
If it is a dict, then return the value of "value".
:param list values: a list of values
:param boolean strip: true if we should strip the plaintext value
:return: a string or None
... | 3c0937d1faefda4ba8649005e29c9961afbadc0a | 698,751 |
def validate_request(request):
"""
Make sure the request is from Twilio and is valid.
Ref: https://www.twilio.com/docs/security#validating-requests
"""
# Forgot where this token if from. Different from above.
# From: https://www.twilio.com/user/account/developer-tools/test-credentials
# Sho... | a83f3065fcebcb8231be4ed5558743fa6d837754 | 698,754 |
def mathprod(seq): # math.prod function is available at python 3.8
"""
returns product of sequence elements
"""
v = seq[0]
for s in seq[1:]:
v *= s
return v | b75ff229e4cfaabe42e542367dd27e257f1d33ec | 698,755 |
from typing import List
from typing import Any
def _split_list_into_chunks(x: List[Any], chunk_size: int = 50) -> List[List[Any]]:
"""Helper function that splits a list into chunks."""
chunks = [x[i:i + chunk_size] for i in range(0, len(x), chunk_size)]
return chunks | b9972b57a18a97fceec78ec1d55156c83d255f9f | 698,756 |
import math
def fix(x):
"""
From http://www.mathworks.com/help/matlab/ref/fix.html
fix
Round toward zero
Syntax:
B = fix(A)
Description:
B = fix(A) rounds the elements of A toward zero,
resulting in an array of integers.
For complex A, the im... | d57d4dd7088b2191e63fff16d0000508275f8a09 | 698,758 |
def create_demand_callback(data):
"""Creates callback to get demands at each location."""
def demand_callback(from_node, to_node):
return data["demands"][from_node]
return demand_callback | ceff0d3caaa1e1269fee18e8aa4684afaa7a5e81 | 698,763 |
def _get_unique_index_values(idf, index_col, assert_all_same=True):
"""
Get unique values in index column from a dataframe
Parameters
----------
idf : :obj:`pd.DataFrame`
Dataframe to get index values from
index_col : str
Column in index to get the values for
assert_all_sa... | 306a919a547a6d0056a4547daa50e6149d840910 | 698,766 |
def str_to_bytes(s):
"""convert string to byte unit. Case insensitive.
>>> str_to_bytes('2GB')
2147483648
>>> str_to_bytes('1kb')
1024
"""
s = s.replace(' ', '')
if s[-1].isalpha() and s[-2].isalpha():
_unit = s[-2:].upper()
_num = s[:-2]
elif s[-1].isalpha():
_unit = s[-1].upper()
... | 71bef1d7a81fad44a00deb268fba83dac1ed633e | 698,779 |
def select_first_node(g):
"""
:param g: the graph
:return: the first node of the node sequence based on which the graph will be partitioned. We select the first node
as the node which has the lowest degree
"""
all_degrees = []
node_list = list(range(0, len(g)))
for node in node_list:
... | 769a36437e38b19984f88f510b544c22df984106 | 698,780 |
def _flatten(coll):
""" Flatten list and convert elements to int
"""
if isinstance(coll, list):
return [int(a) for i in coll for a in _flatten(i)]
else:
return [coll] | a6f1dee42a5c881e4cf4496283f248a230f38465 | 698,784 |
def to_float_hours(hours, minutes, seconds):
""" (int, int, int) -> float
Return the total number of hours in the specified number
of hours, minutes, and seconds.
Precondition: 0 <= minutes < 60 and 0 <= seconds < 60
>>> to_float_hours(0, 15, 0)
0.25
>>> to_float_hours(2, 45, 9)
2.7... | f94f37585929fc45f4b417ab63ca9b7b501a2e57 | 698,786 |
import difflib
def _get_suggestion(provided_string, allowed_strings):
"""
Given a string and a list of allowed_strings, it returns a string to print
on screen, with sensible text depending on whether no suggestion is found,
or one or more than one suggestions are found.
:param provided_string: th... | ebd1b963116bddebbc340312f2d7a16be36b11c6 | 698,789 |
def iso_8601(datetime):
"""Convert a datetime into an iso 8601 string."""
if datetime is None:
return datetime
value = datetime.isoformat()
if value.endswith('+00:00'):
value = value[:-6] + 'Z'
return value | 968b9d9edfe13340e4c2f74fb78c11cb38d6c013 | 698,790 |
def get_request_url(url, *args, **kwargs):
"""Returns url parameter that request will use"""
return url | fde43b531d53e0f3cf80655b0da9895b7a001e13 | 698,794 |
def square_table_while(n):
"""
Returns: list of squares less than (or equal to) N
This function creates a list of integer squares 1*1, 2*2, ...
It only adds those squares that are less than or equal to N.
Parameter n: the bound on the squares
Precondition: n >= 0 is a number
"""
... | 8eb94d9690f4138fb6759cf73d5a602659571b34 | 698,796 |
def populate_words(words, oxford_api, words_api=None, allow_messages=True):
"""
Iterates the words dictionary, populating the data of each object using the OxfordAPI and with the optional
WordsAPI to be used in the case the word is not found in the Oxford dictionary.
:param words: The dictionary contain... | 6f435b2e8d9947a9e7c6ba558aa43e13fe0dcfd6 | 698,798 |
def poly(a, x, y, order=4):
"""Polynomial evaluation.
pol = a[i,j] * x**(i-j) * y**j summed over i and j, where i runs from 0 to order.
Then for each value of i, j runs from 0 to i.
For many of the polynomial operations the coefficients A[i,j] are contained in an
array of dimension (order+1, order+... | e5575d4df2ae4cc5f7f1eea467d9b04ebbb97942 | 698,804 |
import struct
def short_to_bytes(short_data):
"""
For a 16 bit signed short in little endian
:param short_data:
:return: bytes(); len == 2
"""
result = struct.pack('<h', short_data)
return result | 26eeb2de936fa6b434c724ef80c008d93aec0446 | 698,806 |
def find_components(value):
""" Extract the three values which have been combined to
form the given output.
"""
r1 = value >> 20 # 11 most significant bits
r2 = (2**10 - 1) & (value >> 10) # 10 middle bits
r3 = (2**10 - 1) & value # 10 least significant bits
return... | 80a235cafe8ceb37cafb6453f3338e03653bffe1 | 698,811 |
def GetInvalidTypeErrors(type_names, metrics):
"""Check that all of the metrics have valid types.
Args:
type_names: The set of valid type names.
metrics: A list of rappor metric description objects.
Returns:
A list of errors about metrics with invalid_types.
"""
invalid_types = [m for m in metri... | 27af3804cb4a857d044ad365cdfee090a0d1ab56 | 698,813 |
import textwrap
def indent(multiline_str: str, indented=4):
"""
Converts a multiline string to an indented string
Args:
multiline_str: string to be converted
indented: number of space used for indentation
Returns: Indented string
"""
return textwrap.indent(multiline_str, " " ... | 9fd5f2310ade00071a57731040435428cff88557 | 698,815 |
def list_pattern_features(client, patter_name, type_=None, file_=None):
"""List features in a Creo Pattern.
Args:
client (obj):
creopyson Client.
patter_name (str):
Pattern name.
`type_` (str, optional):
Feature type patter (wildcards allowed: True).
... | d1923ccdb178a211ecd896c325170a5e247557aa | 698,816 |
def get_answer(offer, user):
"""Returns an user answer for the given offer"""
if not user.is_authenticated:
return None
return offer.answers.filter(user=user).first() | e89da7d11e6e8a01deb8177d3af9c693267fe09a | 698,820 |
def process_dsn(dsn):
"""
Take a standard DSN-dict and return the args and
kwargs that will be passed to the psycopg2 Connection
constructor.
"""
args = ['host=%s dbname=%s user=%s password=%s' % (dsn['host'], dsn['db'], dsn['user'], dsn['passwd'])]
del dsn['host']
del dsn['db']
del dsn['user']
del dsn['passw... | c73b641cd4e28c5824db6d37d3aec2786c7461ff | 698,826 |
def moftype(cimtype, refclass):
"""Converts a CIM type name to MOF syntax."""
if cimtype == 'reference':
_moftype = refclass + " REF"
else:
_moftype = cimtype
return _moftype | c09697b9a1fabea1f1529de8ab7ee7eeed4da846 | 698,834 |
def handle_status_update(loan_id, new_status):
"""Handles a status update for an order."""
# lookup order in your system using loan_id
# set order status to new_status
return '' | d75f6c145346d7fe9c6fd124dc0590fd66b64da6 | 698,836 |
import json
def translate_header(df, dictionary, dictionary_type='inline'):
"""change the headers of a dataframe base on a mapping dictionary.
Parameters
----------
df : `DataFrame`
The dataframe to be translated
dictionary_type : `str`, default to `inline`
The type of dictionary,... | 371443bc112fa2b0892bbcf945e3089aab995122 | 698,839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.