content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_keys():
""" Get all keys of a given class. """
yield lambda selector: base.find_keys(metadata.CRAIGSLIST, selector) | 34,600 |
def With(prop, val):
"""The 'with <property> <value>' specifier.
Specifies the given property, with no dependencies.
"""
return Specifier(prop, val) | 34,601 |
def bbox_artist(artist, renderer, props=None, fill=True):
"""
A debug function to draw a rectangle around the bounding
box returned by an artist's `.Artist.get_window_extent`
to test whether the artist is returning the correct bbox.
*props* is a dict of rectangle props with the additional property
... | 34,602 |
def pad_node_id(node_id: np.uint64) -> str:
""" Pad node id to 20 digits
:param node_id: int
:return: str
"""
return "%.20d" % node_id | 34,603 |
def test_list_any_uri_enumeration_nistxml_sv_iv_list_any_uri_enumeration_1_1(mode, save_output, output_format):
"""
Type list/anyURI is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/anyURI/Schema+Instance/NISTSchema-SV-IV-list-anyURI-enumeration-1.xsd",
inst... | 34,604 |
async def test_not_200_ok(status_code: int) -> None:
"""Responses that don't have status code 200 should not be cached."""
cache = Cache("locmem://null")
spy = CacheSpy(PlainTextResponse("Hello, world!", status_code=status_code))
app = CacheMiddleware(spy, cache=cache)
client = httpx.AsyncClient(app... | 34,605 |
def ballcurve(x: ArrayLike, xi: float) -> ArrayLike:
"""
function to generate the curve for the nested structure, given a shape
parameter xi. If xi= 1 is linear.
input:
----------
x: 1D array, [0,1]
initial values to be evaluated on the function
xi: number, >=1
shape paramete... | 34,606 |
def plot_attention(src_words: Union[np.ndarray, Sequence[str]],
trg_words: Sequence[str],
attention_matrix: np.ndarray,
file_name: str,
size_x: numbers.Real = 8.0,
size_y: numbers.Real = 8.0) -> None:
"""This takes in sourc... | 34,607 |
def event_log(time, name):
"""开发测试用"""
print('Event ' + name + ', happened at ' + str(time)) | 34,608 |
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
fc = open("connections_log", "a+")
fc.write("%s:%s has connected.\n" % client_address)
... | 34,609 |
def center_vertices(vertices, faces, flip_y=True):
"""
Centroid-align vertices.
Args:
vertices (V x 3): Vertices.
faces (F x 3): Faces.
flip_y (bool): If True, flips y verts to keep with image coordinates convention.
Returns:
vertices, faces
"""
vertices = verti... | 34,610 |
def test_schema_selection(
schema: dict,
mask: singer.SelectionMask,
stream_name: str,
):
"""Test that schema selection rules are correctly applied to SCHEMA messages."""
selected_schema = get_selected_schema(
stream_name,
schema,
mask,
logging.getLogger(),
)
... | 34,611 |
def start_client(page_to_load, PORT=8563):
"""
Starts Python-Eel client and loads the page passed in
'page_to_load', on port 'PORT'.
RETURNS: None
"""
print("in start client")
try:
eel.start(page_to_load, port=PORT)
except Exception:
page_to_load = 'get_chrome.html'
... | 34,612 |
def test_environ(script, tmpdir):
"""$PYTHONWARNINGS was added in python2.7"""
demo = tmpdir.join('warnings_demo.py')
demo.write('''
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
from logging import basicConfig
basicConfig()
from warnings import warn
warn("deprecated!", ... | 34,613 |
def metadata_validator(form, value):
"""
Validates that custom citations are correct.
:param form: Metadata schemas/form to validate
:param value: Appstruct/values passed in for validation.
:return: None, raise a colander.Invalid exception if the validation fails.
"""
error = False
exc ... | 34,614 |
def fingerprint_atompair(fpSize=2048, count=False):
"""Atom pair fingerprint (list of int).
Args:
fpSize: Size of the generated fingerprint (defaults to 2048).
count: The default value of False will generate fingerprint bits
(0 or 1) whereas a value of True will generate the count o... | 34,615 |
def bend_euler_s(**kwargs) -> Component:
"""Sbend made of euler bends."""
c = Component()
b = bend_euler(**kwargs)
b1 = c.add_ref(b)
b2 = c.add_ref(b)
b2.mirror()
b2.connect("o1", b1.ports["o2"])
c.add_port("o1", port=b1.ports["o1"])
c.add_port("o2", port=b2.ports["o2"])
return c | 34,616 |
def main():
"""Function: main
Description: Initializes program-wide used variables and processes command
line arguments and values.
Variables:
dir_chk_list -> contains options which will be directories.
func_dict -> dictionary list for the function calls or other options.
... | 34,617 |
def default(args):
"""Default task, called when no task is provided (default: init)."""
def help_function(): pass
# paver.tasks.help(args, help_function)
call_task("help", args=args) | 34,618 |
def phot_error(star_ADU,n_pix,n_b,sky_ADU,dark,read,gain=1.0):
"""
Photometric error including
INPUT:
star_ADU - stellar flux in ADU (total ADU counts within aperture)
n_pix - number of pixels in aperture
n_b - number of background pixels
sky_ADU - in ADU/pix
dark ... | 34,619 |
def tan(x):
"""
tan(x) -> number
Return the tangent of x; x in radians.
"""
try:
res, x = _init_check_mpfr(x)
gmp.mpfr_tan(res, x, gmp.MPFR_RNDN)
return mpfr._from_c_mpfr(res)
except TypeError:
res, x = _init_check_mpc(x)
gmp.mpc_tan(res, x, gmp.MPC_RNDNN... | 34,620 |
async def test_get_id_from_scene_name() -> None:
"""Test looking up a scene id from the name."""
with pytest.raises(ValueError):
scenes.get_id_from_scene_name("non_exist")
assert scenes.get_id_from_scene_name("Ocean") == 1 | 34,621 |
def test_wrapped_func():
"""
Test uncertainty-aware functions obtained through wrapping.
"""
########################################
# Function which can automatically handle numbers with
# uncertainties:
def f_auto_unc(angle, *list_var):
return umath.cos(angle) + sum(list_var)
... | 34,622 |
def T2str_mag_simplified(K, TE, T2str, N):
"""Signal Model of T2str-weighted UTE GRE Magnitude Image
S = K * [ exp(-TE/T2*) ] + N
parameters:
K :: constant (proportional to proton density)
TE :: sequence echo time
T2str :: relaxation due to spin-spin effects and dephasing
N... | 34,623 |
def main():
"""The program's main entry point"""
program_name = os.path.basename(sys.argv[0])
initialize_debugging(program_name)
process_environment_variables()
arguments = process_command_line()
# Reading from standard input if there are no arguments:
text = []
longuest_line = 0
i... | 34,624 |
def tune(runner, kernel_options, device_options, tuning_options):
""" Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type... | 34,625 |
def test_nvswitch_traffic_p2p(handle, switchIds):
"""
Verifies that fabric can pass p2p read and write traffic successfully
"""
test_utils.skip_test("Bandwidth field not being updated yet")
# TX_0 and RX_0 on port 0
nvSwitchBandwidth0FieldIds = []
for i in range(dcgm_fields.DCGM_FI_DEV_NVS... | 34,626 |
def getTimeString(t, centi=True):
"""
category: General Utility Functions
Given a value in milliseconds, returns a Lstr with:
(hours if > 0):minutes:seconds:centiseconds.
WARNING: this Lstr value is somewhat large so don't use this to
repeatedly update node values in a timer/etc. For that p... | 34,627 |
def version(ctx):
"""Show CSE version"""
ver = 'Container Service Extension for %s' % \
'VMware vCloud Director, version %s' % \
pkg_resources.require("container-service-extension")[0].version
print(ver) | 34,628 |
def validation_supervised(model, input_tensor, y_true, loss_fn, multiclass =False, n_classes= 1):
"""
Returns average loss for an input batch of data with a supervised model.
If running on multiclass mode, it also returns the accuracy.
"""
y_pred = model(input_tensor.float())
if multiclass:
... | 34,629 |
def configure_logger(app):
"""
logging: based on the configured setting we
:param app:
:return:
"""
#
# support stream and rotating handlers
logger = app.logger
logger.setLevel(logging.INFO)
if app.config['HANDLER'] == "StreamHandler":
class InfoFilter(logging.Filter):
... | 34,630 |
def timing(func=None, *, name=None, is_stage=None):
"""
Decorator to measure the time taken by the function to execute
:param func: Function
:param name: Display Name of the function for which the time is being calculated
:param is_stage: Identifier for mining stage
Examples:
... | 34,631 |
def is_skip_file(filename):
""" Should the given file be skipped over for testing
:param filename: The file's name
:type filename: String
:return: True if the given file should be skipped, false otherwise
:rtype: Boolean
"""
filename_len = len(filename)
for skip_name in SKIP_FILES:
... | 34,632 |
def lowercase_or_notify(x):
""" Lowercases the input if it is valid, otherwise logs the error and sets a default value
Args:
String to lowercase
Returns:
Lowercased string if possible, else unmodified string or default value.
"""
try:
return x.lower()
ex... | 34,633 |
def is_not_null(node, eval_type, given_variables):
"""Process the is_not_null operator.
:param node: Formula node
:param eval_type: Type of evaluation
:param given_variables: Dictionary of var/values
:return: Boolean result, SQL query, or text result
"""
if eval_type == EVAL_EXP:
# ... | 34,634 |
def search_for_rooms(filters, allow_admin=False, availability=None):
"""Search for a room, using the provided filters.
:param filters: The filters, provided as a dictionary
:param allow_admin: A boolean specifying whether admins have override privileges
:param availability: A boolean specifying whether... | 34,635 |
def effect_inc_decr_bid_factors(strategy=2):
"""
Experiment that check the effect of having all the possible values for increasing and decreasing bidding factor.
Plots a hit map with the average of difference between the starting prices and the market price in the last round.
This average difference is ... | 34,636 |
def get_scalar(obj):
"""obj can either be a value, or a type
Returns the Stella type for the given object"""
type_ = type(obj)
if type_ == type(int):
type_ = obj
elif type_ == PyWrapper:
type_ = obj.py
# HACK {
if type_ == type(None): # noqa
return None_
elif t... | 34,637 |
def send_test_packets(
mode=DEFAULT_SENDER_MODE,
config=DEFAULT_CONFIG,
publickey=DEFAULT_PUBLICKEY,
address=DEFAULT_HOSTNAME,
port=None,
n=3,
encrypt=True,
raw_packet=None):
"""
Send n (default 3) test packets to the DoseNet server.
"""
s... | 34,638 |
def get_importable_subclasses(base_class, used_in_automl=True):
"""Get importable subclasses of a base class. Used to list all of our estimators, transformers, components and pipelines dynamically.
Args:
base_class (abc.ABCMeta): Base class to find all of the subclasses for.
used_in_automl: Not... | 34,639 |
def sin(x, deg=None, **kwargs):
"""Computes the sine of x in either degrees or radians"""
x = float(x)
if deg or (trigDeg and deg is None):
x = math.radians(x)
return math.sin(x) | 34,640 |
def Debug(message,
print_init_shape=True,
print_forward_shape=False,
print_inverse_shape=False,
compare_vals=False,
name='unnamed'):
# language=rst
"""
Help debug shapes
:param print_init_shape: Print the shapes
:param print_forward_shape: Print the... | 34,641 |
def limit_movie_char_fields(sender, instance, *args, **kwargs):
"""
Limits Movie's character fields based on maximum length.
"""
if len(instance.title) > Movie.TITLE_MAX_LENGTH:
instance.title = instance.title[:Movie.TITLE_MAX_LENGTH-1] + '…'
instance.description = utils.trim_text_... | 34,642 |
def bloated_nested_block(block_dets, *, repeat=False, **_kwargs):
"""
Look for long indented blocks under conditionals, inside loops etc that are
candidates for separating into functions to simplify the narrative of the
main code.
"""
bloated_outer_types = set()
included_if = False
for l... | 34,643 |
def _to_bytes(value: Any, type_str: str = "bytes32") -> bytes:
"""Convert a value to bytes"""
if isinstance(value, bool) or not isinstance(value, (bytes, str, int)):
raise TypeError(f"Cannot convert {type(value).__name__} '{value}' to {type_str}")
value = _to_hex(value)
if type_str == "bytes":
... | 34,644 |
def _plan_ftd1c(pa: str = "abc", pb: int = 50):
"""
This is plan description.
Multiline string.
Parameters
----------
pa
Description of the parameter pa
pb : int
Description
of the parameter pb
"""
yield from [pa, pb] | 34,645 |
def _map_sbs_sigs_back(df: pd.DataFrame) -> pd.Series:
"""
Map Back Single-Base Substitution Signatures.
-----------------------
Args:
* df: pandas.core.frame.DataFrame with index to be mapped
Returns:
* pandas.core.series.Series with matching indices to context96
"""
def _c... | 34,646 |
def test_pipeline_get_eta_metric_peak(
peak: bool,
expected: float,
source_df: pd.DataFrame
) -> None:
"""
Tests the calculation of the eta metric.
Args:
peak: Whether to use peak flux when calculating the eta.
expected: Expected eta value.
source_df: The dataframe conta... | 34,647 |
def rmsd(
coords1: np.ndarray,
coords2: np.ndarray,
atomicn1: np.ndarray,
atomicn2: np.ndarray,
center: bool = False,
minimize: bool = False,
atol: float = 1e-9,
) -> float:
"""
Compute RMSD
Parameters
----------
coords1: np.ndarray
Coordinate of molecule 1
c... | 34,648 |
def get_bridge_interfaces(yaml):
"""Returns a list of all interfaces that are bridgedomain members"""
ret = []
if not "bridgedomains" in yaml:
return ret
for _ifname, iface in yaml["bridgedomains"].items():
if "interfaces" in iface:
ret.extend(iface["interfaces"])
retu... | 34,649 |
def serialize_for_c(qr, border, message):
""" generates a c-style representation of the qr code to stdout. """
# size the output for an even fit to an 8-bit matrix
output_size = 8 * (4 * qr.version + 17 + 2 * border)
# NB: trying to invert the colors here doesn't work with qrcode-6.1
img = qr.make_... | 34,650 |
def get_library_dirs():
"""
Return lists of directories likely to contain Arrow C++ libraries for
linking C or Cython extensions using pyarrow
"""
import os
import sys
package_cwd = os.path.dirname(__file__)
library_dirs = [package_cwd]
if sys.platform == 'win32':
# TODO(we... | 34,651 |
def init_trunk_weights(model, branch=None):
""" Initializes the trunk network weight layer weights.
# Arguments
branch: string indicating the specific branch to initialize. Default of None will initialize 'push-', 'grasp-' and 'place-'.
"""
# Initialize network weights
for m in model.named... | 34,652 |
def get_entity_matched_docs(doc_id_map: List[str], data: List[dict]):
"""Gets the documents where the document name is contained inside the claim
Args:
doc_id_map (List[str]): A list of document names
data (List[dict]): One of the FEVEROUS datasets
Returns:
List[List[str]]: A list ... | 34,653 |
def getTemplateKeys(k):
"""
Prints out templates key for license or gitignore templates from github api
Params: str
Return: code
"""
code = 0
if k.lower() == "license":
r = requests.get(GITHUB_LICENSE_API)
if r.status_code != 200:
code = 1
print("... | 34,654 |
def test_field_extension_exclude_and_include(app_client, load_test_data):
"""Test POST search including/excluding same field (fields extension)"""
test_item = load_test_data("test_item.json")
resp = app_client.post(
f"/collections/{test_item['collection']}/items", json=test_item
)
assert res... | 34,655 |
def get_num_conv2d_layers(model, exclude_downsample=True, include_linear=True):
""" Check the number of Conv2D layers. """
num = 0
for n, m in model.named_modules():
if "downsample" in n and exclude_downsample:
continue
if is_conv2d(m) or (include_linear and isinstance(m, nn.Lin... | 34,656 |
def im_list_to_blob(ims, RGB, NIR, DEPTH):
"""Convert a list of images into a network input.
Assumes images are already prepared (means subtracted, BGR order, ...).
"""
max_shape = np.array([im.shape for im in ims]).max(axis=0)
num_images = len(ims)
if RGB & NIR & DEPTH:
blob = np.zeros((... | 34,657 |
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up entry."""
miniserver = get_miniserver_from_config_entry(hass, config_entry)
loxconfig = miniserver.lox_config.json
devices = []
for switch_entity in get_all_switch_entities(loxconfig):
if switch_entity["type"] in ... | 34,658 |
def displayOutput(win,text):
"""Displays info to the user at the bottom left windows"""
text = text.split(",")
x,y = 215,485
for record in text:
text = Text(Point(x,y),record); text.setFill('grey2')
text.setSize(11); text.draw(win)
y+=25 | 34,659 |
def gradU_from_momenta(x, p, y, sigma):
"""
strain F'(x) for momenta p defined at control points y
a method "convolve_gradient" is doing a similar job but only compute (gradF . z)
x (M, D)
p (N, D)
y (N, D)
return
gradU (M, D, D)
"""
kern = deformetrica.support.kernels.factory(... | 34,660 |
def testSingleSidedSinewaveBoxcar():
"""
Tests teh power spectrum of a sinewave with no hann window.
"""
x = np.arange(-5, 5+0.5, 0.5)
raw_data = np.sin(x)
actual_spectrum = power_spectrum(raw_data, window='box',
siding='single')
desired_spectrum = np.... | 34,661 |
def rules_cuda_dependencies(with_rules_cc = True):
"""Loads rules_cuda dependencies. To be called from WORKSPACE file.
Args:
with_rules_cc: whether to load and patch rules_cc repository.
"""
maybe(
name = "bazel_skylib",
repo_rule = http_archive,
sha256 = "97e70364e9249702... | 34,662 |
def summarize_gp(gp_model, max_num_points=None, weight_function=None):
"""Summarize the GP model with a fixed number of data points inplace.
Parameters
----------
gp_model : gpytorch.models.ExactGPModel
max_num_points : int
The maximum number of data points to use.
weight_function: Call... | 34,663 |
def process(seed, K):
"""
K is model order / number of zeros
"""
print(K, end=" ")
# create the dirac locations with many, many points
rng = np.random.RandomState(seed)
tk = np.sort(rng.rand(K)*period)
# true zeros
uk = np.exp(-1j*2*np.pi*tk/period)
coef_poly = poly.polyfromro... | 34,664 |
def convert_to_file(cgi_input, output_file, twobit_ref):
"""Convert a CGI var file and output VCF-formatted data to file"""
if isinstance(output_file, basestring):
output_file = auto_zip_open(output_file, 'wb')
conversion = convert(cgi_input, twobit_ref) # set up generator
for line in convers... | 34,665 |
def _gen_sieve_array(M, factor_base):
"""Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
that doesn't divide the coefficient `a` we add log_p over the sieve_array
such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i`
is an integer. When p = 2 then log_p i... | 34,666 |
def yolo_eval_weighted_nms(yolo_outputs,
anchors,
num_classes,
image_shape,
score_threshold=.6):
""" yolo evaluate
Args:
yolo_outputs: [batch, 13, 13, 3*85]
anchors: [9, 2]
num_cl... | 34,667 |
def next_coach_id():
"""
Generates the next id for newly added coaches, since their slugs (which combine the id and name fields)
are added post-commit.
"""
c = Coach.objects.aggregate(Max("id"))
return c['id__max']+1 | 34,668 |
def get_unsigned_short(data, index):
"""Return two bytes from data as an unsigned 16-bit value"""
return (data[index+1] << 8) + data[index] | 34,669 |
def getObjDetRoI(imgSize, imgPatchSize, objx1, objy1, objx2, objy2):
"""
Get region of interest (ROI) for a given object detection with respect to image and image patch boundaries.
:param imgSize: size of the image of interest (e.g., [1920x1080]).
:param imgPatchSize: Patch size of the image patch of in... | 34,670 |
def sigma_pp(b):
"""pair production cross section"""
return (
sigma_T
* 3.0
/ 16.0
* (1 - b ** 2)
* (2 * b * (b ** 2 - 2) + (3 - b ** 4) * np.log((1 + b) / (1 - b)))
) | 34,671 |
def plot_shots_per_lens(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None:
"""
Barplot of the number of shots per lens used, on the provided subplot. Acts in place.
Args:
subplot: the subplot plt.axes on which to plot.
data: the pandas DataFrame with your exif data.
Returns:
... | 34,672 |
def compute_radii_simple(distances):
"""
Compute the radius for every hypersphere given the pairwise distances
to satisfy Eq. 6 in the paper. Does not implement the heuristic described
in section 3.5.
"""
n_inputs = tf.shape(distances)[1]
sorted_distances = tf.sort(distances, direction="ASC... | 34,673 |
def data_resolution_and_offset(data, fallback_resolution=None):
"""Compute resolution and offset from x/y axis data.
Only uses first two coordinate values, assumes that data is regularly
sampled.
Returns
=======
(resolution: float, offset: float)
"""
if data.size < 2:
if data.s... | 34,674 |
def show_with_memory_profiler(times, cards_fn, suites, numbers,
print_results=False):
"""A decorator to show reuslts and time elapsed.
"""
fun = memory_profiler.profile(cards_fn)
fun(suites, numbers)
cards = cards_fn(suites, numbers)
if print_results:
print... | 34,675 |
def get_changed_files_committed_and_workdir(
repo: Git, commithash_to_compare: str
) -> List[str]:
"""Get changed files between given commit and the working copy"""
return repo.repo.git.diff("--name-only", commithash_to_compare).split() | 34,676 |
def load_document_by_string(
string: str, uri: str, loadingOptions: Optional[LoadingOptions] = None
) -> Any:
"""Load a CWL object from a serialized YAML string."""
yaml = yaml_no_ts()
result = yaml.load(string)
return load_document_by_yaml(result, uri, loadingOptions) | 34,677 |
def rename_symbol(symbol):
"""Rename the given symbol.
If it is a C symbol, prepend FLAGS.rename_string to the symbol, but
account for the symbol possibly having a prefix via split_symbol().
If it is a C++ symbol, prepend FLAGS.rename_string to all instances of the
given namespace.
Args:
symb... | 34,678 |
def py_time(data):
""" returns a python Time
"""
if '.' in data:
return datetime.datetime.strptime(data, '%H:%M:%S.%f').time()
else:
return datetime.datetime.strptime(data, '%H:%M:%S').time() | 34,679 |
def create_empty_copy(G,with_nodes=True):
"""Return a copy of the graph G with all of the edges removed.
Parameters
----------
G : graph
A NetworkX graph
with_nodes : bool (default=True)
Include nodes.
Notes
-----
Graph, node, and edge data is not propagated to the new ... | 34,680 |
def trim_resize_frame(frame, resize_ratio, trim_factor):
"""
Resize a frame according to specified ratio while
keeping original the original aspect ratio, then trim
the longer side of the frame according to specified
factor.
Parameters
----------
frame: np.array
The input frame
resize_ratio: floa... | 34,681 |
def copy_doclist(doclist, no_copy = []):
"""
Save & return a copy of the given doclist
Pass fields that are not to be copied in `no_copy`
"""
cl = []
# main doc
c = Document(fielddata = doclist[0].fields.copy())
# clear no_copy fields
for f in no_copy:
if c.fields.has_key(f):
c.fields[f] = No... | 34,682 |
def set_from_tags(tags, title, description, all=True):
"""all=True means include non-public photos"""
user = flickr.test_login()
photos = flickr.photos_search(user_id=user.id, auth=all, tags=tags)
set = flickr.Photoset.create(photos[0], title, description)
set.editPhotos(photos)
return set | 34,683 |
def submit():
"""Upload local file.
Needs to follow the station register template.
"""
spec = get_layout_active_spec('Upload')
if request.method == 'POST':
filename = os.path.join(
app.config['UPLOAD_FOLDER'],
datetime.date.today().strftime('%y%m%d'),
req... | 34,684 |
def test_true():
"""True case test."""
assert two_sum([1, 2, 5, 6, 7], 9) == [1, 4]
assert two_sum_dict([1, 2, 5, 6, 7], 9) == [1, 4] | 34,685 |
def heg_kfermi(rs):
""" magnitude of the fermi k vector for the homogeneous electron gas (HEG)
Args:
rs (float): Wigner-Seitz radius
Return:
float: kf
"""
density = (4*np.pi*rs**3/3)**(-1)
kf = (3*np.pi**2*density)**(1./3)
return kf | 34,686 |
def stock_em_jgdy_detail():
"""
东方财富网-数据中心-特色数据-机构调研-机构调研详细
http://data.eastmoney.com/jgdy/xx.html
:return: 机构调研详细
:rtype: pandas.DataFrame
"""
url = "http://datainterface3.eastmoney.com/EM_DataCenter_V3/api/JGDYMX/GetJGDYMX"
params = {
"js": "datatable8174128",
"tkn": "e... | 34,687 |
def intersect_with_grid(int_coords, fill=False):
"""
Args:
- int_coords: projected coordinates to be used for intersection
- fill: whether to include the interior of the intersected cells. I.e.
if the coords of a box are provided and intersect with 0,0 and 4,4,
this would inc... | 34,688 |
def safe_epsilon_softmax(epsilon, temperature):
"""Tolerantly handles the temperature=0 case."""
egreedy = epsilon_greedy(epsilon)
unsafe = epsilon_softmax(epsilon, temperature)
def sample_fn(key: Array, logits: Array):
return jax.lax.cond(temperature > 0,
(key, logits), lambda tup:... | 34,689 |
def get_object_from_controller(object_type, object_name, controller_ip, username, password, tenant):
"""
This function defines that it get the object from controller or raise
exception if object status code is less than 299
:param uri: URI to get the object
:param controller_ip: ip of controller
... | 34,690 |
def dn2rdn_Hyspex(rdn_image_file, dn_image_file, radio_cali_file, acquisition_time):
""" Do Hyspex radiometric calibration.
Arguments:
rdn_image_file: str
Radiance image filename.
dn_image_file: str
Hyspex DN image filename.
radio_cali_file: str
Hyspex... | 34,691 |
def scale_reshaping(scale: np.ndarray,
op2d: common.BaseNode,
kernel_channel_mapping: DefaultDict,
in_channels: bool = True) -> np.ndarray:
"""
Before scaling a kernel, the scale factor needs is reshaped to the correct
dimensions. This is a functio... | 34,692 |
def process_metadata(split_name, caption_data, image_dir):
"""Process the captions and combine the data into a list of ImageMetadata.
Args:
split_name: A train/test/val split name.
caption_data: caption file containing caption annotations.
image_dir: Directory containing the image files.
R... | 34,693 |
def test_circuits_update_interface(runner, circuit, interface):
""" Test updating a circuit's Z side interface """
with runner.isolated_filesystem():
result = runner.run('circuits update -i {0} -Z {1}'.format(
circuit['name'], interface['id']
))
assert_output(result, ['Updat... | 34,694 |
def add_new_exif(info):
"""
创建exif记录(从表)
:param info:
:return:
"""
return ExifInfo(make=info.get('Image Make'),
model=info.get('Image Model'),
orientation=info.get('Image Orientation'),
date_original=info.get('EXIF DateTimeOriginal'),
... | 34,695 |
def test_bad_file():
""" Dies on bad file """
bad = random_string()
rv, out = getstatusoutput(f'{RUN} {bad}')
assert rv != 0
assert re.search(f"No such file or directory: '{bad}'", out) | 34,696 |
def prefetch_input_data(reader,
file_pattern,
is_training,
batch_size,
values_per_shard,
input_queue_capacity_factor=16,
num_reader_threads=1,
shard_que... | 34,697 |
def find_rst(
aligntk_path,
pairs,
images,
mask,
output,
rotation,
max_res,
scale,
tx,
ty,
summary):
""" Wrapper for find_rst in aligntk.
Args:
aligntk_path: Path to aligntk bins
pairs: Path to a *.lst file with lines in form of "{src} {tgt} {src}_{t... | 34,698 |
def save_result_subj_task(res, subject, task, resultdir=None):
"""
Save partial (subj,task) results data from a classifier
inputs:
res - results output of do_subj_classification
subject - subject id - sid00[0-9]{4}
task - name of task from tasks
resultdir - directory for resul... | 34,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.