content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extract_insn_cross_section_cflow(f, bb, insn):
""" inspect the instruction for a CALL or JMP that crosses section boundaries
args:
f (IDA func_t)
bb (IDA BasicBlock)
insn (IDA insn_t)
"""
for ref in idautils.CodeRefsFrom(insn.ea, False):
if ref in get... | 56,800 |
def create():
"""
Create a new DeviceModel.
Request:
{
'dm_name': 'Foo',
'df_list': [
{
'df_id': 12, // required
'df_parameter': [{}, ...] // required
'tags': [], // optional
},
... | 56,801 |
def resize_image(img, min_side=800, max_side=1333):
"""
Resize an image such that the size is constrained to min_side and max_side.
Args
min_side: The image's min side will be equal to min_side after resizing.
max_side: If after resizing the image's max side is above max_side, resize ... | 56,802 |
def filterInvalidLociSaveNewBed(beds, chrsizefnames, outbednames):
"""filter out loci within FS bp to breakpoints"""
chrsizes = loadchrsize(chrsizefnames)
for hap in [0,1]:
for rind, row in enumerate(beds[hap]):
cs = chrsizes[hap][row[0]]
if row[1] < FS or row[2]+FS > cs:
... | 56,803 |
def unlock(caller_id, node_id_list):
"""
Unlocks specified Node. After unlock Node's state is @val{ok} and Users
are able to run VMs on that Node.
@cmview_admin_cm
@param_post{node_id_list,int} list of the specified Nodes ids
@response{None}
@raises{node_unlock,CMException}
"""
f... | 56,804 |
def increase_by_1_list_comp(dummy_list):
"""
Increase the value by 1 using list comprehension
Return
------
A new list containing the new values
Parameters
----------
dummy_list: A list containing integers
"""
return [x+1 for x in dummy_list] | 56,805 |
def registered_root():
"""Return currently registered root"""
return _registered_root["_"] | 56,806 |
def _is_conn_refused_exception(exceptionobj):
"""
<Purpose>
Determines if a given error number indicates that the remote
host has actively refused the connection. E.g.
ECONNREFUSED
<Arguments>
An exception object from a network call.
<Returns>
True if the error indicates the connection was... | 56,807 |
def _load_Xy(zipfile, csvfile, sep=',', header=None, engine='python',
na_values={'?'}, **kwargs):
"""Load a zippend csv file with targets in the last column and features in
the rest."""
with ZipFile(zipfile) as z:
with z.open(csvfile) as c:
s = io.StringIO(c.read().decode... | 56,808 |
def pairwise(iterable):
"""
s -> (s0,s1), (s1,s2), (s2, s3), ...
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b) | 56,809 |
def edit_last_msg(text: str, log=None, tmp=None) -> None: # pylint: disable=unused-argument
""" edit last message """
_send_data("editLastMessage", text) | 56,810 |
def get_pending_transfer_pairs(
transfers_pair: List[MediationPairState],
) -> List[MediationPairState]:
""" Return the transfer pairs that are not at a final state. """
pending_pairs = [
pair
for pair in transfers_pair
if pair.payee_state not in STATE_TRANSFER_FINAL
or pair.... | 56,811 |
def set_style(style_name: str = "default"):
"""
Sets colors, fonts, font sizes, bounding boxes, and more for plots using pyplot.
.. note::
The font sizes of the predefined styles will be overwritten!
.. seealso::
https://matplotlib.org/users/customizing.html
https://matplotlib.... | 56,812 |
def url_download(url, filename, md5=None, retries=3):
"""
Downloads given url and saves its content at given file.
Parameters
----------
url : unicode
Url to download.
filename : unicode
File to save the url content at.
md5 : unicode, optional
*Message Digest 5 (MD5)... | 56,813 |
def split(text: str, max_message_length: int = 4091) -> list:
""" Разделение текста на части
:param text: Разбиваемый текст
:param max_message_length: Максимальная длина разбитой части текста
"""
if len(text) >= max_message_length:
last_index = max(
map(
lambda s... | 56,814 |
def apply_preconfig_to_existing(
self,
preconfig_id: str,
ne_pk: str,
) -> bool:
"""Apply preconfig to existing approved appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - appliancePreconfig
- POST
-... | 56,815 |
def allow_ip(*ips: str):
"""
Allow ip address.
:param ips:
:return:
"""
allowed_ips.update(ipaddress.IPv4Address(ip) for ip in ips) | 56,816 |
def convert_quantiles_to_ci(ci, sm_concat, H, error_ci, coef_spline_smoothing=0):
"""
convert the computed quantiles for the normalized errors
into the quantiles of the errors by scaling back
with additional spline smoothing
"""
weights = np.ones((1,H))
weights_W = 1
q = lis... | 56,817 |
def ultraLatency(args):
"""
Launches a call of ultraLatency.py
args - object returned by argparse.ArgumentParser.parse_args()
"""
startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")
# Determine number of OH's
cardName = getCardName(args.shelf,args.slot)
amcBoard = HwAMC(car... | 56,818 |
def train(arch, loss, lr, epochs, dataset, save, save_path):
"""
Training function. Creates a model, trains it on a given dataset,
and saves the trained weights. It also saves TensorBoard logs for runtime
monitoring.
arch: architecture indicator. String.
loss: loss function indicator. String.
... | 56,819 |
def pythagoras(a, b):
"""Compute pythagoras.
Parameters
----------
a : float
length of one side of the triangle
b : float
length of second side
Returns
-------
c : float
length of the hypothenuse
"""
return np.sqrt(a**2 + b**2) | 56,820 |
def test_param_width_prec():
"""
Width and precision:
"""
old_result = '%*.*f' % (5, 2, 2.7182,)
new_result = '{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)
assert old_result == new_result
assert new_result == " 2.72" | 56,821 |
def construct_target_sets_method_4(features, labels, ncl, n_samples, n_dim, final_features, dataset_name=None):
""" Construct the target sets: most confusion between classes. """
class_combinations = np.unique(labels)
normals = None
anomalies = None
# investigate each combination of classes
c... | 56,822 |
def find_low_point_coords(arr: ArrayLike) -> list[list[int]]:
"""Return the low point locations in the input."""
arr_zeros = np.zeros(arr.shape)
# row[i+1] - row[i] > 0 => [row i+1] > row[i]
diff_down = np.diff(arr, 1, axis=0)
# row[i] - row[i+1] > 0 => row[i] > row[i+1]
diff_up = -1 * diff_d... | 56,823 |
def print_title(title):
""" Prints the tile with separation by ****** an in uppercase """
print(title.upper())
print("*" * 25) | 56,824 |
def save_config(config, path):
"""
Write the configuration file to ``path``.
"""
os.umask(0o77)
f = open(path, "w")
try:
return config.write(f)
finally:
f.close() | 56,825 |
def is_hw(unichr):
"""unichrが半角文字であればTrueを返す。"""
return not unicodedata.east_asian_width(unichr) in ('F', 'W', 'A') | 56,826 |
def view_experiments(query_id: Optional[int] = None, omic_id: Optional[int] = None):
"""View a list of all analyses, with optional filter by network id."""
experiment_query = manager.session.query(Experiment)
if query_id is not None:
experiment_query = experiment_query.filter(Experiment.query_id ==... | 56,827 |
def GenerateLegacyPrefixes(bitness, required_prefixes, optional_prefixes):
"""Produce list of all possible combinations of legacy prefixes.
Legacy prefixes are defined in processor manual:
operand-size override (data16),
address-size override,
segment override,
LOCK,
REP/REPE/REPZ,
REPNE/RE... | 56,828 |
def cfg_path():
"""Returns a path of the project config file to read."""
if utils.is_local_dev_server() or utils.is_dev():
return 'realms-dev.cfg'
return 'realms.cfg' | 56,829 |
def default_event_end(hour: int = DEFAULT_EVENT_END_HOUR) -> datetime:
"""Return next default start time."""
return next_x_hour(hour, default_event_start()) | 56,830 |
def deletedup(xs):
"""Delete duplicates in a playlist."""
result = []
for x in xs:
if x not in result:
result.append(x)
return result | 56,831 |
def _cell_version(cellname):
"""Gets the cell based treadmill root."""
admin_cell = admin.Cell(context.GLOBAL.ldap.conn)
cell = admin_cell.get(cellname)
version = cell.get('version')
if version is None:
raise Exception('Version is not defined for cell: %s')
root = cell.get('root')
... | 56,832 |
def handle_reading_status(user, shelf, book, privacy):
"""post about a user reading a book"""
# tell the world about this cool thing that happened
try:
message = {
"to-read": "wants to read",
"reading": "started reading",
"read": "finished reading",
"s... | 56,833 |
def getSequences(bedFileName, database, outputFileName):
"""Retrieves a fasta file of the sequences corresponding to genomic locations
in the specified bed file. Retrieves the sequences from the specified
database. A name for the output fasta file must be specified. This function
causes that file to be filled wi... | 56,834 |
def prettyStringRepr(s: Any, initialIndentationLevel=0, indentationString=" "):
"""
Creates a pretty string representation (using indentations) from the given object/string representation (as generated, for example, via
ToStringMixin). An indentation level is added for every opening bracket.
:param ... | 56,835 |
def iter_examples():
"""Iterate over the examples in this directory.
Each item is a dict with the following keys:
- "name" : the unique name of the example
- "filename" : the full file path to the example
"""
example_dir = os.path.abspath(os.path.dirname(__file__))
for filename in os.listdi... | 56,836 |
async def test_get_valid_angle_of_illumination(light_control):
"""Test get valid angle of illumination API."""
route = respx.post(f"http://{HOST}:80/axis-cgi/lightcontrol.cgi").respond(
json={
"apiVersion": "1.0",
"context": "my context",
"method": "getValidAngleOfIll... | 56,837 |
def create_flow(blocks, name="AnonymousFlow", mode=MODE_CRITICAL, common={}):
"""Auxiliary function to create test flows on the spot."""
return type(name, (TestFlow,), {'mode': mode,
'common': common,
'blocks': blocks}) | 56,838 |
def execute_script_get_local_variables(script, folder=None,
filename="_temp_custom_run_script_.py",
check=True):
"""
Executes a script and returns the local variables.
@param script filename or code
@param fold... | 56,839 |
def array_buffer(
allocator: Allocator, shape: Iterable[int], dtype: type
) -> Generator[Buffer, Buffer, None]:
"""
A context manager providing a contiguous array, which may be re-used between calls.
Args:
allocator: a function with the same signature as numpy.zeros which returns
an... | 56,840 |
def format_date_time(date_time: wx.DateTime) -> str:
"""Format the given datetime in a string."""
dt: wx.DateTime = date_time
d, mon, y = dt.GetDay(), dt.GetMonth() + 1, dt.GetYear()
h, m = pad_int_str(dt.GetHour()), pad_int_str(dt.GetMinute())
s = pad_int_str(dt.GetSecond())
str_out = f"{wx.Da... | 56,841 |
def test_calc_map():
"""
Test a map which creates a list
"""
pmap = pprocess.Map(limit=4)
calc = pmap.manage(pprocess.MakeParallel(calculate))
answers = list(range(0,2*N*N,2))
for i in range(0,N):
for j in range(0,N):
calc(i,j)
results = sorted([m for m in pmap])
... | 56,842 |
def del_file(f):
"""Deletes file from folder.
Args:
f (pathlib.Path): location of file.
"""
f.unlink() | 56,843 |
def replace_tail(path: str, search: str, replace: str) -> str:
"""
>>> replace_tail('/dir1/dir2/path.ext', '/dir1', '/dir2')
'dir2/dir2/path.ext'
>>> replace_tail('/dir1/dir2/path.ext', '/dir1/', '/dir2/')
'dir2/dir2/path.ext'
>>> replace_tail('/dir1/dir2/path.ext', '/dir3', '/dir2')
'/dir... | 56,844 |
def parse_cencus_tract_info(rows):
""" Pass in multiple rows for a census tract to create CensusTractInfo
object
Demographics the folowing are derived from 'Visible Minority' section
East Asian (Chinese + South East Asian + Korea + Japanese + Fillipino)
Hispanic (Latin American)
... | 56,845 |
def match_points_to_regions(points: List[Tuple[float, float]], shapes_ds: pd.Series,
keep_outside: bool = True, distance_threshold: float = 5.) -> pd.Series:
"""
Match a set of points to regions by identifying in which region each point falls.
If keep_outside is True, points tha... | 56,846 |
def GridSizer_GetCols3(sizer):
"""
Wrapper for wxGridSizer.GetColws()
With wx3 wxGridSizer.GetRows() and wxGridSizer.GetCols() "returns zero
if the sizer is automatically adjusting the number of rows depending
on number of its children."
@param sizer: Instance of wxGridSizer or a derived class... | 56,847 |
def check_config(cfg="fritz.defaults.yaml", yes=False):
"""
Check if config exists, generate a K token for SP, adjust cfg and distribute to K and SP
"""
c = cfg.replace(".defaults", "")
check_config_exists(cfg=cfg, yes=yes)
# generate a token for SkyPortal to talk to Kowalski
with open(c) a... | 56,848 |
def roi_align_nchw_ir(data, rois, num_rois, w_pc, pos_pc, pooled_size, spatial_scale, sample_ratio):
"""Hybrid routing fo ROI align operator in NCHW layout.
Parameters
----------
data : tvm.te.Tensor or numpy NDArray
4-D with shape [batch, channel, height, width]
rois : tvm.te.Tensor or nu... | 56,849 |
def mux(car_state):
"""Returns car_pose to publish, given car_state."""
if car_state == CarState.START: return None
elif car_state == CarState.AUTO: return g['auto_car_pose']
elif car_state == CarState.MANUAL: return g['manual_car_pose'] | 56,850 |
def update_log_level(debug: bool, level: str) -> str:
"""update log level"""
if debug is True:
level_num = logging.DEBUG
else:
level_num = logging.getLevelName(level)
settings.set('LOGLEVEL', logging.getLevelName(level_num))
return settings.LOGLEVEL | 56,851 |
def get_mapping(d):
"""
Reports fields and types of a dictionary recursively
:param object: dictionary to search
:type object:dict
"""
mapp=dict()
for x in d:
if type(d[x])==list:
mapp[x]=str(type(d[x][0]).__name__)
elif type(d[x])==dict:
ma... | 56,852 |
def tf_top_k_top_p_filtering(logits, top_k=0, top_p=1.0, filter_value=-float("Inf"), min_tokens_to_keep=1):
"""
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (batch size, vocabulary size)
top_k (`int`, *optional*, defaul... | 56,853 |
def eval_fx(fx, stats):
"""Given fx and stats ('min', 'max', 'mean', 'std') return the result"""
_ = BNF().parseString(fx, parseAll=True)
val = evaluate_stack(exprStack[:], stats)
return val | 56,854 |
def checkUniqueHeaders(inputFile, checkAlphaNumeric=False, checkUCSC=False, checkAssemblyHub=True):
"""Check that headers are unique and meet certain requirements."""
seen = set()
for header, seq in fastaRead(inputFile):
if " " in header or "\t" in header:
raise RuntimeError("The fasta h... | 56,855 |
def setTrace():
"""
Set a tracepoint in the Python debugger that works with Qt
from PyQt4.QtCore import pyqtRemoveInputHook
when done debugging, call QtCore.pyqtRestoreInputHook() from pdb
may have to use c several times
"""
from PyQt5.QtCore import pyqtRemoveInputHook
from pdb import ... | 56,856 |
def generate_function_code_from_file(infile: str = None, outfile: str = None) -> None:
"""Generate the function code from the input file.
:param infile: {str}
:param outfile: {str}
:returns None:
"""
logging.info("Going to parse input file '{}'".format(infile))
function_name = None
fu... | 56,857 |
def help(event):
"""Returns some documentation for a given command.
Examples:
!help help
"""
def prepare_doc(doc):
return doc.split('\n')[0]
plugin_manager = event.source_bot.plugin_manager
prendex = 'Available commands: '
if len(event.args) < 1:
return prendex +... | 56,858 |
def wordCount(wordListRDD):
"""Creates a pair RDD with word counts from an RDD of words.
Args:
wordListRDD (RDD of str): An RDD consisting of words.
Returns:
RDD of (str, int): An RDD consisting of (word, count) tuples.
"""
return (wordListRDD.map(lambda x: (x,1)).reduceByKey(lambd... | 56,859 |
def parse_size(text):
"""Parse a size string to a structured type"""
match = SIZE_RE.match(text)
if not match:
return None
width = int(match.group('width'))
height = int(match.group('height'))
if 'rate' in match.groupdict():
framerate = float(match.group('rate'))
interlaced =... | 56,860 |
def temporarily_as_user(setenv=True):
"""
Set effective user/group ID to the ordinary user (the one invoking the script).
An optional parameter "setenv=False" will skip setting user-related
environmental variables accordingly.
It can be used either as an ordinary function, or as a context manager
in "with" statem... | 56,861 |
def ontology_references(handle) -> ty.Iterable[RfamDatabaseLink]:
"""
Produce an iterable of all ontology terms from Rfam.
"""
for reference in parse(handle):
if not reference.from_ontology():
continue
if reference.database in {"SO", "GO"}:
reference = correct_g... | 56,862 |
def encode_author(author):
"""
:param author:
:return:
"""
author = lxml.html.fromstring(author).text
if isinstance(author, str):
return unidecode.unidecode(remove_control_chars_author(to_unicode(author)))
return author | 56,863 |
def _buffering_rectangular_subregions(xyz_mins, xyz_maxs, rmax_xyz):
"""Decompose the buffered subvolume into 27 subregions.
There will be one subregion for the subvolume itself,
and the remaining 26 come from the rectangles adjacent to
each face, edge, and corner:
* 1 for the data in (xyz_mins, x... | 56,864 |
def MVR3(pos1, pos2, pos3):
"""Designates start point, end point and center point. Moves from start point to end point with circular interpolation movement"""
MVR3_Int(printLineNum, pos1, pos2, pos3) | 56,865 |
def create_clowder_collection(session, url, collection, dryrun=False):
"""Create a Clowder collection.
Args:
session: http session
url: Clowder URL
collection: Clowder collection name
dryrun: Boolean. If true, no POST requests are made
Returns:
coll_id: Clowder colle... | 56,866 |
def pait(
# param check
at_most_one_of_list: Optional[List[List[str]]] = None,
required_by: Optional[Dict[str, List[str]]] = None,
pre_depend_list: Optional[List[Callable]] = None,
make_mock_response_fn: Optional[Callable[[Type[response.PaitBaseResponseModel]], Any]] = None,
# doc
author: Op... | 56,867 |
def test_LocalstackSession_start_timeout():
"""Test that the LocalstackSession.start() timeout works."""
test_session = test_utils.make_test_LocalstackSession()
test_session._check_services.side_effect = exceptions.ContainerNotStartedError(
test_session
)
with pytest.raises(exceptions.Cont... | 56,868 |
def alpha_clipping(rectangle, line):
"""
Apply alpha-clipping of `line` according to `rectangle`.
Parameters
----------
rectangle : Rectangle
line : Line
Returns
-------
`None` or Line within rectangle
"""
a_min = 0.0
a_max = 1.0
outcode_p1 = rectangle.get_outcode(l... | 56,869 |
def openSessionOptions(fileName: str = '', directory: typing.Literal['CURRENT', 'HOME'] = HOME) -> CaeKerPrefs:
"""This function enables you to examine and change the default behavior for many session
options Abaqus/CAE; that is, the settings that you can save in Abaqus/CAE from the
FileSave Display Constra... | 56,870 |
def create_spark_session():
"""
Create the entry point to programming Spark with the Dataset and DataFrame API.
The entry point into all functionality in Spark is the SparkSession class.
Instead of having a spark context, hive context, SQL context, now all of it is encapsulated in a Spark session.
S... | 56,871 |
def model_gui(model,
sample=None,
data_dt=.01,
plot=plot_fit_diagnostics,
conditions=None,
verify=False):
"""Mess around with model parameters visually.
This allows you to see how the model `model` would be affected by
various changes in... | 56,872 |
def check_resize(server, flavor, flavor_id):
"""
Verify that a resizing server is properly resized.
If that's the case, confirm the resize, if not raise an error.
"""
refresh_server(server)
while server.status == 'RESIZE':
yield
refresh_server(server)
if server.status == 'VER... | 56,873 |
def precision_recall_evaluator(
input,
label,
positive_label=None,
weight=None,
name=None, ):
"""
An Evaluator to calculate precision and recall, F1-score.
It is adapt to the task with multiple labels.
- If positive_label=-1, it will print the average precision, ... | 56,874 |
def force_bytes(s, encoding='utf-8', errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first for performance reas... | 56,875 |
def single_random_user(ev_room):
"""
Returns a single user name from users in a room
:param ev_room: Room to select users from
:return: A single user tuple
"""
return random.choice(GlobalVars.users_chatting[ev_room]) | 56,876 |
def get_bploc_tuples(bp, source_map=None):
""" Returns a list of tuples (file, line) where a breakpoint was resolved. """
if not bp.IsValid():
return []
locs = []
for bploc in bp:
le_tupl = resolve_line_entry(bploc.GetAddress().line_entry, source_map)
if le_tupl[0] and le_tupl[1]... | 56,877 |
def remplace_mot_entre_parentheses(texte: str):
"""
Les mots entre parenthèse représente le petite texte dans Animal Crossing.
Cela n'est pas prononcées.
"""
while '(' in texte and ')' in texte:
debut = texte.index("(")
fin = texte.index(")")
texte = texte[:debut] + "*" * ... | 56,878 |
def main(token: str) -> int:
"""
Args:
token (str): bot access token
Return:
exit code of main script
NoneZero indicate a failure
"""
client = discord.Client()
@client.event
async def on_error(event, *args, **kwargs):
"""
Safely logout bot on event of... | 56,879 |
def _threefry(
irb, key_buf, key_offset, counter_buf, counter_offset, out_buf, out_offset, out_shape
):
"""IRBuilder code for running Threefry
Parameters
----------
irb: IRBuilder
IRBuilder that this code will be generated for.
key_buf: BufferVar
Buffer to read the key from.
... | 56,880 |
def ussa_temp(altitude):
""" Compute reference temperature for a given altitude corresponding to the
US Standard Atmosphere.
Parameters
----------
altitude : float
Ambient altitude in kilometers; must lie in the range 0-50 km.
Returns
-------
Temperature at given altitude in K.... | 56,881 |
def get_output_lines(ctx, line):
"""Expression evaluated to result, otherwise treated as plain text"""
if line.startswith('{{') and line.endswith('}}'):
expr = line[2:-2].strip()
result = eval(expr, {}, {'ctx': ctx})
if isinstance(result, str):
yield result
elif isins... | 56,882 |
def get_scaled_cutout_basic_view(shp, p1, p2, scales):
"""
Like get_scaled_cutout_basic, but returns the view/slice to extract
from an image, instead of the extraction itself
"""
x1, y1 = p1[:2]
x2, y2 = p2[:2]
scale_x, scale_y = scales[:2]
# calculate dimensions of NON-scaled cutout
... | 56,883 |
def line_base(y, x, source_dataframe, width, height, description, title,
x_label, y_label, show_plot, color, colorbar_type, legend,
line_width, alpha, style, x_axis_type, y_axis_type, x_range,
y_range, fill_between, grid_visible, session, save_path):
""" One dimensional plo... | 56,884 |
def update_catalogs(pot_path, output_dir, locale):
"""
Create new locale `.po` files or update and merge if they already exist.
Parameters
----------
pot_path: str
Path to `.pot` file.
output_dir: str
Path to base output directory. The `.po` files will be placed in
"{out... | 56,885 |
def xml_download_retry(ena_accession):
"""
pulling xml record from ENA, some of the records take a longer time to connect, this retry set timeout to be 5 mins
:param ena_accession:
:return:
"""
try:
xml = ET.fromstring(requests.get("https://www.ebi.ac.uk/ena/data/view/{}&display=xml".for... | 56,886 |
def check_data_for_invalid(data: List[int], preamble_size: int = 25) -> int:
"""Check the data for a number with an invalid sum.
Args:
data (List[int]): data from the data port
preamble_size (int; optional): the size of the preamble for data;
defaults to 25
Returns:
int... | 56,887 |
def parseWeather(data: list) -> list:
""" take MetOffice weatherdata and return the first four future entries"""
forecast = []
whichday = 0
for day in data:
for entry in day['Rep']:
# The forecast is laggy for the current day, so we need to discard past entries
if ((whichday == 0) & (int(entry['... | 56,888 |
def process_file(filename):
"""
Process FITS file to get desired header info and image statistics
"""
outstr = ""
with fits.open(filename) as hdul:
hdr = hdul[0].header
if hdr['NAXIS'] == 3:
im = np.flipud(hdul[0].data[:, :, 0])
else:
im = hdul[0].data... | 56,889 |
def knapsack(v, w, n, W):
"""
Function solves 0/1 Knapsack problem
Function to calculate frequency of items to be added
to knapsack to maximise value
such that total weight is less than or equal to W
:param v: set of values of n objects,
:param w: set of weights of n objects,
first eleme... | 56,890 |
def get_stock_forms_by_case_id(case_ids):
"""Get a dict of form id sets by case id for the given list of case ids
This function loads Couch stock forms (even though they are
technically stored in SQL).
"""
form_ids_by_case_id = defaultdict(set)
for case_id, form_id in (
StockReport.obje... | 56,891 |
def randint(low=0, high=None, shape=[1], dtype=None, name=None):
"""
:alias_main: paddle.randint
:alias: paddle.randint,paddle.tensor.randint,paddle.tensor.random.randint
This function returns a Tensor filled with random integers from the
"discrete uniform" distribution of the specified data type in the ... | 56,892 |
def variable_frequency(DataFrame, variable, sorted=False, ascending=False, limit=None, show_plot=False):
"""
Parameters
----------
DataFrame : pandas.DataFrame
DataFrame
variable : str
Variable to examine the freqeuncy.
sorted : bool, default False
ascending : bool, defa... | 56,893 |
def predict(examples,parameters):
"""
Compute the probability of being y=1 for all the `examples` given `parameters`.
Return a 1D array of probabilities.
"""
z = np.dot(examples,parameters)
return sigmoid(z) | 56,894 |
def less_generators(X):
"""
Reduce the generator matrix of the module defined by ``X``.
This is Algorithm 6.4 in [BC2012]_ and relies on the row syzygies of
the matrix ``X``.
EXAMPLES::
sage: from sage.geometry.hyperplane_arrangement.check_freeness import less_generators
sage: R.<... | 56,895 |
def test_hug_explainable():
"""Test to ensure hug_explainable works as expected"""
local_results = my_code()
http_results = hug.test.get(__name__, 'my_code').data
for results in (local_results, http_results):
assert results['answer'] == 20
explanation = results['explanation']
ass... | 56,896 |
def deploy_plain_bgp_config(duthost):
"""
Deploy bgp plain config on the DUT
Args:
duthost: DUT host object
Returns:
Pathname of the bgp plain config on the DUT
"""
bgp_plain_template_src_path = os.path.join(TEMPLATE_DIR, BGP_PLAIN_TEMPLATE)
bgp_plain_template_path = os.pat... | 56,897 |
def __normalize_request_parameters(post_body, query):
"""
Return a normalized string representing request parameters. This
includes POST parameters as well as query string parameters.
"oauth_signature" is not included.
:param post_body: The body of an HTTP POST request.
:type post_body: strin... | 56,898 |
def test_repo_dir(dir, name):
"""
Test an entered GitHub repository directory name.
"""
subdir = os.path.basename(dir)
return subdir != name | 56,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.