content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def opInsertTestTable(dataDict):
"""
同步 testtabel 表新插入的数据
dataDict dict: 数据值
"""
# 通过 restfull API 发送cypher 语句,把数据同步到neo4j
dataDict = valueDict['data']
cypher = "Merge (n:Person{id:\"%s\", age:\"%s\"})" % (dataDict['id'], dataDict['age'])
payload = {
"statements": [{
... | 66,800 |
def get_connection_mask(a):
"""
Given a subset mask, return the appropriate
vispy.Line connection array for the subset.
Only the points in the subset are plotted, so
return an array where each group of connected
points in the array is terminated by a FALSE
"""
new_mask = []
for k,g ... | 66,801 |
def escape_path(value: bytes) -> str:
"""
Take a binary path value, and return a printable string, with special
characters escaped.
"""
def human_readable_byte(b: int) -> str:
if b < 0x20 or b >= 0x7F:
return "\\x{:02x}".format(b)
elif b == ord(b"\\"):
return... | 66,802 |
def fdumpit(object_: Any,
view_: AnyStr = 'vertical',
colors: Union[bool, str] = False,
all_: bool = True) -> AnyStr:
"""
Export object to string.
:param object_: Any kind of python object.
:param view_: Choose between Vertical or Table view
:param colors: Should... | 66,803 |
def opval_ADO(key, value):
"""A helper function for parse_branch."""
operation, value = value
return "[%s] %s %s" % (key, cmpcasts_ADO[operation], quoted_field(value)) | 66,804 |
def graphMethod(funcOrFlags=0, delegateTo=None):
"""Declare a GraphObject method as on-graph.
Use as a decorator, for example:
class Example(GraphObject):
@graphMethod
def X(self):
return self.Y()
@graphMethod(Settable)
def Y(self):
... | 66,805 |
def get_config(key: str = "", fallback: Union[str, Dict] = None, envvar_prefix: str = "DOING_CONFIG_"):
"""
Finds and reads doing configuration file.
Note you can overwrite a value in the config by setting an environment variable:
```python
import os
os.environ["DOING_TEAM"] = "my team"
f... | 66,806 |
def test_example_1(x, outcome, function):
""" Tests that the example 1 provided in the documentation works (positive integer) """
# if x == 'foo' and function == function_input_mini_lambda:
# print('uncomment and put your breakpoint here to debug')
if outcome is True:
function(x)
else:... | 66,807 |
def get_data(filters: typing.List[dict], threads=1, async=False, processor: typing.Callable = None):
"""
Get async data for a list of filters. Works only for the historical API
:param filters: a list of filters
:param threads: number of threads for data retrieval
:param async: if True, return queue.... | 66,808 |
def get_packets(data: Union[bytes, memoryview], packet_type: Optional[str] = None) -> Iterator[Packet]:
"""
Get all the packets of a particular type. If no type is given, returns all packets.
WARNING: packets are generated with non-header data as a `memoryview`.
:param data: The data to search throug... | 66,809 |
def get_row_col_matrix(row_index_set, col_index_set):
"""
Returns the resulting matrix when using a row and column of indices (list of tuples)
row_index_set: the index set that would be taken from wells A-H (or equivalent) on that plate. Should be dim 8 or 16.
col_index_set: the index set that would be ... | 66,810 |
def on_exam_finish(s):
"""
This method finishes exam when either time is up or educator requests so.
:param s: It is for handling class structure.
:return:
"""
def on_exam_finish_confirm(self, dt):
"""
This method changes exam's status to finished through server.
:param ... | 66,811 |
def temporal_centroid(alpha, bin_freqs):
"""Spectral centroid of the temporal spectrum.
Calculated as the weighted average of analysis bin magnitudes.
Note, temporal centroid depends on the spec frequency bins/scale (as well as
the choice of `aggr_func` if custom spec is used). That is, temporal centr... | 66,812 |
def _obtain_input_shape(
input_shape,
default_size,
min_size,
data_format,
require_flatten):
"""Internal utility to compute/validate an ImageNet model's input shape.
Args:
input_shape: either None (will return the default network input shape),
or a user-provided shape ... | 66,813 |
def get_auction_lores(auctions):
"""return lore for each auction, use asyncio.to_thread for this"""
return [get_safe_content(i["item_lore"]) for i in auctions] | 66,814 |
def abort():
"""
Attempt to kill all processes that might be related to a malaria attack
"""
with fab.settings(warn_only=True):
fab.run("kill $(pgrep malaria)", )
# TODO - should only be done when bridging?
fab.run("kill $(pgrep mosquitto)") | 66,815 |
def create_update_dashboard(orgname=None, profile="grafana", **kwargs):
"""
Create or update a dashboard.
dashboard
A dict that defines the dashboard to create/update.
overwrite
Whether the dashboard should be overwritten if already existing.
orgname
Name of the organizati... | 66,816 |
def raw_reward_threshold(threshold):
"""Return a reward processor that cut off at a threshold."""
def fn(metadata):
if metadata['raw_reward'] > threshold:
return 1.
elif metadata['raw_reward'] > 0:
return -1
return metadata['raw_reward']
return fn | 66,817 |
def force_fluctuation(agent):
"""Truncated normal distribution with standard deviation of 3."""
i = agent.indices()
magnitude = tn.rvs(-0.3, 0.3, loc=0, scale=agent.std_rand_force[i], size=i.size)
angle = np.random.uniform(0, 2 * np.pi, size=i.size)
force = magnitude * np.array((np.cos(angle), np.si... | 66,818 |
def O2_conv(S, T, P, O2conc):
"""sal, temp, press, oxy conc"""
sigmatheta_pri = sw.eos80.dens(s=S, t=T, p=P)
density = sigmatheta_pri / 1000
O2conc = O2conc / density
return O2conc | 66,819 |
def parse_input(input_):
"""Convert the puzzle input in a list of "Line" objects."""
lines = []
for l in input_.splitlines():
tokens = l.split('->')
startpos, endpos = tokens[0], tokens[1]
startpos = startpos.split(',')
x1 = int(startpos[0])
y1 = int(startpos[1])
... | 66,820 |
def ShortSetNames(set_names_nparray, dbg_lvl=0):
""" Using a table with rules, shorten the names of these sets
Args:
set_names_nparray (numpy.ndarray): Array of string, unique set names from exps file
Returns:
set_names_nparray (numpy.ndarray): Edited set Names to be
in the for... | 66,821 |
def generate_box(anchors, color = [], rotate = False):
"""
input:
Anchor (n, 7)
color: if true then the generated box will display red, otherwise black
"""
anchor_boxes = []
for anchor in tqdm(anchors):
anchor[3:-1] = np.array([anchor[4],anchor[3],anchor[5]])
box = np.zeros(s... | 66,822 |
def test_load_as_matrix_success():
"""
Test successfully passing ``load_as_matrix`` and invoking implementation
defined ``_load_as_matrix`` method (no ``matrix`` property on data elem).
"""
m_elem = mock.MagicMock(spec_set=DataElement)
crop_bb = AxisAlignedBoundingBox([0, 0], [1, 1])
m_read... | 66,823 |
def load_xps(save_as):
"""Load `xps` (as a `list`) from given dir."""
save_as = Path(save_as).expanduser()
files = [d / "xp" for d in uplink.list_job_dirs(save_as)]
if not files:
raise FileNotFoundError(f"No results found at {save_as}.")
def load_any(filepath):
"""Load any/all `xp's... | 66,824 |
def process_target_counters():
"""
This function extracts the target counters and converts them to the appropriate format using the
convert_target_counters function. It then converts the "object" dtype records of the output dataframe (df2) to
"numeric" dtype in order for the df2 to have the same type o... | 66,825 |
def read_ID_and_GO_multiCols(file_name, name_col, GO_col,
header_rows = 0, split_char = "\t"):
"""
This opens the file and read GO classes and Gene Identifier
Everything is stored as a dict that has Gene ID as key
GO classes are as a list (or array, how is it called...)
Bug Genera... | 66,826 |
def build_pruned_tree(tree, cases):
"""
Build new tree with only the specifiied cases
Parameters
----------
tree : List[...]
the sidebar tree
cases : List[int]
the cases to keep
Returns
-------
tree_final : List[...]
the updated sidebar tree
Examples
... | 66,827 |
def filter_median(im, filter_size):
"""
Abstracted media filter function that catches warnings about image type conversion (float to uint8)
Args:
im (ndarray): image
filter_size (int): size of disk filter
Returns:
uint8 ndarray: filtered image
"""
with warnings.catch_warnings():
# catche... | 66,828 |
def comp_profit_inc_div_drp(price, price_bought_list, vol_list, DRP_list, admin_fee_list, div):
"""
return current market value - total cost of buying this stock, after deduct admin fees, with DRP and div
"""
vol_DRP_list = [i[0] + i[1] for i in zip(vol_list, DRP_list)]
return comp_market_value(pric... | 66,829 |
def get_migration_table(environment, Base):
"""Get the migration table for a given environment."""
class MigrationTable(Base):
__tablename__ = "migrations_{}".format(environment)
id = Column(String(100), primary_key=True)
commit_time = Column(
TIMESTAMP,
onupdate... | 66,830 |
def get_rotation(box):
"""Return the rotation of a rectangle contour based on the slope of one of its long side."""
x1 = 0
x2 = 0
# Take the first three vertices and calculate side lengths of the right angle triangle they form
d1 = math.sqrt(pow((box[0][0]-box[1][0]),2)+pow((box[0][1]-box[... | 66,831 |
def test_paragraph_series_m_hs_ol_t_nl_i2_t_nl_hs():
"""
Test case: Ordered list text newline indent of 2 text new line setext heading
was: test_list_blocks_256haa
"""
# Arrange
source_markdown = """1. abc
foo
---
"""
expected_tokens = [
"[olist(1,1):.:1:3:: ]",
"... | 66,832 |
def add_users(auth_salt):
"""
"""
users = read_json_file(filename="data_users.json")
for usr in users:
# prepare hash for password
t1 = hashlib.sha1()
t1.update(usr["password"].encode("utf8"))
pwd_hash = t1.hexdigest()
# password with salt
pwd_salt = "%s... | 66,833 |
def resample_with_sepconv(feat,
target_width,
target_num_filters,
use_native_resize_op=False,
batch_norm_activation=nn_ops.BatchNormActivation(),
data_format='channels_last',
... | 66,834 |
def fits_table_source(url, extension):
"""
url -- fits file to open (local filename or URL)
extension -- name or number of extension (HDU)
"""
header = fitsio.read_header(url, ext=extension)
n_entries = header["NAXIS2"]
fitsfile = fitsio.FITS(url, iter_row_buffer=10000)
table = fitsfil... | 66,835 |
def authenticate():
"""Authenticate user.
Since this goes via modifying the app, undo modifications afterwards.
"""
async def logged_in_user(token=None): # pylint: disable=unused-argument
"""Fake active user."""
return UserInDB(**config.fake_users_db["johndoe@example.com"])
app.d... | 66,836 |
def calculate_transit_duration_in_days(t, period, transit_times, duration):
"""Return estimate for transit duration in days"""
# Difference between (time series duration / period) and epochs
transit_duration_in_days_raw = (
duration * calculate_stretch(t, period, transit_times) * period
)
... | 66,837 |
def add_metadata_element_to_xml(root, md_element, md_fields):
"""
helper function to generate xml elements for a given metadata element that belongs to
'hsterms' namespace
:param root: the xml document root element to which xml elements for the specified
metadata element needs to be added
:para... | 66,838 |
def add_image_unit(header, history=True):
"""
Add unit of image to header.
Parameters
----------
header : astropy.io.fits.Header
Header object in which image type is to be changed.
history : bool, optional
If `True`, add history of keyword modification to `header`.
"""
... | 66,839 |
def display_astyle_version(exe):
""" Display the version number from the AStyle executable.
This will not display when run from a Windows editor.
"""
astyle = [exe, "--version"]
retval = subprocess.call(astyle)
if retval:
print("Bad astyle return: " + str(retval))
os._exit(1) | 66,840 |
def processing_ends(vass: VoiceAssistant) -> None:
"""Do when NLP ends."""
pixel_ring.off()
global ring_state
ring_state = PixelRingState.off | 66,841 |
def profile(request, user_id):
"""
Function that enables one to see their profile
"""
title = "Profile"
profile = Profile.objects.get(user_id=user_id)
biz = Business.objects.filter(user_id=user_id).all()
hood = Neighbour.objects.filter(user_id=user_id).all()
users = User.objects.get(id=u... | 66,842 |
def get_binomial_filter_1d(size):
"""
This produces a 1d spatial filter with binomial coefficients
"""
assert size > 1
kernel = np.array([0.5, 0.5])
for i in range(size - 2):
kernel = convolve(np.array([0.5, 0.5]), kernel)
return kernel | 66,843 |
def get_hostname() -> str:
"""
Get the current hostname, or fall back to localhost.
"""
try:
return socket.getfqdn()
except:
return 'localhost' | 66,844 |
def assert_values_not_almost_equal(val1, val2, **kwargs):
""" Compare 2 objects containing HasTraits and assert they are not
almost equal.
Parameters
----------
val1, val2 : object
Non-HasTraits values to compare, typically attributes of a
HasTraits class.
kwargs : dict
... | 66,845 |
def format_design_table(designs: pd.DataFrame,
minimum_detectable_iroas: float,
minimum_lift_in_response_metric: float = 10.0,
minimum_revenue_covered_by_treatment: float = 5.0):
"""Formats a table with the output designs.
Args:
designs: t... | 66,846 |
def SerializeEntries(entries):
"""Serializes given triplets of python and wire values and a descriptor."""
output = []
for python_format, wire_format, type_descriptor in entries:
if wire_format is None or (python_format and
type_descriptor.IsDirty(python_format)):
wire_fo... | 66,847 |
def get_anilist(username: str, **vars) -> List[Tuple[int,str]]:
"""
Gets an anilist list with a username.
"""
measure = Measure()
raw = get_raw_anilist(username, **vars)
data = sort_anilist(raw)
logger.info(f'[get] Got data from anilist in {measure()}s.')
return data | 66,848 |
async def SendGlobalLog(bot, event, timestamp=None, author=None):
"""
Essentially a function that will take the passed args, and then send the message to our global log channel in our support discord
If a timestamp is not passed in, the bot will send a message to the log channel, get the dynamic timestamp f... | 66,849 |
def get_metadata_wikidata(person_complete_name):
"""
Get birth date, gender and nationality (expressed with country name) for the given person
:param person_complete_name: Person you are interested in
:return:
"""
entities_ids = get_wikidata_entities(person_complete_name)
person_metadata = {... | 66,850 |
def evaluate_general(
result_paths, interactions_paths, events_paths, metrics,
x_axis_name, x_axis_type,
group_key, group_key_name_func, sort_keyfunc=None,
xticks=[],
K=10):
"""
Return a 3D table
group_key: the legend part
metrics: the y axis
x_axis_name, sort... | 66,851 |
def test_main_interrupted():
"""Work interrupted: message handler notified properly, return code in 1."""
with patch.object(logsetup, 'message_handler') as mh_mock:
with patch('charmcraft.main.Dispatcher.run') as d_mock:
d_mock.side_effect = KeyboardInterrupt
retcode = main(['cha... | 66,852 |
def _get_group_discount_offer(basket, balance, group_items, num_items_offer, price_offer):
"""
Update the balance and the basket for a Group discount offer.
"""
group_items = [item for item in group_items if item in basket]
offers_sold = sum([basket[item] for item in group_items])//num_items_offer... | 66,853 |
def calculate_acc(mode: enums.GameMode, osu_score: dict, exclude_misses: bool = False):
""" Calculate the accuracy using formulas from https://osu.ppy.sh/wiki/Accuracy """
# Parse data from the score: 50s, 100s, 300s, misses, katu and geki
keys = ("count_300", "count_100", "count_50", "count_miss", "count_k... | 66,854 |
def softmax_kernel_transformation(data,
is_query,
projection_matrix=None,
numerical_stabilizer=0.000001):
"""Computes random features for the softmax kernel using FAVOR+ mechanism.
Computes random features for the... | 66,855 |
def global_bspline_interpolation_first_derivatives(
fit_points: List[Vec3],
derivatives: List[Vec3],
degree: int,
t_vector: Sequence[float]) -> Tuple[List[Vec3], List[float]]:
"""
Interpolate the control points for a B-spline by global interpolation from fit points and
1st de... | 66,856 |
def dashboard(request):
"""
Render HTML for dashboard/metrics view.
"""
# Datasets
dataset_count = Dataset.objects.all().count()
datasets_without_descriptions = [(unquote(dataset['name']), dataset['slug']) for dataset in Dataset.objects.filter(description='').values('name', 'slug')]
dataset... | 66,857 |
def test_list_reports_empty(staff_client, private_channel):
"""List reported content when there is none"""
url = reverse("channel-reports", kwargs={"channel_name": private_channel.name})
resp = staff_client.get(url)
assert resp.status_code == status.HTTP_200_OK
assert resp.json() == [] | 66,858 |
def main():
"""run calculator"""
calculator.main() | 66,859 |
def read_csv_as_list_dict(filename, separator, quote):
"""
Inputs:
filename - name of CSV file
separator - character that separates fields
quote - character used to optionally quote fields
Output:
Returns a list of dictionaries where each item in the list
corresponds to a ... | 66,860 |
def Prepare(benchmark_spec):
"""Install Nginx on the server and a load generator on the clients.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
"""
clients = benchmark_spec.vm_groups['clients']
server = benchmark_spec.vm_groups['server'... | 66,861 |
async def async_setup_entry(
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], bool], None],
) -> None:
"""Set up BSBLan device based on a config entry."""
driver: MagiQtouch_Driver = hass.data[DOMAIN][entry.entry_id]
await driver.login()
await hass.asy... | 66,862 |
def _getname(node: Node):
"""Get mpiexec name for forward and frechet."""
if node.step is not None:
return f"_it{node.iter:05d}_ls{node.step:05d}"
else:
return f"_it{node.iter:05d}" | 66,863 |
def get_plugin(plugin_name):
"""
_get_plugin_
Get the deploy plugin requested from the factory
"""
factory = pluggage.registry.get_factory(
'deploy',
load_modules=['cirrus.plugins.deployers']
)
return factory(plugin_name) | 66,864 |
def get_instance_identification():
"""
Gets an identifier for an instance. Gets EC2 instanceId if possible, else local hostname
"""
instance_id = socket.gethostname()
try:
# "special tactics" for getting instance data inside EC2
instance_data = subprocess.check_output(
[... | 66,865 |
def shift_display_orders(at_display_order):
"""
shift the display order in hpo_site_id_mappings_table when a new HPO is to be added.
:param at_display_order: index where the display order
:return:
"""
q = SHIFT_HPO_SITE_DISPLAY_ORDER.format(
display_order=at_display_order,
hpo_si... | 66,866 |
def perCameraVisibility(q=1,c="name",ex=1,hi=1,rm=1,ra=1,rc=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/perCameraVisibility.html
-----------------------------------------
perCameraVisibility is NOT undoable, queryable, and NOT editable.
The perCameraVisibility command crea... | 66,867 |
def calculate_postrior_GP(lmbda_q2, mu_omega_int_points, kappa_X, mu_omega_X,
kappa_int_points, num_integration_points, T, Kss_inv, noise,
ks_X, ks_int_points):
"""
This method calculates the mean and the covariance of the GP in the inducing points.
:param... | 66,868 |
def main():
"""Manually input a JWT token to be validated."""
token = input("Enter an access token to validate: ")
validated_jwt = validate_eve_jwt(token)
print("\nThe contents of the access token are: {}".format(validated_jwt)) | 66,869 |
def get_species_list(request):
"""
Get list of distinct species labels
"""
species = models.ImageSet.objects.order_by().values_list('species', flat=True).distinct()
return Response(sorted(list(species))) | 66,870 |
def encode(value):
"""
Encode Swarm.
:param bytes value: a decoded content
:return: the encoded content
:rtype: str
"""
mhash = multihash.encode(multihash.from_hex_string(value), 'keccak-256')
return make_cid(1, 'swarm-manifest', mhash).buffer | 66,871 |
def main():
"""
Main method that collects the BGP router-id from the spine switches using the native model
"""
bgp_rtrid_filter = """
<System xmlns="http://cisco.com/ns/yang/cisco-nx-os-device">
<bgp-items>
<inst-items>
<dom-items>
<Dom-list>
<... | 66,872 |
def process_raw_data(raw_data_filepath: str, processed_data_filepath: str) -> None:
"""
Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
raw_data = pd.read_csv(raw_data_filepath, ... | 66,873 |
def scrape(web_url, pdf, pg_no):
"""
Web scraping logic
"""
try:
page = urllib2.urlopen(web_url, timeout=200)
except http.client.RemoteDisconnected:
print("Error 404: {} not found.".format(web_url))
return 0
soup = BeautifulSoup(page, "html.parser")
di... | 66,874 |
def _get_best_corrs(pvals_file):
"""extract sig motifs
"""
with h5py.File(pvals_file, "r") as hf:
keys = sorted(hf["pvals"].keys())
for key_idx in range(len(keys)):
key = "pvals/{}/correlations".format(keys[key_idx])
# get hgnc_ids and corr values
with h5py.File(pvals_f... | 66,875 |
def access_batch_data(
reader_leader,
reader_name,
trainer_env,
input_queue,
out_queue,
cache_capcity,
error_queue,
):
"""
Run DataAccesser in a seperated process
"""
try:
a = DataAccesser(
reader_leader,
reader_name,
trainer_env,
... | 66,876 |
def pid_control(output, p, i, d, objCoord, centerCoord):
""" Returns the PID error based on the current PID values,
Object Coords and Center Coords
Keyword arguments:
output -- output variable
p -- proportional controller variable
i -- integral controller variable
d -- differential controller variab... | 66,877 |
def __getslice__(*args, **kwargs): # real signature unknown
""" getslice(a, b, c) -- Same as a[b:c]. """
pass | 66,878 |
def find_stddev_from_stream(p=100):
"""
O(1) time and space
"""
mean = None
total_sum = 0
total_square = 0
nb = 0
stddev = 0
while True:
data = stream(p)
nb+=1
if not mean:
mean = data
else:
mean = (mean*(nb-1) + data)/(nb)
stddev = (
(total_square+data**2)/nb
- 2*(total_sum+data)/nb
... | 66,879 |
def l2_regularization(params):
"""Computes l2 regularization term for parameters."""
return jax.tree_util.tree_reduce(op.add, l2_norm(params)) | 66,880 |
def load(dpath):
"""
Loads data from directory.
Arguments:
dpath -- directory
Returns:
train_set_x_orig -- train set features
train_set_y_orig -- train set labels
test_set_x_orig -- train set features
test_set_y_orig -- test set labels
classes -- list of classes
"""
if... | 66,881 |
def clean_rxn_smis_50k_all_phases(
input_file_prefix: str = "schneider50k",
output_file_prefix: str = "50k_clean_rxnsmi_noreagent_allmapped",
input_root: Optional[Union[str, bytes, os.PathLike]] = None,
output_root: Optional[Union[str, bytes, os.PathLike]] = None,
lines_to_skip: Optional[int] = 1,
... | 66,882 |
def _extended_image(catalog, reference_cube):
"""Reprojects and adds extended source images to a larger survey image.
"""
# This import is here instead of at the top to avoid an ImportError
# due to circular dependencies
from ..datasets import fetch_fermi_extended_sources
from ..data import Spec... | 66,883 |
def _read_epoch_encoder_file(metadata):
"""
Read in epochs from the ``epoch_encoder_file`` in ``metadata`` and return a
dataframe.
"""
if metadata.get('epoch_encoder_file', None) is None:
return None
else:
# data types for each column in the file
dtypes = {
... | 66,884 |
def get_submission_data_from_pushshift(raw_submission):
"""Creates a submission object from a Pushshift Submission JSON
Parameters:
raw_submission (dict): Pushshift Submission instance
Returns:
dict: object with information about a submission, like body, author or URL
"""
if (not 'selfte... | 66,885 |
def nonulls(df):
""" a function to drop all NaNs in a DataFrame"""
df.dropna(how='any') | 66,886 |
def generate_figure_metric_plotly(df, metric, stats):
"""
Generate interactive bar plot across sites
:param df:
:param metric:
:param stats:
:return:
"""
# Sort values per vendor
site_sorted = df.sort_values(by=['vendor', 'model', 'site']).index.values
vendor_sorted = df['vendor'... | 66,887 |
def google_webResults(input):
"""
google_webResults
"""
return google_webResults_soup(input) | 66,888 |
def preview_image(image_array, normalize_by="volume", cmap=None, figsize=(12, 12), threshold=None):
"""
Display three orthogonal slices of the given 3D image.
image_array is assumed to be of shape (H,W,D)
If a number is provided for threshold, then pixels for which the value
is below the threshold... | 66,889 |
def pyscv_refresh(*args):
"""
pyscv_refresh(py_this) -> bool
"""
return _ida_kernwin.pyscv_refresh(*args) | 66,890 |
def get_auth_header():
"""
Return the authentication header.
"""
return gazu.client.make_auth_header() | 66,891 |
def default_input_mapping(data: Any) -> List[Tensor]:
"""Finds all tensors in a (nested) collection that have the same batch size.
Args:
data: a tensor or a collection of tensors (tuple, list, dict, etc.).
Returns:
A list of all tensors with the same batch dimensions. If the input was alre... | 66,892 |
def get_month_range(months=0, unbounded=False):
"""获取月的开始和结束时间.
:param unbounded: 开区间
"""
today = datetime.date.today()
year_diff = (today.month + months) // 12
end = today.replace(
month=(today.month + months) % 12 + 1,
year=today.year + year_diff,
day=1
) - datet... | 66,893 |
def _load_categories(filepath: str) -> Dict[str, str]:
"""Load data for domain category matching.
Args:
filepath: relative path to csv file containing domains and categories
Returns:
Dictionary mapping domains to categories
"""
data = pkgutil.get_data(__name__, filepath)
if not data:
raise Fil... | 66,894 |
def parse_data(format, need_shape=True, **kwargs):
"""An interface of data parser.
Args:
format (str): Data parser format.
need_shape (bool): Whether need shape attributes. Default: True.
Returns:
obj (dict): Parsed data.
Examples:
{'img_names': ['COCO_val2014... | 66,895 |
def extract_waveforms(ephys_file, ts, ch, t=2.0, sr=30000, n_ch_probe=385, dtype='int16',
offset=0, car=True):
"""
Extracts spike waveforms from binary ephys data file, after (optionally)
common-average-referencing (CAR) spatial noise.
Parameters
----------
ephys_file : st... | 66,896 |
def test_evidencevariable_9(base_settings):
"""No. 9 tests collection for EvidenceVariable.
Test File: evidencevariable-example-Stroke-Thrombolysis-Trialists-2014-2016-IPD-MA-Cohort.json
"""
filename = (
base_settings["unittest_data_dir"]
/ "evidencevariable-example-Stroke-Thrombolysis-T... | 66,897 |
def users_groups(user, user_lookup_field, **kwargs):
"""List all groups belonging to a user"""
user_obj = _okta_get("users", user,
search=f"profile.{user_lookup_field} eq \"{user}\"")
user_id = user_obj["id"]
rv = okta_manager.call_okta(f"/users/{user_id}/groups", REST.get)
rv.s... | 66,898 |
def describe_direct_connect_gateway_associations(associationId=None, associatedGatewayId=None, directConnectGatewayId=None, maxResults=None, nextToken=None, virtualGatewayId=None):
"""
Lists the associations between your Direct Connect gateways and virtual private gateways. You must specify a Direct Connect gat... | 66,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.