content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the gi... | 2,700 |
def euler719(n=10**12):
"""Solution for problem 719."""
return sum(i*i
for i in range(2, 1 + int(math.sqrt(n)))
if can_be_split_in_sum(i*i, i)) | 2,701 |
def mark_as_child(data):
"""
Marks the incoming data as child of celeryapplications
"""
kopf.adopt(data) | 2,702 |
def inner(a, b):
"""
Inner product of two tensors.
Ordinary inner product of vectors for 1-D tensors (without complex
conjugation), in higher dimensions a sum product over the last
axes.
Note:
Numpy argument out is not supported.
On GPU, the supported dtypes are np.float16, and... | 2,703 |
def create():
"""
Creates settings and screens table.
"""
sql_exec(
f'''CREATE TABLE settings (
{Settings.IP} text,
{Settings.PASS} text,
{Settings.PC} integer,
{Settings.ENCRYPTION} integer
)'''
)
sql_exec("INSERT ... | 2,704 |
def cleanup_environment():
"""
Shutdown the ZEO server process running in another thread and cleanup the
temporary directory.
"""
SERV.terminate()
shutil.rmtree(TMP_PATH)
if os.path.exists(TMP_PATH):
os.rmdir(TMP_PATH)
global TMP_PATH
TMP_PATH = None | 2,705 |
def stern_warning(warn_msg: str) -> str:
"""Wraps warn_msg so that it prints in red."""
return _reg(colorama.Fore.RED, warn_msg) | 2,706 |
def alt2temp_ratio(H, alt_units=default_alt_units):
"""
Return the temperature ratio (temperature / standard temperature for
sea level). The altitude is specified in feet ('ft'), metres ('m'),
statute miles, ('sm') or nautical miles ('nm').
If the units are not specified, the units in defaul... | 2,707 |
def test_random_page_uses_given_language(mock_requests_get: Mock) -> None:
"""Is selects the specific Wikipedia language edition."""
wikipedia.random_page(language="de")
args, _ = mock_requests_get.call_args
assert "de.wikipedia.org" in args[0] | 2,708 |
def set_background_priority(isBackground: bool):
"""Start or stop process as background prioity to ensure app does not interfer with performance"""
processID = os.getpid()
processHandle = ctypes.windll.kernel32.OpenProcess(ctypes.c_uint(
0x0200 | 0x0400), ctypes.c_bool(False), ctypes.c_uint(processI... | 2,709 |
def test_medicationusage_2(base_settings):
"""No. 2 tests collection for MedicationUsage.
Test File: medicationusageexample3.json
"""
filename = base_settings["unittest_data_dir"] / "medicationusageexample3.json"
inst = medicationusage.MedicationUsage.parse_file(
filename, content_type="appl... | 2,710 |
def save_labels(labels, fn, overwrite=True):
"""
Save the labels to the given filename.
Raises
------
* NotImplementedError if `fn` is an unsupported file type.
* AssertionError if `fn` exists and `not overwrite`.
Parameters
----------
labels : numpy.ndarray
...
fn : st... | 2,711 |
def getFiles(searchpattern):
"""Append paths of all files that match search pattern to existingFiles"""
results = glob.glob(searchpattern)
for f in results:
if os.path.isfile(f):
existingFiles.append(f) | 2,712 |
def test_set_precision_collapse(geometry, mode, expected):
"""Lines and polygons collapse to empty geometries if vertices are too close"""
actual = pygeos.set_precision(geometry, 1, mode=mode)
if pygeos.geos_version < (3, 9, 0):
# pre GEOS 3.9 has difficulty comparing empty geometries exactly
... | 2,713 |
def verify_inputs(data, action):
""" Simple error checking for input data.
"""
try:
# Verify action for which we are validating the field (create or update).
verify_action(action)
if not data:
message = 'Field validation requires event type, data dict and a defined action... | 2,714 |
def encode_message(key, message):
""" Encodes the message (string) using the key (string) and
pybase64.urlsafe_b64encode functionality """
keycoded = []
if not key:
key = chr(0)
# iterating through the message
for i in range(len(message)):
# assigning a key_character based on ... | 2,715 |
def test_file_open_close():
""" https://github.com/telegraphic/hickle/issues/20 """
import h5py
f = h5py.File('test.hdf', 'w')
a = np.arange(5)
dump(a, 'test.hkl')
dump(a, 'test.hkl')
dump(a, f, mode='w')
f.close()
try:
dump(a, f, mode='w')
except hickle.hickle.ClosedFi... | 2,716 |
def cfg():
"""Configuration of argument parser."""
parser = argparse.ArgumentParser(
description="Crawl SolarEdge and stores results in InfluxDB",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# TODO: error message when missing env variable
parser.add_argument('--gardena-... | 2,717 |
def get_debugger():
"""
Returns a debugger instance
"""
try:
from IPython.core.debugger import Pdb
pdb = Pdb()
except ImportError:
try:
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
IPShell(argv=[""])
... | 2,718 |
def add_sibling(data, node_path, new_key, new_data, _i=0):
"""
Traversal-safe method to add a siblings data node.
:param data: The data object you're traversing.
:param node_path: List of path segments pointing to the node you're creating a
sibling of. Same as node_path of traverse()
:param new_key: The sibling... | 2,719 |
def draw_pnl(ax, df):
"""
Draw p&l line on the chart.
"""
ax.clear()
ax.set_title('Performance')
index = df.index.unique()
dt = index.get_level_values(level=0)
pnl = index.get_level_values(level=4)
ax.plot(
dt, pnl, '-',
color='green',
linewidth=1.0,
... | 2,720 |
def maxRstat(Z, R, i):
"""
Return the maximum statistic for each non-singleton cluster and its
children.
Parameters
----------
Z : array_like
The hierarchical clustering encoded as a matrix. See `linkage` for more
information.
R : array_like
The inconsistency matrix.... | 2,721 |
def strip_characters(text):
"""Strip characters in text."""
t = re.sub('\(|\)|:|,|;|\.|’|”|“|\?|%|>|<', '', text)
t = re.sub('/', ' ', t)
t = t.replace("'", '')
return t | 2,722 |
def get_trained_model(datapath, dataset, image_size, nb_labels):
"""Recover model weights stored on the file system, and assign them into
the `model` structure
Parameters
----------
datapath : str
Path of the data on the file system
dataset : str
Name of the dataset
image_si... | 2,723 |
def make_std_secgroup(name, desc="standard security group"):
"""
Returns a standarized resource group with rules for ping and ssh access.
The returned resource can be further configured with additional rules by the
caller.
The name parameter is used to form the name of the ResourceGroup, and al... | 2,724 |
def parse_plot_args(*args, **options):
"""Parse the args the same way plt.plot does."""
x = None
y = None
style = None
if len(args) == 1:
y = args[0]
elif len(args) == 2:
if isinstance(args[1], str):
y, style = args
else:
x, y = args
elif len(... | 2,725 |
def publications_classification_terms_get(search=None): # noqa: E501
"""List of Classification Terms
List of Classification Terms # noqa: E501
:param search: search term applied
:type search: str
:rtype: ApiOptions
"""
return 'do some magic!' | 2,726 |
def test_empty_latest_listing():
"""Test listing a 'backup-list LATEST' on an empty prefix."""
container_name = 'wal-e-test-empty-listing'
layout = storage.StorageLayout('wabs://{0}/test-prefix'
.format(container_name))
with FreshContainer(container_name) as fb:
... | 2,727 |
def lu_decompose(tri_diagonal):
"""Decompose a tri-diagonal matrix into LU form.
Parameters
----------
tri_diagonal : TriDiagonal
Represents the matrix to decompose.
"""
# WHR Appendix B: perform LU decomposition
#
# d[0] = hd[0]
# b[i] = hu[i]
#
# Iterative algorith... | 2,728 |
def _card(item):
"""Handle card entries
Returns: title (append " - Card" to the name,
username (Card brand),
password (card number),
url (none),
notes (including all card info)
"""
notes = item.get('notes', "") or ""
# Add car... | 2,729 |
def s3():
"""Boto3 S3 resource."""
return S3().resource | 2,730 |
def tile2(i):
"""
This function handles OSC user input in address "/amazon/arduino/norm/baldosa2", with 1 arguments: i.
Use pl.OSC decorator to define handles like this. Multiple scripts can listen to
the same address simultaneously.
"""
print "baldosa2"
videoPlayers[1].play() | 2,731 |
def SUE(xmean=None,ymean=None,xstdev=None,ystdev=None,rho=None, \
xskew=None,yskew=None,xmin=None,xmax=None,ymin=None,ymax=None, \
Npt=300,xisln=False,yisln=False):
"""
SKEWED UNCERTAINTY ELLIPSES (SUE)
Function to plot uncertainty SUEs (or 1 sigma contour of a bivariate
split-normal di... | 2,732 |
def create_label(places, size, corners, resolution=0.50, x=(0, 90), y=(-50, 50), z=(-4.5, 5.5), scale=4, min_value=np.array([0., -50., -4.5])):
"""Create training Labels which satisfy the range of experiment"""
x_logical = np.logical_and((places[:, 0] < x[1]), (places[:, 0] >= x[0]))
y_logical = np.logical_... | 2,733 |
def usage():
"""Serve the usage page."""
return render_template("meta/access.html") | 2,734 |
def GetCache(name, create=False):
"""Returns the cache given a cache indentfier name.
Args:
name: The cache name to operate on. May be prefixed by "resource://" for
resource cache names or "file://" for persistent file cache names. If
only the prefix is specified then the default cache name for tha... | 2,735 |
def rf_local_divide_int(tile_col, scalar):
"""Divide a Tile by an integral scalar"""
return _apply_scalar_to_tile('rf_local_divide_int', tile_col, scalar) | 2,736 |
def or_(*children: Any) -> Dict[str, Any]:
"""Select devices that match at least one of the given selectors.
>>> or_(tag('sports'), tag('business'))
{'or': [{'tag': 'sports'}, {'tag': 'business'}]}
"""
return {"or": [child for child in children]} | 2,737 |
def get_width_and_height_from_size(x):
""" Obtains width and height from a int or tuple """
if isinstance(x, int): return x, x
if isinstance(x, list) or isinstance(x, tuple): return x
else: raise TypeError() | 2,738 |
def remove_stopwords(lista,stopwords):
"""Function to remove stopwords
Args:
lista ([list]): list of texts
stopwords ([list]): [description]
Returns:
[list]: List of texts without stopwords
"""
lista_out = list()
for idx, text in enumerate(lista):
text = ' '.joi... | 2,739 |
def Skeletonize3D(directory, crop=None, flip='y', dtype=None):
"""Skeletonize TrailMap results.
Parameters
----------
directory : string
Path to directory with segmented data.
crop : dict (optional, default None)
Dictionary with ImageJ-format cropping coordinates ({width:, heigh... | 2,740 |
def run_smeagle(package, version, path, libname):
"""
Run smeagle for a library of interest
"""
print("Testing %s with smeagle" % libname)
out_dir = "/results/{{ tester.name }}/{{ tester.version }}/%s/%s" % (package, version)
lib = os.path.join(path, libname)
libdir = os.path.dirname(libnam... | 2,741 |
async def test_PilotBuilder_speed(correct_bulb: wizlight) -> None:
"""Test speed."""
await correct_bulb.turn_on(PilotBuilder(scene=1, speed=50))
state = await correct_bulb.updateState()
assert state and state.get_scene() == SCENES[1]
assert state and state.get_speed() == 50 | 2,742 |
def get_users_report(valid_users, ibmcloud_account_users):
"""get_users_report()"""
users_report = []
valid_account_users = []
invalid_account_users = []
# use case 1: find users in account not in valid_users
for account_user in ibmcloud_account_users:
# check if account user is in va... | 2,743 |
def insert_bn(names):
"""Insert bn layer after each conv.
Args:
names (list): The list of layer names.
Returns:
list: The list of layer names with bn layers.
"""
names_bn = []
for name in names:
names_bn.append(name)
if 'conv' in name:
position = nam... | 2,744 |
def encrypt(KeyId=None, Plaintext=None, EncryptionContext=None, GrantTokens=None, EncryptionAlgorithm=None):
"""
Encrypts plaintext into ciphertext by using a customer master key (CMK). The Encrypt operation has two primary use cases:
You don\'t need to use the Encrypt operation to encrypt a data key. The ... | 2,745 |
def convert_format(parameters):
"""Converts dictionary database type format to serial transmission format"""
values = parameters.copy()
for key, (index, format, value) in values.items():
if type(format) == type(db.Int):
values[key] = (index, 'i', value) # signed 32 bit int (arduino long... | 2,746 |
def tester_pr3():
"""show calpost raster in different projection"""
from plotter import calpost_reader as reader
import rasterio
import cartopy.crs as ccrs
with open('../data/tseries_ch4_1min_conc_co_fl.dat') as f:
dat = reader.Reader(f, slice(60 * 12, 60 * 12 + 10))
# background
b ... | 2,747 |
async def test_addon_options_changed(
hass,
client,
addon_installed,
addon_running,
install_addon,
addon_options,
start_addon,
old_device,
new_device,
old_s0_legacy_key,
new_s0_legacy_key,
old_s2_access_control_key,
new_s2_access_control_key,
old_s2_authenticated_... | 2,748 |
def example_load_and_plot(filename=None,
summary_dir=os.path.join(REPO, '..', 'summary')):
"""Example demonstrating loading an HDF file into Pandas and plotting."""
import matplotlib.pyplot as plt
import pandas as pd
if filename is None:
filebase = 'merged_tract_4849_1... | 2,749 |
def prepare(_config):
"""
Preparation of the train and validation datasets for the training and initialization of the padertorch trainer,
using the configuration dict.
Args:
_config: Configuration dict of the experiment
Returns:
3-Tuple of the prepared datasets and the trainer.
... | 2,750 |
def getproj4(epsg):
"""
Get projection file (.prj) text for given epsg code from
spatialreference.org. See: https://www.epsg-registry.org/
.. deprecated:: 3.2.11
This function will be removed in version 3.3.5. Use
:py:class:`flopy.discretization.structuredgrid.StructuredGrid` instead.
... | 2,751 |
def vpn_tunnel_inside_cidr(cidr):
"""
Property: VpnTunnelOptionsSpecification.TunnelInsideCidr
"""
reserved_cidrs = [
"169.254.0.0/30",
"169.254.1.0/30",
"169.254.2.0/30",
"169.254.3.0/30",
"169.254.4.0/30",
"169.254.5.0/30",
"169.254.169.252/30",
... | 2,752 |
def choose_media_type(accept, resource_types):
"""choose_media_type(accept, resource_types) -> resource type
select a media type for the response
accept is the Accept header from the request. If there is no Accept header, '*/*' is assumed. If the Accept header cannot be parsed, HTTP400BadRequest is rai... | 2,753 |
def get_border_removal_size(image: Image, border_removal_percentage: float = .04, patch_width: int = 8):
"""
This function will compute the border removal size. When computing the boarder removal the patch size becomes
important the output shape of the image will always be an even factor of the patch size. ... | 2,754 |
def sample(n, ds, model):
""" Sample the potential of the given data source n times. """
i = 0
while i < n:
random = np.random.rand(2)
mock_params = [DataValue(value=random[0], type="float"),
DataValue(value=random[1], type="float")]
ds.run(model, mock_params)
... | 2,755 |
def get_natural_num(msg):
"""
Get a valid natural number from the user!
:param msg: message asking for a natural number
:return: a positive integer converted from the user enter.
"""
valid_enter = False
while not valid_enter:
given_number = input(msg).strip()
i... | 2,756 |
def _decode_panoptic_or_depth_map(map_path: str) -> Optional[str]:
"""Decodes the panoptic or depth map from encoded image file.
Args:
map_path: Path to the panoptic or depth map image file.
Returns:
Panoptic or depth map as an encoded int32 numpy array bytes or None if not
existing.
"""
if no... | 2,757 |
def splitstr(s, l=25):
""" split string with max length < l
"(i/n)"
"""
arr = [len(x) for x in s.split()]
out = []
counter = 5
tmp_out = ''
for i in xrange(len(arr)):
if counter + arr[i] > l:
out.append(tmp_out)
tmp_out = ''
counter = 5... | 2,758 |
def SplitRequirementSpecifier(requirement_specifier):
"""Splits the package name from the other components of a requirement spec.
Only supports PEP 508 `name_req` requirement specifiers. Does not support
requirement specifiers containing environment markers.
Args:
requirement_specifier: str, a PEP 508 req... | 2,759 |
def arctanh(var):
"""
Wrapper function for atanh
"""
return atanh(var) | 2,760 |
def plot_roc_per_class(model, test_data, test_truth, labels, title, batch_size=32, prefix='./figures/'):
"""Plot a per class ROC curve.
Arguments:
model: The model whose predictions to evaluate.
test_data: Input testing data in the shape the model expects.
test_truth: The true labels of... | 2,761 |
def predict_sentiment(txt: str, direc: str = 'models/sentiment/saved_models/model50') -> float:
"""
predicts sentiment of string
only use for testing not good for large data because
model is loaded each time
input is a txt string
optional directory change for using different models
returns a... | 2,762 |
def logfbank(signal,
samplerate=16000,
winlen=0.025,
winstep=0.01,
nfilt=26,
nfft=512,
lowfreq=0,
highfreq=None,
preemph=0.97,
winfunc=lambda x: numpy.ones((x,))):
"""Compute log Mel-filterbank energy ... | 2,763 |
def write_logging_statement():
"""Writes logging statements"""
time.sleep(1)
logger.debug('A debug statement')
time.sleep(1)
logger.info('An info statement')
time.sleep(1)
logger.warning('A warning statement')
time.sleep(1)
logger.critical('A critical warning statement')
time.sle... | 2,764 |
def UpdateBufferStyles(sheet):
"""Update the style used in all buffers
@param sheet: Style sheet to use
"""
# Only update if the sheet has changed
if sheet is None or sheet == Profile_Get('SYNTHEME'):
return
Profile_Set('SYNTHEME', sheet)
for mainw in wx.GetApp().GetMainWindows():
... | 2,765 |
def get_rmsd( pose, second_pose, overhang = 0):
"""
Get RMSD assuming they are both the same length!
"""
#id_map = get_mask_for_alignment(pose, second_pose, cdr, overhang)
#rms = rms_at_corresponding_atoms_no_super(pose, second_pose, id_map)
start = 1 + overhang
end = pose.total_residue()... | 2,766 |
def inverse(a: int, n: int):
"""
calc the inverse of a in the case of module n, where a and n must be mutually prime.
a * x = 1 (mod n)
:param a: (int)
:param n: (int)
:return: (int) x
"""
assert greatest_common_divisor(a, n) == 1
return greatest_common_divisor_with_coefficient(a, n)... | 2,767 |
def create_app():
"""Create the Flask application."""
return app | 2,768 |
def generate_prime_candidate(length):
""" Genera un integer impar aleatorimanete
param size: tamanio del numero deseado
return:integer
"""
p = big_int(length)
p |= (1 << length - 1) | 1
return p | 2,769 |
def test_read_record_member(memberAPI):
"""Test reading records."""
token = memberAPI.get_token(USER_EMAIL,
USER_PASSWORD,
REDIRECT_URL,
'/read-limited')
activities = memberAPI.read_record_member(USER_ORCID,
... | 2,770 |
def test_find_with_one_cond(mock_devices, generate_data):
"""
test find method with one cond
:param cond: condition to filter devices.
like : where("sdk")==19 the details syntax
See more at: http://
:type cond: where
:return: len of device
"""
mock_devices.return_value = genera... | 2,771 |
def PathPrefix(vm):
"""Determines the prefix for a sysbench command based on the operating system.
Args:
vm: VM on which the sysbench command will be executed.
Returns:
A string representing the sysbench command prefix.
"""
if vm.OS_TYPE == os_types.RHEL:
return INSTALL_DIR
else:
return '... | 2,772 |
def _find_form_xobject_images(pdf, container, contentsinfo):
"""Find any images that are in Form XObjects in the container
The container may be a page, or a parent Form XObject.
"""
if '/Resources' not in container:
return
resources = container['/Resources']
if '/XObject' not in resour... | 2,773 |
def get_next_valid_seq_number(
address: str, client: SyncClient, ledger_index: Union[str, int] = "current"
) -> int:
"""
Query the ledger for the next available sequence number for an account.
Args:
address: the account to query.
client: the network client used to make network calls.
... | 2,774 |
def apps_list(api_filter, partial_name, **kwargs):
"""List all defined applications. If you give an optional command line
argument, the apps are filtered by name using this string."""
params = {}
if api_filter:
params = {"filter": api_filter}
rv = okta_manager.call_okta("/apps", REST.get, pa... | 2,775 |
def jacquez(s_coords, t_coords, k, permutations=99):
"""
Jacquez k nearest neighbors test for spatio-temporal interaction.
:cite:`Jacquez:1996`
Parameters
----------
s_coords : array
(n, 2), spatial coordinates.
t_coords : array
(n, ... | 2,776 |
def array2tensor(array, device='auto'):
"""Convert ndarray to tensor on ['cpu', 'gpu', 'auto']
"""
assert device in ['cpu', 'gpu', 'auto'], "Invalid device"
if device != 'auto':
return t.tensor(array).float().to(t.device(device))
if device == 'auto':
return t.tensor(array).float().to... | 2,777 |
def to_json(graph):
"""Convert this graph to a Node-Link JSON object.
:param BELGraph graph: A BEL graph
:return: A Node-Link JSON object representing the given graph
:rtype: dict
"""
graph_json_dict = node_link_data(graph)
# Convert annotation list definitions (which are sets) to canonica... | 2,778 |
def export(df: pd.DataFrame):
"""
From generated pandas dataframe to xml configuration
:param df: computed pandas dataframe
:return:
"""
return df | 2,779 |
def has_same_attributes(link1, link2):
"""
Return True if the two links have the same attributes for our purposes,
ie it is OK to merge them together into one link
Parameters:
link1 - Link object
link2 - Link object
Return value:
True iff link1 and link2 have compatible attribu... | 2,780 |
def test_signals_creation(test_df, signal_algorithm):
"""Checks signal algorithms can create a signal in a Pandas dataframe."""
test_df_copy = test_df.copy()
original_columns = test_df.columns
# We check if the test series has the columns needed for the rule to calculate.
required_columns = Api.re... | 2,781 |
def com_google_fonts_check_fontv(ttFont):
"""Check for font-v versioning."""
from fontv.libfv import FontVersion
fv = FontVersion(ttFont)
if fv.version and (fv.is_development or fv.is_release):
yield PASS, "Font version string looks GREAT!"
else:
yield INFO,\
Message("... | 2,782 |
def test_qplad_integration_af_quantiles():
"""
Test QPLAD correctly matches adjustmentfactor and quantiles for lat, dayofyear and for a specific quantile
The strategy is to bias-correct a Dataset of ones, and then try to
downscale it to two gridpoints with QPLAD. In one case we take the
adjustment ... | 2,783 |
def get_prev_day(d):
"""
Returns the date of the previous day.
"""
curr = date(*map(int, d.split('-')))
prev = curr - timedelta(days=1)
return str(prev) | 2,784 |
def copy_function(old_func, updated_module):
"""Copies a function, updating it's globals to point to updated_module."""
new_func = types.FunctionType(old_func.__code__, updated_module.__dict__,
name=old_func.__name__,
argdefs=old_func.__defaults__,
... | 2,785 |
def test_app_sanity_check_fail(app_scaffold, dev_db): # noQA
"""Create an application and see we don't start if migrations are not run."""
execute_ws_command('pserve', app_scaffold, assert_exit=1) | 2,786 |
def update_diseases(all_diseases: Dict[StateYearPair, StrItemSet], cursor: MySQLdb.cursors.Cursor):
"""
Fetches rows from cursor and updates all_diseases with the rows
Doesn't return anything, but updates all_diseases directly
:param all_diseases: dict from place and time to set of diseases at that time... | 2,787 |
def get_random_color():
"""
获得一个随机的bootstrap颜色字符串标识
:return: bootstrap颜色字符串
"""
color_str = [
'primary',
'secondary',
'success',
'danger',
'warning',
'info',
'dark',
]
return random.choice(color_str) | 2,788 |
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
Implement a single forward step of the LSTM-cell as described in Figure (4)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
c_prev ... | 2,789 |
def save_department_data(department_data, scraper, location):
"""Write department data to JSON file.
Args:
department_data: Dictionary of department data.
scraper: Base scraper object.
location: String location output files.
"""
filename = department_data['code']
filepath = ... | 2,790 |
def logged_run(cmd, buffer):
"""Return exit code."""
pid = Popen(cmd, stdout=PIPE, stderr=STDOUT)
pid.wait()
buffer.write(pid.stdout.read())
return pid.returncode | 2,791 |
def download_file(project, bucket, orig_file_name, temp_file_name):
"""Download a file stored in a Google Cloud Storage bucket to the disk"""
client = storage.Client(project=project)
bucket = client.get_bucket(bucket)
blob = bucket.blob(orig_file_name)
blob.download_to_filename(temp_file_name)
... | 2,792 |
def createPListFile(mapname,image):
"""
Create a xml plist file from sprite sheet image.
:param mapname the name of file with information about frame of animation.
:param image the image info of sprite sheet generated
"""
if __debug__ :
print "Creating Plist file"
... | 2,793 |
def _decode_and_format_b64_string(b64encoded_string, item_prefix=None,
current_depth=1, current_index=1):
"""Decode string and return displayable content plus list of decoded artifacts."""
# Check if we recognize this as a known file type
(_, f_type) = _is_known_b64_prefix(... | 2,794 |
def buildDMG():
"""
Create DMG containing the rootDir
"""
outdir = os.path.join(WORKDIR, 'diskimage')
if os.path.exists(outdir):
shutil.rmtree(outdir)
imagepath = os.path.join(outdir,
'python-%s-macosx'%(getFullVersion(),))
if INCLUDE_TIMESTAMP:
imagepath... | 2,795 |
def create_iam_role(iam_client):
"""Create an IAM role for the Redshift cluster to have read only access to
S3.
Arguments:
iam_client (boto3.client) - IAM client
Returns:
role_arn (str) - ARN for the IAM Role
"""
# Create the role if it doesn't already exist.
try:
p... | 2,796 |
def pony(var, wrapper, message):
"""Toss a magical pony into the air and see what happens!"""
wrapper.send(messages["pony_toss"].format(wrapper.source))
# 59/29/7/5 split
rnd = random.random()
if rnd < 0.59:
pony = messages.get("pony_land", 0)
elif rnd < 0.88:
pony = messages.ge... | 2,797 |
def cone_face_to_span(F):
"""
Compute the span matrix F^S of the face matrix F,
that is, a matrix such that
{F x <= 0} if and only if {x = F^S z, z >= 0}.
"""
b, A = zeros((F.shape[0], 1)), -F
# H-representation: A x + b >= 0
F_cdd = Matrix(hstack([b, A]), number_type=NUMBER_TYPE)... | 2,798 |
def show_progress_bar(progress, start_time, msg):
"""
Well, it's a fancy progress bar, it looks like this:
Msg: 50.0% [=========================> ] in 0.9s
:param progress: range 0 to 100
:param start_time: looks like time.time()
:param msg: message to show
... | 2,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.