content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_uncrustify_tool_plugin_found():
"""Test that the plugin manager can find the uncrustify plugin."""
manager = PluginManager()
# Get the path to statick_tool/__init__.py, get the directory part, and
# add 'plugins' to that to get the standard plugins dir
manager.setPluginPlaces([os.path.join(... | 20,400 |
def objective_func(x, cs_objects, cs_data):
"""
Define the objective function
:param x: 1D array containing the voltages to be set
:param args: tuple containing all extra parameters needed
:return: average count rate for 100 shots
"""
x = np.around(x,2)
try:
flag_range = 0
... | 20,401 |
def getHPELTraceLogAttribute(nodename, servername, attributename):
""" This function returns an attribute of the HPEL Trace Log for the specified server.
Function parameters:
nodename - the name of the node on which the server to be configured resides.
servername - the name of the server w... | 20,402 |
def dispersionTable(adata):
"""
Parameters
----------
adata
Returns
-------
"""
if adata.uns["ispFitInfo"]["blind"] is None:
raise ("Error: no dispersion model found. Please call estimateDispersions() before calling this function")
disp_df = pd.DataFrame({"gene_id": adata... | 20,403 |
def L10_indicator(row):
"""
Determine the Indicator of L10 as one of five indicators
"""
if row < 40:
return "Excellent"
elif row < 50:
return "Good"
elif row < 61:
return "Fair"
elif row <= 85:
return "Poor"
else:
return "Hazard" | 20,404 |
def create_ip_record(
heartbeat_df: pd.DataFrame, az_net_df: pd.DataFrame = None
) -> IpAddress:
"""
Generate ip_entity record for provided IP value.
Parameters
----------
heartbeat_df : pd.DataFrame
A dataframe of heartbeat data for the host
az_net_df : pd.DataFrame
Option ... | 20,405 |
def batch_render(voxel_dir, dest_dir, voxel_processor=None):
"""Render a bunch of voxel tensors stored as npy files in the voxel_dir.
Args:
voxel_dir: A directory containing voxel tensors stored in npy files.
voxel_processor: Function that processes the voxels before rendering
"""
npy_fi... | 20,406 |
def extract_version(version_file_name):
"""Extracts the version from a python file.
The statement setting the __version__ variable must not be indented. Comments after that
statement are allowed.
"""
regex = re.compile(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]\s*(#.*)?$")
with open(version_file_... | 20,407 |
def test_image_dictionary(test_link):
"""
Test if the image_dictionary method returns dictinary in correct
format.
"""
url = 'https://example.com'
filename = 'example.com'
result = {'url' : url, 'filename' : filename}
assert test_link.image_dictionary(url, filename) == result | 20,408 |
def test_invalid_stdout():
"""invalid utf-8 byte in stdout."""
# https://en.wikipedia.org/wiki/UTF-8#Codepage_layout
# 0x92 continuation byte
if six.PY3:
cmd = [python, "-c", "import sys;sys.stdout.buffer.write(b'\\x92')"]
else:
cmd = [python, "-c", "import sys;sys.stdout.write(b'\... | 20,409 |
def batteryRoutine():
""" Creates a routine to the robot thats checks the battery and
sends the robot to the dock station for charging purpouses
"""
# The "get Charged" routine
getChargedTask = Selector("getChargedTask")
# Add the check battery condition
checkBatteryTask = MonitorTask("checkBattery", "batter... | 20,410 |
def get_object_combinations(objects: Collection[Object],
types: Sequence[Type]) -> Iterator[List[Object]]:
"""Get all combinations of objects satisfying the given types sequence."""
sorted_objects = sorted(objects)
choices = []
for vt in types:
this_choices = []
... | 20,411 |
def powerlaw_loglike(data, theta):
"""Return the natural logarithm of the likelihood P(data | theta) for our
model of the ice flow.
data is expected to be a tuple of numpy arrays = (x, y, sigma)
theta is expected to be an array of parameters = (intercept, slope)
"""
x, y, sigma = data
n = ... | 20,412 |
def get_conv(dim=3):
"""Chooses an implementation for a convolution layer."""
if dim == 3:
return nn.Conv3d
elif dim == 2:
return nn.Conv2d
else:
raise ValueError('dim has to be 2 or 3') | 20,413 |
def resolve_path(path, parent=None):
"""Resolves the absolute path of the specified file.
Args:
path (str): Path to resolve.
parent (str): The directory containing ``path`` if ``path`` is relative.
Returns:
The absolute path.
Raises:
IOError: if the path do... | 20,414 |
def notebook_metadata():
"""Attempts to query jupyter for the path and name of the notebook file"""
error_message = "Failed to query for notebook name, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable"
try:
import ipykernel
from notebook.notebookapp import list_runni... | 20,415 |
async def create_mute_role(bot, ctx):
"""Create the mute role for a guild"""
perms = discord.Permissions(
send_messages=False, read_messages=True)
mute_role = await ctx.guild.create_role(
name='Muted', permissions=perms,
reason='Could not find a muted role in the process of muting or... | 20,416 |
def build_request_data(useralias,
req_node):
"""build_request_data
:param useralias: user alias for directory name
:param req_node: simulated request node
"""
if "file" not in req_node:
return None
use_uniques = req_node["unique_names"]
use_file = req_node["... | 20,417 |
def main():
"""
Entry point
"""
parser = argparse.ArgumentParser(COMMAND)
parser.add_argument(
"dbt_dir",
type=str,
help="dbt root directory")
parser.add_argument(
"-b",
"--backup",
action="store_true",
help="When set, take a back up of ex... | 20,418 |
def _get_stmt_lists(self):
"""
Returns a tuple of the statement lists contained in this `ast.stmt`
node. This method should only be called by an `ast.stmt` node.
"""
if self.is_simple():
return ()
elif self.is_body():
return (self.body,)
elif self.is_body_orelse():
r... | 20,419 |
def get_article(name):
"""a general function to get an article, returns None if doesn't exist
"""
article = None
if name is not None:
try:
article = Article.objects.get(name=name)
except Article.DoesNotExist:
pass
return article | 20,420 |
def _CreateNginxConfigMapDir():
"""Returns a TemporaryDirectory containing files in the Nginx ConfigMap."""
if FLAGS.nginx_conf:
nginx_conf_filename = FLAGS.nginx_conf
else:
nginx_conf_filename = (
data.ResourcePath('container/kubernetes_nginx/http.conf'))
temp_dir = tempfile.TemporaryDirectory... | 20,421 |
def abbreviateLab(lab):
"""Lab names are very long and sometimes differ by punctuation or typos. Abbreviate for easier comparison."""
labAbbrev = apostropheSRe.sub('', lab)
labAbbrev = firstLetterRe.sub(r'\1', labAbbrev, count=0)
labAbbrev = spacePunctRe.sub('', labAbbrev, count=0)
return labAbbrev | 20,422 |
def backproject(depth, intrinsics, instance_mask):
""" Back-projection, use opencv camera coordinate frame.
"""
cam_fx = intrinsics[0, 0]
cam_fy = intrinsics[1, 1]
cam_cx = intrinsics[0, 2]
cam_cy = intrinsics[1, 2]
non_zero_mask = (depth > 0)
final_instance_mask = np.logical_and(insta... | 20,423 |
def if_any(
_data,
*args,
_names=None,
_context=None,
**kwargs,
):
"""Apply the same predicate function to a selection of columns and combine
the results True if any element is True.
See Also:
[`across()`](datar.dplyr.across.across)
"""
if not args:
args = (None,... | 20,424 |
def get_inpgen_para_from_xml(inpxmlfile, inpgen_ready=True):
"""
This routine returns an python dictionary produced from the inp.xml
file, which can be used as a calc_parameters node by inpgen.
Be aware that inpgen does not take all information that is contained in an inp.xml file
:param inpxmlfile... | 20,425 |
def confirm_revocation(cert):
"""Confirm revocation screen.
:param cert: certificate object
:type cert: :class:
:returns: True if user would like to revoke, False otherwise
:rtype: bool
"""
return util(interfaces.IDisplay).yesno(
"Are you sure you would like to revoke the followin... | 20,426 |
def main(config_path):
"""main entry point, load and validate config and call generate"""
with open(config_path) as handle:
config = json.load(handle)
http_config = config.get("http", {})
misc_config = config.get("misc", {})
data_config = config.get("data", {})
l... | 20,427 |
def Gaussian(y, model, yerr):
"""Returns the loglikelihood for a Gaussian distribution.
In this calculation, it is assumed that the parameters
are true, and the loglikelihood that the data is drawn from
the distribution established by the parameters is calculated
Parameters
----------
model... | 20,428 |
def clean_us_demographics(us_demographics_spark, spark_session):
"""
Clean data from us_demographics
Args:
us_demographics (object): Pyspark dataframe object
spark_session (object): Pyspark session
Returns:
(object): Pyspark dataframe with cleaned data
"""
s... | 20,429 |
def parse_date(date=None):
"""
Parse a string in YYYY-MM-DD format into a datetime.date object.
Throws ValueError if input is invalid
:param date: string in YYYY-MM-DD format giving a date
:return: a datetime.date object corresponding to the date given
"""
if date is None:
raise Val... | 20,430 |
def torch_save(path, model):
"""Function to save torch model states
:param str path: file path to be saved
:param torch.nn.Module model: torch model
"""
if hasattr(model, 'module'):
torch.save(model.module.state_dict(), path)
else:
torch.save(model.state_dict(), path) | 20,431 |
def status():
""" Incoming status handler: forwarded by ForwardServerProvider """
req = jsonex_loads(request.get_data())
status = g.provider._receive_status(req['status'])
return {'status': status} | 20,432 |
def cli(env, identifier, uri, ibm_api_key):
"""Export an image to object storage.
The URI for an object storage object (.vhd/.iso file) of the format:
swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud
Object Storage
... | 20,433 |
def test_TimeSeriesEvent():
"""Test basic getters and setters."""
event = ktk.TimeSeriesEvent()
event.time = 1
event.name = 'one'
assert event.time == 1
assert event.name == 'one' | 20,434 |
def get_feature_extractor_info():
"""Return tuple of pretrained feature extractor and its best-input image size for the extractor"""
return get_pretrained_feature_extractor(), K_MODEL_IMAGE_SIZE | 20,435 |
def _alembic_connect(db_path: Path, enforce_foreign_keys=True) -> Iterator[Config]:
"""Context manager to return an instance of an Alembic configuration.
The profiles's database connection is added in the `attributes` property, through which it can then also be
retrieved, also in the `env.py` file, which i... | 20,436 |
def compare_flowcorr( self, blocks=False ):
"""
Plots the flowcorr against the slopes data.
Creates two files: a 2d histogram and a point map
if blocks is set to true, then it breaks the result down by block and writes a unified HTML table
"""
if not ( hasattr( self, 'flowcorr') and hasattr( se... | 20,437 |
def nx_find_connected_limited(graph, start_set, end_set, max_depth=3):
"""Return the neurons in end_set reachable from start_set with limited depth."""
reverse_graph = graph.reverse()
reachable = []
for e in end_set:
preorder_nodes = list(
(
networkx.algorithms.trave... | 20,438 |
def hexbyte_2integer_normalizer(first_int_byte, second_int_btye):
"""Function to normalize integer bytes to a single byte
Transform two integer bytes to their hex byte values and normalize
their values to a single integer
Parameters
__________
first_int_byte, second_int_byte : int
inte... | 20,439 |
def wrapAngle(angle):
""" Ensures angle is between -360 and 360
arguments:
angle - float angle that you want to be between -360 and 360
returns:
float - angle between -360 and 360
"""
printDebug("In wrapAngle, angle is " + str(angle), DEBUG_INFO)
if angle >... | 20,440 |
def batch(iterable, batch_size):
"""Yields lists by batch"""
b = []
for i, t in enumerate(iterable):
b.append(t)
if (i + 1) % batch_size == 0:
yield b
b = []
if len(b) > 0:
yield b | 20,441 |
def _save_first_checkpoint(keras_model, custom_objects, config):
"""Save first checkpoint for the keras Estimator.
Args:
keras_model: an instance of compiled keras model.
custom_objects: Dictionary for custom objects.
config: Estimator config.
Returns:
The path where keras model checkpoint is sa... | 20,442 |
def query_pubmed_mod_updates():
"""
:return:
"""
populate_alliance_pmids()
# query_pmc_mgi() # find pmc articles for mice and 9 journals, get pmid mappings and list of pmc without pmid
# download_pmc_without_pmid_mgi() # download pmc xml for pmc without pmid and find their article type
... | 20,443 |
def build_reference_spectrum_list_from_config_file(config):
"""
Read reference spectrum file glob(s) from configuration file to create
and return a list of ReferenceSpectrum instances.
:param config: configparser instance
:return: list of ReferenceSpectrum instances
"""
log = logging.getLog... | 20,444 |
def make_window(signal, sample_spacing, which=None, alpha=4):
"""Generate a window function to be used in PSD analysis.
Parameters
----------
signal : `numpy.ndarray`
signal or phase data
sample_spacing : `float`
spacing of samples in the input data
which : `str,` {'welch', 'han... | 20,445 |
def set_units(
df: pd.DataFrame, units: Dict[str, Union[pint.Unit, str]]
) -> pd.DataFrame:
"""Make dataframe unit-aware. If dataframe is already unit-aware, convert to specified
units. If not, assume values are in specified unit.
Parameters
----------
df : pd.DataFrame
units : Dict[str, Un... | 20,446 |
def makeTokensTable(medidasTokens__instance, table_dir="/home/r/repos/artigoTextoNasRedes/tables/",fname="tokensInline.tex",tag=None):
"""Tabela de medidas de tokens TTM"""
tms=medidasTokens__instance
mvars=("tokens",
"tokens_diff",
"knownw",
"knownw_diff",
"s... | 20,447 |
def address_repr(buf, reverse: bool = True, delimit: str = "") -> str:
"""Convert a buffer into a hexlified string."""
order = range(len(buf) - 1, -1, -1) if reverse else range(len(buf))
return delimit.join(["%02X" % buf[byte] for byte in order]) | 20,448 |
def _highlight(line1, line2):
"""Returns the sections that should be bolded in the given lines.
Returns:
two tuples. Each tuple indicates the start and end of the section
of the line that should be bolded for line1 and line2 respectively.
"""
start1 = start2 = 0
match = re.search(r'\S', line1) # ig... | 20,449 |
def test_memtable_flush_writer_blocked():
"""verify flush writer blocked"""
analyzer = recs.Engine()
stage = recs.Stage(
name="MemtableFlushWriter",
pending=0,
active=0,
local_backpressure=0,
completed=0,
blocked=1,
all_time_blocked=0,
)
re... | 20,450 |
def get_comrec_build(pkg_dir, build_cmd=build_py):
""" Return extended build command class for recording commit
The extended command tries to run git to find the current commit, getting
the empty string if it fails. It then writes the commit hash into a file
in the `pkg_dir` path, named ``COMMIT_INFO.... | 20,451 |
def get_detected_objects_new(df, siglim=5, Terr_lim=3, Toffset=2000):
"""
Get a dataframe with only the detected objects.
:param df: A DataFrame such as one output by get_ccf_summary with N > 1
:param siglim: The minimum significance to count as detected
:param Terr_lim: The maximum number of standa... | 20,452 |
def test_refresh_repositories(nexus_mock_client):
"""
Ensure the method retrieves latest repositories and sets the class
attribute.
"""
repositories = nexus_mock_client.repositories.raw_list()
x_repositories = nexus_mock_client._request.return_value._json
nexus_mock_client._request.assert_c... | 20,453 |
def cmp(a, b):
"""
Python 3 does not have a cmp function, this will do the cmp.
:param a: first object to check
:param b: second object to check
:return:
"""
# convert to lower case for string comparison.
if a is None:
return -1
if type(a) is str and type(b) is str:
a... | 20,454 |
def pe(cmd, shell=True):
"""
Print and execute command on system
"""
ret = []
for line in execute(cmd, shell=shell):
ret.append(line)
print(line, end="")
return ret | 20,455 |
def create_photo(user_id, text: str, greencolor: bool): # color: tuple(R,G,B)
"""
:param user_id: int or str
:param text: str
:param greencolor: bool
True = зеленый (204, 255, 204)
False = серый (240, 238, 237)
"""
color = (204, 255, 204)
if not greencolo... | 20,456 |
def mark_production_ready(config, incident, team, artifact, tag, url):
"""
Manually mark image as production ready.
"""
pierone_url = set_pierone_url(config, url)
registry = get_registry(pierone_url)
image = DockerImage(registry, team, artifact, tag)
if incident.startswith("INC-"):
#... | 20,457 |
def crop(image):
"""
Method to crop out the uncessary white parts of the image.
Inputs:
image (numpy array): Numpy array of the image label.
Outputs:
image (numpy array): Numpy array of the image label, cropped.
"""
image = ImageOps.invert(image)
imageBox = image.getbbox()... | 20,458 |
def test(dataset):
"""Test the solving algorithm against a dataset"""
reader = csv.reader(dataset)
total_problems = sum(1 for row in reader)
solved_problems = 0
dataset.seek(0)
print_progress(solved_problems, total_problems)
try:
for row in reader:
problem = row[0]
... | 20,459 |
def copy_param(code, target, source):
"""
Copy a parameter from source reg to preferred slot in the target reg.
For params in slot 0, this is just and add immediate.
For params in other slots, the source is rotated.
Note that other values in the source are copied, too.
"""
if source[SLOT] != 0:
code.a... | 20,460 |
def all_pairs_normalized_distances(X):
"""
We can't really compute distances over incomplete data since
rows are missing different numbers of entries.
The next best thing is the mean squared difference between two vectors
(a normalized distance), which gets computed only over the columns that
tw... | 20,461 |
def forward_pass(model, target_angle, mixed_data, conditioning_label, args):
"""
Runs the network on the mixed_data
with the candidate region given by voice
"""
target_pos = np.array([
FAR_FIELD_RADIUS * np.cos(target_angle),
FAR_FIELD_RADIUS * np.sin(target_angle)
])
data, ... | 20,462 |
async def get_event_by_code(code: str, db: AsyncSession) -> Event:
"""
Get an event by its code
"""
statement = select(Event).where(Event.code == code)
result = await db.execute(statement)
event: Optional[Event] = result.scalars().first()
if event is None:
raise HTTPException(
... | 20,463 |
def get(name):
"""Returns an OpDef for a given `name` or None if the lookup fails."""
with _sync_lock:
return _registered_ops.get(name) | 20,464 |
def angle_detect_dnn(img, adjust=True):
"""
文字方向检测
"""
h, w = img.shape[:2]
ROTATE = [0, 90, 180, 270]
if adjust:
thesh = 0.05
xmin, ymin, xmax, ymax = int(thesh * w), int(thesh * h), w - int(thesh * w), h - int(thesh * h)
img = img[ymin:ymax, xmin:xmax] ##剪切图片边缘
in... | 20,465 |
def get_correct_line(df_decisions):
"""
The passed df has repeated lines for the same file (same chemin_source).
We take the most recent one.
:param df_decisions: Dataframe of decisions
:return: Dataframe without repeated lines (according to the chemin_source column)
"""
return df_decisions.... | 20,466 |
def fix_1(lst1, lst2):
"""
Divide all of the elements in `lst1` by each element in `lst2`
and return the values in a list.
>>> fix_1([1, 2, 3], [0, 1])
[1.0, 2.0, 3.0]
>>> fix_1([], [])
[]
>>> fix_1([10, 20, 30], [0, 10, 10, 0])
[1.0, 2.0, 3.0, 1.0, 2.0, 3.0]
"""
out = []
... | 20,467 |
def sleep_countdown(duration, print_step=2):
"""Sleep for certain duration and print remaining time in steps of print_step
Args:
duration (int): duration of timeout
print_step (int): steps to print countdown
Returns
None: Countdown in console
"""
for i in range(duration, 0,... | 20,468 |
def user_wants_upload():
"""
Determines whether or not the user wants to upload the extension
:return: boolean
"""
choice = input("Do you want to upload your extension right now? :")
if "y" in choice or "Y" in choice:
return True
else:
return False | 20,469 |
def has_genus_flag(df, genus_col="mhm_Genus", bit_col="mhm_HasGenus", inplace=False):
"""
Creates a bit flag: `mhm_HasGenus` where 1 denotes a recorded Genus and 0 denotes the contrary.
Parameters
----------
df : pd.DataFrame
A mosquito habitat mapper DataFrame
genus_col : str, default=... | 20,470 |
def record_point_cloud(target, file_name):
"""Record a raw point cloud and print the number of received bytes.
If the record_to_file parameter is set with a path and a filename, the stream will be recorded to this file.
:param target: hostname or IP address of the device
:param file_name: file path to... | 20,471 |
def interact_model(
model_name='124M',
seed=int(_seed()[:-2]),
nsamples=8,
batch_size=1,
length=None,
temperature=1,
top_k=50,
top_p=0.93,
models_dir='models',
):
"""
Interactively run the model
:model_name=124M : String, which model to use
:seed=None : Integer seed f... | 20,472 |
def compass(
size: Tuple[float, float] = (4.0, 2.0),
layer: Layer = gf.LAYER.WG,
port_type: str = "electrical",
) -> Component:
"""Rectangular contact pad with centered ports on rectangle edges
(north, south, east, and west)
Args:
size: rectangle size
layer: tuple (int, int)
... | 20,473 |
def get_service(vm, port):
"""Return the service for a given port."""
for service in vm.get('suppliedServices', []):
if service['portRange'] == port:
return service | 20,474 |
def test_create_mutant_with_cache(binop_file, stdoutIO):
"""Change ast.Add to ast.Mult in a mutation including pycache changes."""
genome = Genome(source_file=binop_file)
# this target is the add_five() function, changing add to mult
target_idx = LocIndex(ast_class="BinOp", lineno=10, col_offset=11, op... | 20,475 |
def write_ef_tree_solution(ef, solution_directory_name,
scenario_tree_solution_writer=scenario_tree_solution_writer):
""" Write a tree solution directory, if available, to the solution_directory_name provided
Args:
ef : A Concrete Model of the Extensive Form (output of create_EF).
... | 20,476 |
async def async_setup_entry(hass, config_entry):
"""Set up AirVisual as config entry."""
entry_updates = {}
if not config_entry.unique_id:
# If the config entry doesn't already have a unique ID, set one:
entry_updates["unique_id"] = config_entry.data[CONF_API_KEY]
if not config_entry.opt... | 20,477 |
def rotation_point_cloud(pc):
"""
Randomly rotate the point clouds to augment the dataset
rotation is per shape based along up direction
:param pc: B X N X 3 array, original batch of point clouds
:return: BxNx3 array, rotated batch of point clouds
"""
# rotated_data = np.zeros(pc.shape, dtyp... | 20,478 |
def alliance_system_oneday(mongohandle, alliance_id, system):
"""find by corp and system - one day"""
allkills = mongohandle.allkills
system = int(system)
timeframe = 24 * 60 * 60
gmtminus = time.mktime(time.gmtime()) - timeframe
cursor = allkills.find({"alliance_id": alliance_id,
... | 20,479 |
def execute(**kwargs):
"""
Airflowのpython_operatorからcall
:param kwargs:
:return:
"""
print('Record ID:{}'.format(kwargs['record_id']))
record_id = int(kwargs['record_id'])
analyzer = LaneAnalyzer()
analyzer.execute(imported_data_id=record_id) | 20,480 |
def slit_select(ra, dec, length, width, center_ra=0, center_dec=0, angle=0):
"""
:param ra: angular coordinate of photon/ray
:param dec: angular coordinate of photon/ray
:param length: length of slit
:param width: width of slit
:param center_ra: center of slit
:param center_dec: center of s... | 20,481 |
def login():
""" Logs in user """
req = flask.request.get_json(force=True)
username = req.get('username', None)
password = req.get('password', None)
user = guard.authenticate(username, password)
ret = {'access_token': guard.encode_jwt_token(user)}
return ret, 200 | 20,482 |
def acor(value, bounds, nparams, nants=None, archive_size=None, maxit=1000,
diverse=0.5, evap=0.85, seed=None):
"""
Minimize the objective function using ACO-R.
ACO-R stands for Ant Colony Optimization for Continuous Domains (Socha and
Dorigo, 2008).
Parameters:
* value : function
... | 20,483 |
def devicePanel(q=1,e=1,ctl=1,cp="string",cs=1,dt="string",dtg="string",es=1,ex=1,init=1,iu=1,l="string",mrl=1,mbv=1,ni=1,p="string",pmp="script",rp="string",to=1,toc="string",tor=1,up=1,ut="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/devicePanel.html
-----------------... | 20,484 |
def statuses_filter(auth, **params):
"""
Collect tweets from the twitter statuses_filter api.
"""
endpoint = "https://stream.twitter.com/1.1/statuses/filter.json"
if "follow" in params and isinstance(params["follow"], (list, tuple)):
params["follow"] = list_to_csv(params["follow"])
if ... | 20,485 |
def adjust_hue(image, hue_factor):
"""Adjusts hue of an image.
The image hue is adjusted by converting the image to HSV and
cyclically shifting the intensities in the hue channel (H).
The image is then converted back to original image mode.
`hue_factor` is the amount of shift in H channel and must... | 20,486 |
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-fo... | 20,487 |
def compareDict(a, b):
"""
Compare two definitions removing the unique Ids from the entities
"""
ignore = ['Id']
_a = [hashDict(dict(x), ignore) for x in a]
_b = [hashDict(dict(y), ignore) for y in b]
_a.sort()
_b.sort()
return _a == _b | 20,488 |
def create_twitter_auth(cf_t):
"""Function to create a twitter object
Args: cf_t is configuration dictionary.
Returns: Twitter object.
"""
# When using twitter stream you must authorize.
# these tokens are necessary for user authentication
# create twit... | 20,489 |
def main():
"""Entry point."""
debug = False
try:
argparser = ArgumentParser(description=modules[__name__].__doc__)
argparser.add_argument('device', nargs='?', default='ftdi:///?',
help='serial port device name')
argparser.add_argument('-S', '--no-smb',... | 20,490 |
def _project(doc, projection):
"""Return new doc with items filtered according to projection."""
def _include_key(key, projection):
for k, v in projection.items():
if key == k:
if v == 0:
return False
elif v == 1:
return... | 20,491 |
def test_null_model(objective: str, expectation: float) -> None:
"""
It outputs the mean/modal training value for all training predictors.
Args:
objective: The objective of the model (classification or regression).
expectation: The expected prediction of the model.
"""
# Data
X_... | 20,492 |
def random_swap(words, n):
"""
Randomly swap two words in the sentence n times
Args:
words ([type]): [description]
n ([type]): [description]
Returns:
[type]: [description]
"""
def swap_word(new_words):
random_idx_1 = random.randint(0, len(new_words) - ... | 20,493 |
def get_dist_for_angles(dict_of_arrays, clusters, roll, pitch, yaw, metric='3d', kind='max'):
"""
Calculate a single distance metric for a combination of angles
"""
if (dict_of_arrays['yaw_corr'] == 0).all():
rot_by_boresight = apply_boresight_same(dict_of_arrays, roll, pitch, yaw)
else:... | 20,494 |
def test_extra_yaml():
"""Test loading extra yaml file"""
load(settings, filename=YAML)
yaml = """
example:
helloexample: world
"""
settings.set("YAML", yaml)
settings.execute_loaders(env="EXAMPLE")
assert settings.HELLOEXAMPLE == "world" | 20,495 |
async def stream():
"""Main streaming loop for PHD"""
while True:
if phd_client.is_connected and manager.active_connections:
response = await phd_client.get_responses()
if response is not None:
# Add to the websocket queue
# If it is the initial da... | 20,496 |
def filter_camera_angle(places, angle=1.):
"""Filter pointclound by camera angle"""
bool_in = np.logical_and((places[:, 1] * angle < places[:, 0]),
(-places[:, 1] * angle < places[:, 0]))
return places[bool_in] | 20,497 |
def main():
"""Carry out model performance estimation.
"""
parser = ArgumentParser()
parser.add_argument('--config', '-c', type=str, required=True, help='Path to config file')
args = parser.parse_args()
assert exists(args.config)
task_monitor = get_monitor(args.config)
task_monitor.pe... | 20,498 |
def load_nifti(path: str) \
-> tuple[np.ndarray, np.ndarray, nib.nifti1.Nifti1Header]:
"""
This function loads a nifti image using
the nibabel library.
"""
# Extract image
img = nib.load(path)
img_aff = img.affine
img_hdr = img.header
# Extract the actual data in a numpy arra... | 20,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.