content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def carla_cityscapes_image_to_ndarray(image: carla.Image) -> np.ndarray: # pylint: disable=no-member
"""Returns a `NumPy` array from a `CARLA` semantic segmentation image.
Args:
image: The `CARLA` semantic segmented image.
Returns:
A `NumPy` array representation of the image.
"""
image.convert(carl... | 30,200 |
async def restore(ctx, server: str, backup_name: str):
"""Restores a server to a named file system backup. Shuts down the server before executing and restarts after
the backup finishes. """
pass | 30,201 |
def test_fetch_burst_uuid():
""" test fetch_burst_uuid """
test_dict = UUID_DICT["burst"]
uuid = test_dict["uuid"]
filename = test_dict["filename"]
lib = PhotoLibrary()
photo = lib.fetch_uuid(uuid)
bursts_selected = lib.fetch_burst_uuid(photo.burstid)
assert len(bursts_selected) == test... | 30,202 |
def main(time_series: str, config: dict = {}, train: bool = True, test: bool = True):
"""_summary_
Parameters
----------
time_series : str
_description_
config : dict, optional
_description_, by default {}
"""
# Get train files
train_files = list_files(time_series, confi... | 30,203 |
def main(argv):
"""
Build the docs and serve them with an HTTP server.
"""
parser = argparse.ArgumentParser(description='Build and serve HTML Sphinx docs')
parser.add_argument(
'--port',
help='Serve on this port, default 8000',
type=int,
default=8000)
parser.add... | 30,204 |
def since(version):
"""A decorator that annotates a function to append the version
of skutil the function was added. This decorator is an adaptation of PySpark's.
Parameters
----------
version : str, float or int
The version the specified method was added to skutil.
Examples
---... | 30,205 |
def get_dMdU():
"""Compute dMdU"""
dMdC = form_nd_array("dMdC", [3,3,3,3,3])
dMdPsi = form_nd_array("dMdPsi", [3,3,3,3,3])
dMdGamma = form_nd_array("dMdGamma",[3,3,3,3,3,3])
dCdU = form_symb_dCdU()
dPsidU = form_symb_dPhidU()
dGammadU = form_symb_dGammadU()
... | 30,206 |
async def test_setup_duplicate_entries(opp: OpenPeerPower, remote: Mock, caplog):
"""Test duplicate setup of platform."""
await async_setup_component(opp, SAMSUNGTV_DOMAIN, MOCK_CONFIG)
await opp.async_block_till_done()
assert opp.states.get(ENTITY_ID)
assert len(opp.states.async_all()) == 1
awa... | 30,207 |
def get_group_value_ctx_nb(sc_oc):
"""Get group value from context.
Accepts `vectorbt.portfolio.enums.SegmentContext` and `vectorbt.portfolio.enums.OrderContext`.
Best called once from `segment_prep_func_nb`.
To set the valuation price, change `last_val_price` of the context in-place.
!!! note
... | 30,208 |
def motion_blur_generate_kernel(radius, angle, sigma):
"""
Args:
radius
angle (float): Radians clockwise from the (x=1, y=0) vector. This
is how ImageMagick's -motion-blur filter accepts angles, as far
as I can tell.
>>> mb_1_0_inf_expected = torch.ones(3) / 3
>>... | 30,209 |
def substitute_crypto_to_req(req):
"""Replace crypto requirements if customized."""
crypto_backend = get_crypto_req()
if crypto_backend is None:
return req
def is_not_crypto(r):
CRYPTO_LIBS = PYCRYPTO_DIST, "cryptography"
return not any(r.lower().startswith(c) for c in CRYPTO_L... | 30,210 |
def remove_att(doc_id, doc_rev, att_id, **kwargs):
"""Delete an attachment.
http://docs.couchdb.org/en/stable/api/document/attachments.html#delete--db-docid-attname
:param str doc_id: The attachment document.
:param str doc_rev: The document revision.
:param str att_id: The attachment to remove.
... | 30,211 |
def read_file(file_path):
"""Read file according to its file schema"""
s3_schema = 's3'
path_comps = urllib.parse.urlparse(file_path)
scheme = path_comps.scheme
return_result = None
if not scheme or scheme != s3_schema:
file_stream = open(file_path)
return_result = file_stream.r... | 30,212 |
def build_command(codemodders_list: List) -> BaseCodemodCommand:
"""Build a custom command with the list of visitors."""
class CustomCommand(BaseCodemodCommand):
transformers = codemodders_list
return CustomCommand(CodemodContext()) | 30,213 |
def default_gen_mat(dt: float, size: int) -> np.ndarray:
"""Default process matrix generator.
Parameters
----------
dt : float
Dimension variable difference.
size : int
Size of the process matrix, equals to number of rows and columns.
Returns
-------
np.ndarray
... | 30,214 |
def handle_list(bot, update, conn):
""" Lists all contracts that are active
"""
for contract in db.get_open_contracts_for_user(conn, update.message.chat_id):
bot.send_message(
contract.chat_id,
f'Contract for url {contract.query} \nTo stop watching it, send "/stop {contract.... | 30,215 |
def bubble_sort_optimized(array):
""" Модификований алгоритм сортування "Бульбашкою"
:param array: Вхідний масив даних, що треба відсортувати.
"""
n = len(array)
for i in range(n - 1, 0, -1):
check = True
for j in range(i):
if array[j] > array[j + 1]:
chec... | 30,216 |
def SplitMultiDelims(line, delimiters):
"""
Split a string into tokens using one or more (multi-character) delimiters.
(Bug: The current version of this function does not preserve white space,
but this should not matter.)
"""
token = ''
for sub_token in line.strip().split():
... | 30,217 |
async def test_consume_multiple_queues(event_loop, caplog):
"""Consume multiple queues and check delivery.
"""
class CounterConsumerMultiple(CounterConsumerMixin, BaseConsumer):
"""Counter consumer (multiple queue interface).
Count messages from all consumed queues in `self.counter`.
... | 30,218 |
def row_accessor(row: tuple):
"""
Utility generator yielding tuple of form (str, str); e.g
('A10', 'Project/Programme Name').
:param row:
:return:
"""
for item in row:
yield ("".join([item.column, str(item.row)]), item.value) | 30,219 |
def _PrepareListOfSources(spec, generator_flags, gyp_file):
"""Prepare list of sources and excluded sources.
Besides the sources specified directly in the spec, adds the gyp file so
that a change to it will cause a re-compile. Also adds appropriate sources
for actions and copies. Assumes later stage will un-ex... | 30,220 |
def striptag(tag):
"""
Get the short representation of a fully qualified tag
:param str tag: a (fully qualified or not) XML tag
"""
if tag.startswith('{'):
return tag.rsplit('}')[1]
return tag | 30,221 |
def dump_key(key):
""" Convert key into printable form using openssl utility
Used to compare keys which can be stored in different
format by different OpenSSL versions
"""
return Popen(["openssl","pkey","-text","-noout"],stdin=PIPE,stdout=PIPE).communicate(key)[0] | 30,222 |
def download_complete(root_data_path, domain_name, start_date, end_date):
"""
Check that all files have been downloaded and that they contain the data in
the expected date range
"""
missing_files = _find_missing_files(
root_data_path=root_data_path,
domain_name=domain_name,
s... | 30,223 |
def convertsrc(direc=os.path.curdir, ext=None, orig=1):
"""Replace Numeric/arrayobject.h with numpy/oldnumeric.h in all files in the
directory with extension give by list ext (if ext is None, then all files are
replaced)."""
if ext is None:
files = glob.glob(os.path.join(direc,'*'))
else:
... | 30,224 |
def get_test_string(actual: Any, rtol: float, atol: float) -> str:
"""
Args:
actual: The actual value that was produced, and that should be the desired value.
rtol: The relative tolerance of the comparisons in the assertion.
atol: The absolute tolerance of the comparisons in the assertio... | 30,225 |
def is_type_resolved(_type):
"""Helper function that checks if type is already resolved."""
return _type in BASIC_TYPES or isinstance(_type, TypeDef) | 30,226 |
def _add_ingredients(ingredients, column1, column2):
"""Add ingredients from two columns."""
# Process down then across. It's possible that the file was exported
# to read across then down, but we're ignoring that possibility.
# This could be a flag we could pass in.
column1.extend(column2)
# A... | 30,227 |
def menu_alta(nombre, apellido, datos):
""" Pregunta si se desea ingresar un nombre y apellido y
de ser así, pide los datos al usuario. """
print ("No se encuentra %s %s en la agenda." %(nombre, apellido))
confirmacion = input("¿Desea ingresarlo? (s/n) ")
if confirmacion.lower() != "s":
... | 30,228 |
def test_rom_is_bytes(mario):
"""Test the emulator can run with in-memory bytes."""
rom = mario.read_bytes()
cartridge = Cartridge(rom)
assert "SUPER MARIOLAND" in repr(cartridge) | 30,229 |
def test_get_or_create_bootcamp_application(mocker):
"""
get_or_create_bootcamp_application should fetch an existing bootcamp application, or create one with the \
application state set properly
"""
patched_derive_state = mocker.patch(
"applications.api.derive_application_state",
ret... | 30,230 |
def main(audio_dir, results_dir):
"""
Estimates beat positions for all files in the Harmonix Set, using the estimators published in the paper.
Args:
audio_dir: str - The complete path to the directory containing mp3 files for all tracks in the Harmonix Set.
results_dir: str - The complete ... | 30,231 |
def test_for_dataset_1(rate_sim_3):
"""Test _for_dataset.
Use timestep=False.
"""
x = rate_sim_3._for_dataset(timestep=False)
desired_stimulus_set = np.array(
[
[3, 1],
[3, 1],
[9, 12],
[0, 0],
[3, 4],
[3, 4],
... | 30,232 |
def get_extension(media):
"""Gets the corresponding extension for any Telegram media."""
# Photos are always compressed as .jpg by Telegram
try:
get_input_photo(media)
return '.jpg'
except TypeError:
# These cases are not handled by input photo because it can't
if isinst... | 30,233 |
def VLBAInitContFQParms(uv, parms, err, \
logfile=None, check=False, debug=False):
"""
Initialize VLBA continuum pipeline frequency dependent parameters
Values set if None on input
* uv = Project raw UV data object
* parms = Project parameters
* err ... | 30,234 |
def process_input(df, col_group, col_t, col_death_rate, return_df=True):
"""
Trim filter and adding extra information to the data frame.
Args:
df (pd.DataFrame): Provided data frame.
col_group (str): Column name of group definition.
col_t (str): Column name of the independent variab... | 30,235 |
def cross_entropy_loss():
"""
Returns an instance to compute Cross Entropy loss
"""
return tf.keras.losses.BinaryCrossentropy(from_logits=True) | 30,236 |
def main():
"""Entry point."""
greet('Content extraction tool')
filesystem = Filesystem()
source = ask('Path to source theme')
target = ask('Path to target theme')
filesystem.ensure_folder_exists(source)
filesystem.ensure_folder_exists(target)
while True:
keys = ask_list('Whic... | 30,237 |
def f(x):
"""
Surrogate function over the error metric to be optimized
"""
evaluation = run_quip(cutoff = float(x[:,0]), delta = float(x[:,1]), n_sparse = float(x[:,2]), nlmax = float(x[:,3]))
print("\nParam: {}, {}, {}, {} | MAE : {}, R2: {}".format(float(x[:,0]),float(x[:,1]),float(x[:,2]),f... | 30,238 |
def equal(* vals):
"""Returns True if all arguments are equal"""
if len(vals) < 2:
return True
a = vals[0]
for b in vals[1:]:
if a != b:
return False
return True | 30,239 |
def test_all_settings():
""" Test parse_request for '_all _settings GET'
returns correctly parsed request.
"""
request = {
'args': {
'method': 'GET',
'uri': '/_all/_settings',
},
'parsed_request': {
'indices': ['_all'],
'cluster... | 30,240 |
def chrome_options() -> Options:
"""Pass standard Chrome options to a test."""
options = Options()
executable_path = os.getenv("EXECUTABLE_PATH")
assert (
executable_path is not None
), "EXECUTABLE_PATH environment variable must be set"
logger.info(f"EXECUTABLE_PATH is {executable_path}"... | 30,241 |
def main(custom_args: list = None):
"""
The main entry point of the `dref` command line tool.
Accepts two positional arguments:
input_uri - the input document to be resolved.
output_file - the output file for resolved data.
If the `output_file` extension is `yaml` or `yml`, the output
... | 30,242 |
def exp(x: pd.Series) -> pd.Series:
"""
Exponential of series
:param x: timeseries
:return: exponential of each element
**Usage**
For each element in the series, :math:`X_t`, raise :math:`e` (Euler's number) to the power of :math:`X_t`.
Euler's number is the base of the natural logarithm,... | 30,243 |
def level_location(level, cache_dir):
"""
Return the path where all tiles for `level` will be stored.
>>> level_location(2, '/tmp/cache')
'/tmp/cache/02'
"""
if isinstance(level, string_type):
return os.path.join(cache_dir, level)
else:
return os.path.join(cache_dir, "%02d" ... | 30,244 |
def pil_paste_image(im, mask, start_point=(0, 0)):
"""
:param im:
:param mask:
:param start_point:
:return:
"""
out = Image.fromarray(im)
mask = Image.fromarray(mask)
out.paste(mask, start_point, mask)
return np.asarray(out) | 30,245 |
def service_northwind_v2(schema_northwind_v2):
"""https://services.odata.org/V2/Northwind/Northwind.svc/"""
return pyodata.v2.service.Service('http://not.resolvable.services.odata.org/V2/Northwind/Northwind.svc',
schema_northwind_v2, requests) | 30,246 |
def train_and_eval(
params: base_configs.ExperimentConfig,
strategy_override: tf.distribute.Strategy) -> Mapping[str, Any]:
"""Runs the train and eval path using compile/fit."""
logging.info('Running train and eval.')
# Note: for TPUs, strategy and scope should be created before the dataset
strategy = ... | 30,247 |
def make_params(params, extra_params):
"""
Creates URL query params by combining arbitrary params
with params designated by keyword arguments and escapes
them to be compatible with HTTP request URI.
Raises an exception if there is a conflict between the
two ways to specify a query param.
""... | 30,248 |
def raw_tag(name, value):
"""Create a DMAP tag with raw data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value | 30,249 |
def process_preprocess_layers(params: dict):
"""Perform preprocess layers"""
layers = params["preprocess_layers"]
if "formats" in layers:
add_formats_layer(params) | 30,250 |
def get_command(tool_xml):
"""Get command XML element from supplied XML root."""
root = tool_xml.getroot()
commands = root.findall("command")
command = None
if len(commands) == 1:
command = commands[0]
return command | 30,251 |
def OPTIMIZE(writer, segments):
"""This policy merges all existing segments.
"""
from whoosh.reading import SegmentReader
for seg in segments:
reader = SegmentReader(writer.storage, writer.schema, seg)
writer.add_reader(reader)
reader.close()
return [] | 30,252 |
def build_features_revenue_model_q2(
df_listings: pd.DataFrame, df_daily_revenue: pd.DataFrame
):
"""Builds the features to be used on the revenue modelling for
answer question 2.
Parameters
----------
df_listings : pd.DataFrame
Pandas dataframe with information about listings.... | 30,253 |
def test_get_entry_empty():
"""
Test the get_entry function by reading the `test_input.xlsx` workbook
reading the and empty row and check that the output is None
"""
row = pytest.ws.__getitem__('5')
entry = standardcitations.get_entry(row, True)
assert not entry | 30,254 |
def load_data():
"""Return the MNIST data as a tuple containing the training data,
the validation data, and the test data.
The ``training_data`` is returned as a tuple with two entries.
The first entry contains the actual training images. This is a
numpy ndarray with 50,000 entries. Each entry is... | 30,255 |
def tensorboard_image(
writer: SummaryWriter,
image: torch.Tensor,
target: torch.Tensor,
output: torch.Tensor,
global_step: int,
) -> None:
"""Output image tensors in tensorboard visualization.
Useful for image based training
Args:
writer (SummaryWriter): tensorboard... | 30,256 |
def find_by_id(cls, groupkey, objectid, raises=False):
"""A helper function to look up an object by id"""
ob = None
try:
ob = keyedcache.cache_get(groupkey, objectid)
except keyedcache.NotCachedError as e:
try:
ob = cls.objects.get(pk=objectid)
keyedcache.cache_s... | 30,257 |
def write_results(conn, seed_tab_rows, sig_param_dicts,\
bkg_nllh, sig_nllhs, TSs):
"""
Writes a result row to the result table and updates the seed table as done
Parameters:
conn: sqlite connection object
seed_tab_rows: list of named tuples, a row of the seed table as a named tupl... | 30,258 |
def get_elements(xmldoc, tag_name, attribute):
"""Returns a list of elements"""
l = []
for item in xmldoc.getElementsByTagName(tag_name) :
value = item.getAttribute(attribute)
l.append( repr( value ) )
return l | 30,259 |
def test_card_value_equality():
"""
Same cards values are equal and different cards values are not equal.
Cards values are equal to a number.
"""
five_diamonds_1 = Card("5", "diamonds", value=5)
five_diamonds_2 = Card("5", "diamonds", value=5)
six_diamonds = Card("6", "diamonds", value=6)
... | 30,260 |
def test_algorithm(circuit, iterations=(1000000)):
"""
Tests a circuit by submitting it to both aer_simulator and PyLinalg.
"""
linalg = PyLinalg()
qlm_circ, _ = qiskit_to_qlm(circuit, sep_measures=True)
test_job = qlm_circ.to_job(nbshots=0, aggregate_data=False)
expected = linalg.submit(tes... | 30,261 |
def return_list_of_sn_host():
""" Return potential SN host names
This includes:
- List of object names in SIMBAD that would correspond to extra-galactic object
- Unknown objects
- objects with failed crossmatch
In practice, this exclude galactic objects from SIMBAD.
"""
list_simbad_ga... | 30,262 |
def folder2catalog(path, granule_trunk='', granule_extension='*', add_sf=False, client=None):
""" Reads a folder of granules into a STAREDataFrame catalog
:param path: Path of the folder containing granules
:type path: str
:param granule_trunk: Granule identifier (e.g. MOD09)
:type granule_trunk: s... | 30,263 |
def test_ingest():
"""
Test ingesting data with a given schema
"""
schema = pa.schema([
pa.field("foo", pa.int64()),
pa.field("bar", pa.int64())
])
data = [{"foo": 1, "bar": 2}, {"foo": 10, "bar": 20}]
converted_data = client.ingest_data(data, schema)
assert converted_d... | 30,264 |
def _check_satellite_low(xbee, is_on_hold):
"""
Check if satellites are low and set the is_on_hold flag.
Args:
xbee(xbee.Zigbee): the XBee communication interface.
is_on_hold(bool): a flag telling if the thread is already on hold.
Returns:
bool: True if low sats, False ... | 30,265 |
def indexof(path):
"""Returns list of filenames parsed off "Index of" page"""
resp = requests.get(path)
return [a for a, b in file_index_re.findall(resp.text) if a == b] | 30,266 |
def get_oversight(xml: str) -> Optional[OversightInfo]:
""" Get oversight """
if val := xml.get('oversight_info'):
return OversightInfo(
has_dmc=val.get('has_dmc', ''),
is_fda_regulated_drug=val.get('is_fda_regulated_drug', ''),
is_fda_regulated_device=val.get('is_fd... | 30,267 |
def get_user_id(gi,email):
"""
Get the user ID corresponding to a username email
Arguments:
gi (bioblend.galaxy.GalaxyInstance): Galaxy instance
email : email address for the user
Returns:
String: user ID, or None if no match.
"""
user_id = None
try:
for u in get_... | 30,268 |
def _patch_intercept_mark():
"""Need to make cursor wider when in first column. Otherwise
the border of the cell box makes it hard to notice the cursor.
NB! Need to be careful with setting text["insertwidth"]!
My first straightforward solution caused unexplainable
infinite loop of insertions an... | 30,269 |
def test_circuitpython_libraries(monkeypatch):
"""Test main function of 'circuitpyton_libraries.py', without writing an output file."""
monkeypatch.setattr(common_funcs, "list_repos", mock_list_repos)
circuitpython_libraries.main(validator="all") | 30,270 |
def get_tests_directory() -> str:
"""
Returns the path of the top level directory for tests.
Returns: The path of the top level directory for tests.
This is useful for constructing paths to the test files.
"""
module_file_path = os.path.abspath(__file__)
return os.path.dirname(module_file_p... | 30,271 |
def test_set_car_online():
"""Test set/get car_online."""
_controller = Controller(None)
_controller.set_id_vin(CAR_ID, VIN)
assert _controller.get_car_online() == {}
assert _controller.get_car_online(vin=VIN) == {}
assert _controller.is_car_online(vin=VIN) == {}
_controller.set_car_onlin... | 30,272 |
def ldns_pkt_size(*args):
"""LDNS buffer."""
return _ldns.ldns_pkt_size(*args) | 30,273 |
def draw_intro_screen():
"""
Start menu.
"""
# Animating chicken sprite.
chick_x = xDisplay * 0.1875
chick_y = yDisplay * 0.55
chick_dir = True
while 1:
for event in pygame.event.get():
quit_program(event)
# Controls chicken's movement
... | 30,274 |
def getUser(userID):
""" Takes a user ID as an argument and returns the user associated
with that ID.
Args:
userID -- The ID of a user stored in the Patrons table
"""
user = session.query(Patrons).filter_by(id = userID).one()
return user | 30,275 |
def guard_transform(transform):
"""Return an Affine transformation instance"""
if not isinstance(transform, Affine):
if tastes_like_gdal(transform):
warnings.warn(
"GDAL-style transforms are deprecated and will not "
"be supported in Rasterio 1.0.",
... | 30,276 |
def config_logger(filename="/logging.yaml", level=None):
"""
Configure the main logger.
Parameters
----------
filename : string, optional
The filename for the logging configuration
file. Defaults to "logging.yaml" in the current
working directory.
level : object
... | 30,277 |
def create_heatmap(piek_json,
antske_json,
output_path=None,
verbose=0):
"""
"""
# initialize dataframe
likert_values = [1, 2, 3, 4, 5, 6, 7]
df = pandas.DataFrame()
default_values = [None for _ in range(len(likert_values))]
for liker... | 30,278 |
def get_classification_report(true_labels, pred_labels, labels=None, target_names=None, output_dict=False):
"""
true_labels = [0, 1, 2, 3, 4, 1] # Y
pred_labels = [0, 1, 1, 2, 2, 1] # X
target_names = ["A", "B", "C", "D", "E"]
out_result = get_classification_report(true_labels, pred_labels, target... | 30,279 |
def test_simple_flow_existing_tag_on_last_commit(
existing_tag, next_tag, simple_repo, default_detectors):
"""Test a simple flow locally."""
repo = git.Repo(simple_repo, odbt=git.GitDB)
repo.create_tag(
existing_tag,
ref=list(repo.iter_commits())[0])
autotag = core.AutoTag(
... | 30,280 |
def generate_message(minutes_to_next=None):
"""
Using the list of exercises, this function generates a new exercise message. Optionally it
takes a minutes_to_next parameter which it uses to add an indication of when the next exercise
will take place.
"""
# Randomly select an exercise and a... | 30,281 |
def yx():
"""
测试印象笔记服务
:return:
"""
client = EvernoteClient(token=dev_token,sandbox=False)
client.service_host = 'app.yinxiang.com'
userStore = client.get_user_store()
user = userStore.getUser()
print user
return "yx" | 30,282 |
def generate_frequency_result_for_time_precedence_query_workload(config_map, time_interval, spatial_interval):
"""
:param config_map:
:param time_interval:
:param spatial_interval:
:return:
"""
frequency_result = {}
for key in config_map.keys():
region_param_list = c... | 30,283 |
def delete(request):
"""退出登录,清除session"""
request.session.flush()
return redirect('/login/') | 30,284 |
def acovf(x, unbiased=False, demean=True, fft=None, missing='none', nlag=None):
"""
Autocovariance for 1D
Parameters
----------
x : array
Time series data. Must be 1d.
unbiased : bool
If True, then denominators is n-k, otherwise n
demean : bool
If True, then subtract... | 30,285 |
def coins_snapshot(broker='hb', code='btc', size='5'):
"""
获取实时快照数据
params:
broker:hb,ok,chbtc
code:btc,ltc,eth,etc,bcc
size:<150
return Panel: asks,bids
"""
pass | 30,286 |
def ParseTimeCommandResult(command_result):
"""Parse command result and get time elapsed.
Args:
command_result: The result after executing a remote time command.
Returns:
Time taken for the command.
"""
time_data = re.findall(r'real\s+(\d+)m(\d+.\d+)', command_result)
time_in_seconds = 60 * floa... | 30,287 |
def _GetTmpDir():
"""Determines the right temporary dir to use and creates it if necessary.
Returns:
path to temporary directory.
"""
tmp_dir = FLAGS.emulator_tmp_dir or os.path.abspath(
tempfile.mkdtemp('android-emulator-launch'))
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)
return ... | 30,288 |
def _push_aol_to_dativetop_server(aol):
"""Make a PUT request to the DativeTop server in order to push ``aol`` on to
the server's AOL.
"""
try:
resp = requests.put(c.DATIVETOP_SERVER_URL, json=aol)
resp.raise_for_status()
return resp.json(), None
except json.decoder.JSONDecod... | 30,289 |
def dual_single(lag_mul: float, val: np.ndarray, count: np.ndarray) -> float:
"""Weighted average minus 1 for estimate of F_0.
Computes phi_n(lambda_n) - 1.
Args:
lag_mul: The normalized Lagrangian multiplier. Must be
strictly between 0 and 1.
val: Likelihood values (excluding... | 30,290 |
def _execute(
repository_ctx,
cmdline,
error_msg = None,
error_details = None,
empty_stdout_fine = False,
environment = {}):
"""Executes an arbitrary shell command.
Args:
repository_ctx: the repository_ctx object
cmdline: list of strings, the command ... | 30,291 |
def resetDefaultConfig(): #-----------------------------------------------
"""Resets settings/config/materials to defaults.
"""
#print 'deb:lresetDefaultConfig keywords_org: \n', keywords_org #---------
updateConfig(keywords_org, drawTypes_org) | 30,292 |
def parse_tagged_block(block):
"""
Replaces "data" attribute of a block with parsed data structure
if it is known how to parse it.
"""
key = block.key.decode('ascii')
if not TaggedBlock.is_known(key):
warnings.warn("Unknown tagged block (%s)" % block.key)
decoder = _tagged_block_dec... | 30,293 |
def floatX(arr):
"""Converts data to a numpy array of dtype ``theano.config.floatX``.
Parameters
----------
arr : array_like
The data to be converted.
Returns
-------
numpy ndarray
The input array in the ``floatX`` dtype configured for Theano.
If `arr` is an ndarray o... | 30,294 |
def getNumberOfPublicIp():
"""Get the total number of public IP
return: (long) Number of public IP
"""
#No need to calculate this constant everytime
return 3689020672
# Real implementation:
#ranges = getValidPublicIpRange()
#number_of_ip = 0
#for range in ranges:
# number_of_ip = number_of_ip + (r... | 30,295 |
def load_config(config_name):
"""
loads config specified by name given and reload connnection
"""
import connection
global SOLR_PORT, SOLR_ADDRESS, SOLR_CORE
config = CONFIGS[config_name]
SOLR_CORE = config['core']
SOLR_PORT = config['port']
SOLR_ADDRESS = config['host']
connecti... | 30,296 |
def framework_find(fn, executable_path=None, env=None):
"""
Find a framework using dyld semantics in a very loose manner.
Will take input such as:
Python
Python.framework
Python.framework/Versions/Current
"""
error = None
try:
return dyld_find(fn, executable_path... | 30,297 |
def find_modules(path):
"""
Funtion to list all the modules in a repository.
"""
modules = set()
packages = find_packages(path)
for pkg in packages:
modules.add(pkg)
pkgpath = path + "/" + pkg.replace(".", "/")
if sys.version_info.major == 2 or (
sys.version_i... | 30,298 |
def cart2sph(x, y, z):
"""
Convert Cartesian coordinates x, y, z
to conventional spherical coordinates r, p, a
:param x: Cartesian coordinate or vector x
:type x: float or np.ndarray
:param y: Cartesian coordinate or vector y
:type y: float or np.ndarray
:param z: Cartesian coordinates ... | 30,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.