content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def apply_hardmask_with_map(input, attention, mask):
""" Apply any number of attention masks over the input.
input: [batch, num_objs, visual_features] = [b, o ,v]
attention: [batch, num_objs, glimpses] = [b, o ,g]
return: masked_input, masked_weight
"""
b, o, v = input.shape
# r... | 41,400 |
def _make_merge_query(increment_table_id, target_table_id):
"""merge incremental_load to existing target_table"""
client = bigquery.Client()
#try ge target table columns for merge, if not possible then it means it does not exist so just copy instead
try:
table = client.get_table(target_table_id)... | 41,401 |
def delete_alert(id):
"""
delete an alert and associated thread from the database
"""
alert = Alert.query.get(id)
if alert is None:
return {'message': 'Alert ' + str(id) + ' does not exist'}, 404
# delete associated thread
delete_thread(id)
# delete alert
db.session.delete(al... | 41,402 |
def data_file_read_calltree(filename):
"""
Extracts the calltree of a fuzzer from a .data file.
This is for C/C++ files
"""
read_tree = False
function_call_depths = []
tmp_function_depths = {
'depth' : -2,
'function_calls' : []
}
with open(fil... | 41,403 |
def group(iterable, key):
"""
groupby which sorts the input, discards the key and returns the output
as a sequence of lists.
"""
for _, grouped in groupby(sorted(iterable, key=key), key=key):
yield list(grouped) | 41,404 |
def test_wrong_model_type():
"""
Test of predict_output() and predict_gradient() when the model type is
unknown.
"""
input = np.random.rand(5, 1)
input_scaler = MinMaxScaler()
input_scaler.fit(input)
model = MLPClassifier()
try:
predict_output(model, input)
assert ... | 41,405 |
def bidirected(DAG):
"""Return a graph with an opposing edge added for every edge in DAG."""
return skeleton(DAG).to_directed() | 41,406 |
def match_funcs(qt_funcs):
"""
Convert function names scraped from Qt to their *actual* representation.
The function names we scrape from the Functions window Qt table actually
use the underscore character ('_') as a substitute for a variety of
different characters.
For example, a function nam... | 41,407 |
def get_census_data(independent_var, dependent_var):
"""
Returns a dict containing the data for the requested variables in a table format
:param census_vars: the chosen variable
:return:
"""
# Adjust the names of the variables for querying
if dependent_var == PAYPEREMP:
dependent_va... | 41,408 |
def clear_generic_text_badge(node: hou.Node):
"""Clear the generic text badge from the node.
:param node: The node to clear the badge from.
:return:
"""
with hou.undos.disabler():
# Try to remove the user data from the node.
try:
node.destroyUserData(_ht_generic_text_ba... | 41,409 |
def validate_object(x):
"""This function validates an object x that is supposed to represent an object
inside an image, and throws an exception on failure.
Specifically it is checking that:
x['polygon'] is a list of >= 3 integer (x,y) pairs representing the corners
of the polygon i... | 41,410 |
def test_update_anon_org(client, jwt, session, keycloak_mock): # pylint:disable=unused-argument
"""Assert that an org can be updated via PUT."""
headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.staff_admin_role)
rv = client.post('/api/v1/users', headers=headers, content_type='application/json')
... | 41,411 |
def generate_chirp_exp(dur, freq_start, freq_end, Fs=22050):
"""Generation chirp with exponential frequency increase
Notebook: C1/C1S3_Dynamics.ipynb
Args:
dur (float): Length (seconds) of the signal
freq_start (float): Start frequency of the chirp
freq_end (float): End frequency o... | 41,412 |
def email_startup(url):
"""Send an notification message via email notifying about the system startup.
"""
# Prepare email
subject = 'INFO - Security system is up and running'
body = 'Nothing to worry about. This message is sent after the security system starts up. Take a peak: %s' % str(url)
... | 41,413 |
def _swap(b, h, k):
"""
Procedure swaps b[h] and b[k]
Parameter b: The list to rearrange
Precondition: b is a mutable sequence (e.g. a list).
Parameter h: The first position to swap
Precondition: h is an int and a valid position in b
Parameter k: The second position to swap
Preconditi... | 41,414 |
def get_geoId(row: str, geo_map: dict) -> str:
"""
Dataframe utility function to map DC geoId based on latitude, longitude
"""
loc = f"{str(row['Latitude'])},{str(row['Longitude'])}"
try:
return ', '.join(geo_map[loc])
except:
print(f"{loc} -- does not exist in the map") | 41,415 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Generate bbox output from a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU id(s) to use',
default='0', type=str)
parser.add_argument('--def', dest='pr... | 41,416 |
def update_cm_working_file(source_file, target):
"""Copies source file to target and stages in git. Returns True on success."""
print('<<Copy {} to {}>>'.format(source_file, target))
try:
shutil.copyfile(source_file, target)
except OSError as ex:
print('Exception copying file: {}'.format... | 41,417 |
def farthest(pts, xlims, ylims, n):
""" Find the 'n' points that lie farthest from the points given
in the region bounded by 'xlims' and 'ylims'.
'pts' is an array of points.
'xlims' and 'ylims are tuples storing the maximum and minimum
values to consider along the x and y axes."""
# There are a... | 41,418 |
def structure_of_node_tabl_poltree():
"""Info about content of NODE_TABLE.
Returns
-------
decription : STR. Information on node table with inital node.
"""
description = """Trees are fully saved in Node_Table (list of lists)
Structure des Node_table
- Each knot is one list that cont... | 41,419 |
def test_dangerous_code_should_give_0_score():
"""Dangerous model that attempts to open a file should not get the compile score even with a valid code."""
task = util.load_programmatic_task(TASK_MODULE_NAME)
results_data = task.evaluate_model(DangerousModel())
for rd in results_data:
assert rd.s... | 41,420 |
def vis_ss_barplot(m, s, sample, hyperparams, stats=None, t_on=None, t_off=None, with_ss=True, with_params=True, voltage_trace=None,
test_idx=None, case=None, title=None, date_today=None, counter=0, save_fig=False, legend_offset=0.0,
axss=None, axmemparams=None, axsynparams=N... | 41,421 |
def divisores_n(n):
"""
Función para calcular los divisores del número entero y mostrar
lista con los divisores.
Args: número "n" entero positivo.
Salida: lista con todos los divisores de dicho número "n".
"""
lista=[]
for i in range(1,n+1):
if n % i ==0:
... | 41,422 |
def test_retry_loop_max_continue_on_success(mock_time_sleep):
"""Retry loops breaks out of loop on success."""
rd = RetryDecorator({'max': 3, 'sleep': 10.1})
context = Context({'k1': 'v1'})
mock = MagicMock()
mock.side_effect = [ValueError('arb'), None]
with patch_logger('pypyr.dsl', logging.IN... | 41,423 |
def delta_to_binary_mask(delta, k, hop_size, sample_rate, return_indeces=False):
"""returns a binary mask indicating the k segments with the largest norm / magnitude """
delta_factorization = TimeFrequencyTorchFactorization(delta,
frequency_segments=4,
... | 41,424 |
def clean(ctx, docs=True, bytecode=False):
"""
Cleans the project.
Parameters
----------
ctx : invoke.context.Context
Context.
docs : bool, optional
Whether to clean the *docs* directory.
bytecode : bool, optional
Whether to clean the bytecode files, e.g., *.pyc* fil... | 41,425 |
def get_patron_pid(record):
"""Get patron_pid from existing users."""
user = get_user_by_legacy_id(record["id_crcBORROWER"])
if not user:
# user was deleted, fallback to the AnonymousUser
anonym = current_app.config["ILS_PATRON_ANONYMOUS_CLASS"]()
patron_pid = str(anonym.id)
else... | 41,426 |
def get_QGroupBox():
"""QGroupBox getter."""
try:
import PySide.QtGui as QtGui
return QtGui.QGroupBox
except ImportError:
import PyQt5.QtWidgets as QtWidgets
return QtWidgets.QGroupBox | 41,427 |
def update_dict(orig_dict: dict, new_dict: collections.abc.Mapping) -> dict:
"""Updates exisitng dictionary with values from a new dictionory.
This function mimics the dict.update() function. However, it works for
nested dictionories as well.
Ref: https://stackoverflow.com/questions/3232943/update-val... | 41,428 |
def simulate_data(
covariates: int, scales: Sequence[int], levels: Sequence[int], singletons: float,
state: np.random.RandomState) -> Tuple[Array, Array, Array]:
"""Simulate IDs and data matrices."""
# simulate fixed effects
ids = np.array(list(itertools.product(*(np.repeat(np.arange(l), s)... | 41,429 |
def signup():
"""
User registeration endpoint.
---
parameters:
- name: fname
in: application/json
type: string
required: true
- name: lname
in: application/json
type: string
required: true
- name: email
in: applicat... | 41,430 |
def add_rating_to_dish(conn: pymysql.Connection, dish_id: int, user_id, stars: int):
"""
Adds a rating to the given dish
:param conn: The pymysql connection
:param dish_id: The id of the rated dish
:param user_id: The id of the rating user
:param stars: The amount of stars the user gave the dish
"""
cur = conn.... | 41,431 |
def create_strike_ingest_job_message(ingest_id, strike_id):
"""Creates a message to create the ingest job for a strike
:param ingest_id: ID of the ingest
:type ingest_id: int
:param strike_id: The ID of the strike
:type strike_id: int
"""
message = CreateIngest()
message.create_inge... | 41,432 |
def update_pytest_fixture(settings):
""" """
lines = list()
fixture_file = settings.RESOURCE_TARGET_DIRECTORY / "tests" / "fixtures.py"
with open(str(fixture_file), "r", encoding="utf-8") as fp:
for line in fp:
if "ROOT_PATH =" in line:
parts = list()
... | 41,433 |
def create_data(nfac0, # [Number of facet 0 elements -- rows/persons]
nfac1, # [Number of facet 1 elements -- columns/items]
ndim, # [Number of dimensions to create]
seed = None, # [<None,int,{'Fac0':<None,int,array>,'Fac1':<None,int,array>}> => generates coordinate... | 41,434 |
def load_database() -> pd.DataFrame:
"""
Loads data from hplib_database.
Returns
-------
df : pd.DataFrame
Content of the database
"""
df = pd.read_csv(cwd()+r'/hplib_database.csv')
return df | 41,435 |
def ensure_windows_file_path_format_encoding_as_url(path: str) -> str:
"""Relevant for Windows where a file path name should be "file://path/to/file.html" instead of "file://path\\to\\file.html" ."""
output = path.replace("\\", "/") # Raw replace backslash with slash.
# Handle exception for "file:///C:/pa... | 41,436 |
def _predict(rfields_rec, rt_clf, input_dir, output_dir):
""" This function loads test data, recommends research fields, and
generates output json file.
"""
print('Test data: {}'.format(input_dir))
print('Loading test data...')
parsed_pubs_test = load_rcc_test_dataset(input_dir)
test_lis... | 41,437 |
def main():
"""CLI entrypoint"""
logger = get_logger(prepend_timestamp=False, log_init=False)
warnings = False
root_dir = Path(__file__).parent.parent
patches_dir = root_dir / 'patches'
config_bundles_dir = root_dir / 'config_bundles'
journal = ExplorationJournal(
# bundle paths n... | 41,438 |
def status():
"""Get the status of all temcagt nodes"""
temcagt("status") | 41,439 |
def init_logger(log_level=logging.WARNING):
"""Initialize logger.
Args:
log_level (int): logging level
May be (in order of increasing verboseness):
logging.CRITICAL or 50
logging.ERROR or 40
logging.WARNING or 30
logging.INFO or 20
... | 41,440 |
def index():
"""
index page for WebUI
Returns:
rendered HTML page
"""
data = load_messages().message_contents
return render_template("index.html", data=data, encoded_data=data) | 41,441 |
def psnr(x, pred_x, max_val=255):
"""
PSNR
"""
val = tf.reduce_mean(tf.image.psnr(x, pred_x, max_val=max_val))
return val | 41,442 |
def across_series_nearest_neighbors(Ts, Ts_idx, subseq_idx, m):
"""
For multiple time series find, per individual time series, the subsequences closest
to a query.
Parameters
----------
Ts : list
A list of time series for which to find the nearest neighbor subsequences that
are ... | 41,443 |
def get_boundary_from_response(response):
""" Parses the response header and returns the boundary.
:param response: response containing the header that contains the boundary
:return: a binary string of the boundary
"""
# Read only the first value with key 'content-type' (duplicate keys are al... | 41,444 |
def get_message(message):
"""{
'pattern': None,
'type': 'subscribe',
'channel': 'my-second-channel',
'data': 1L,
}"""
if not message:
return
logging.info('MSG: %s', message)
data = message.get('data', {})
return json.loads(data) | 41,445 |
def parent_node(selector):
"""
Finds the parent_node of the given selector.
"""
if not get_instance():
raise Exception("You need to start a browser first with open_browser()")
return parent_node_g(get_instance(), selector) | 41,446 |
def getPairCategory(rollSorted):
"""
Converts a roll's ordered list of frequencies to the pairwise hand
category.
"""
if rollSorted[0] == 6:
return "six-of-a-kind"
elif rollSorted[0] == 5:
return "five-of-a-kind"
elif rollSorted[0] == 4 and rollSorted[1] == 2:
retur... | 41,447 |
def allocz(size):
"""Alloc zeros with range"""
return [0 for _ in range(size)] | 41,448 |
def uint_to_little_endian_bytearray(number, size):
"""Converts an unsigned interger to a little endian bytearray.
Arguments:
number -- the number to convert
size -- the length of the target bytearray
"""
if number > (2 ** (8 * size) - 1):
raise ValueError("Integer overflow")
nle = [... | 41,449 |
def to_alu_hlu_map(input_str):
"""Converter for alu hlu map
Convert following input into a alu -> hlu map:
Sample input:
```
HLU Number ALU Number
---------- ----------
0 12
1 23
```
ALU stands for array LUN number
hlu stands... | 41,450 |
def debug(func):
"""Decorator to debug a function's inputs and outputs. Uses the built-in 'logging' module.\n
Inputs are logged via `decorate.debug.debug_input`, and follow the format: \n
`'Datetime' | ['action'] 'function' | args=(args,) | kwargs={kwargs:values}`
Logged input example:
`2021... | 41,451 |
def randomize(jet):
"""build a random tree"""
jet = copy.deepcopy(jet)
leaves = np.where(jet["tree"][:, 0] == -1)[0]
nodes = [n for n in leaves]
content = [jet["content"][n] for n in nodes]
nodes = range(len(nodes))
tree = [[-1, -1] for n in nodes]
pool = [n for n in nodes]
next_id... | 41,452 |
def stream_into(
fn: t.Callable[[StreamData], None],
stream: str,
group: str,
consumer: t.Optional[str] = None,
concurrency: int = mp.cpu_count(),
) -> None:
"""Feed entries from a Redis stream into a callable fn()
Imagining a Redis stream as an infinite iterator, stream_into() applies
... | 41,453 |
def run_command(command):
""" Run command """
try:
res = subprocess.run(
command,
capture_output=True,
text=True,
check=True,
shell=True,
)
out = res.stdout
except subprocess.CalledProcessError as exc:
out = exc.output, exc.stderr, exc.returncode
return out | 41,454 |
def get_vt_retrohunt_files(vt_key: str, r_id: str, limit: Optional[int] = 100):
"""Retrieve file objects related to a retrohunt from VT."""
url = f"https://www.virustotal.com/api/v3/intelligence/retrohunt_jobs/{r_id}/matching_files?limit={limit}"
data = vt_request(api_key=vt_key, url=url)
if "error" in... | 41,455 |
def proj_make_3dinput_v2(project, angle = 15, start_slice = [0,0,0], crop_slice = [0.75, 0.625, 0.625]):
"""
This function unprojects 2d data into 3d voxel at different angles/views and do crop.
:param project: 2d image input
:param angle: the angle of different view. set max(1) as 0.
:param... | 41,456 |
def _ListUrlRootFunc(cls, args_tuple, thread_state=None):
"""Worker function for listing files/objects under to be sync'd.
Outputs sorted list to out_file_name, formatted per _BuildTmpOutputLine. We
sort the listed URLs because we don't want to depend on consistent sort
order across file systems and cloud prov... | 41,457 |
async def test_import_migration(hass, aiohttp_client, aioclient_mock, current_request):
"""Test if importing step with migration works."""
old_entry = MockConfigEntry(domain=DOMAIN, unique_id=123, version=1)
old_entry.add_to_hass(hass)
await setup_component(hass)
entries = hass.config_entries.asyn... | 41,458 |
def topological_sort(digraph):
"""Link in with Topological sort."""
from ch07.digraph_search import topological_sort as ts
return ts(digraph) | 41,459 |
def get_test_case(clazz, test_case_list=None, prefix='test_'):
"""
添加指定测试类中的测试用例
:param clazz:
:param test_case_list:
:return []:
"""
method_list = dir(clazz)
for method in method_list:
if method.startswith(prefix):
test_case_list.append(clazz(method)) | 41,460 |
def reset_timer():
"""Reset the timer and the design to the original one"""
global reps
button_reset.grid_forget()
button_play.grid(column=1, row=3)
window.after_cancel(timer)
canvas.itemconfig(timer_text, text="00:00", fill="white")
title_label.config(text="Timer", bg=WORK_BG_C, fg=RED)
... | 41,461 |
def merge_scores(scores_test, scores_val):
"""
Aggregate scores
"""
scores_valtest = {}
for key in scores_test:
key_valtest = "final/" + key.split("/")[1]
if key.startswith("test/"):
keyval = "val/" + key.split("/")[1]
value = 0.5 * (scores_test[key]["value"] ... | 41,462 |
def extract_data_frame_from_file(data_path, filename):
"""
:param data_path: path of source file directory
:param filename: source file name
:return: pandas dataframe with file content
"""
file_path = os.path.join(data_path, filename)
return pd.read_csv(file_path, skiprows=1, sep=SEPARATOR) | 41,463 |
def validateDate(data, name, published):
"""
Verify that a date string is valid.
"""
# Verify that if published exists it's a valid date
date = parse_datetime(published)
if not date:
raise InvalidField(name, published)
return published | 41,464 |
def test_keyword__Table__1(address_book, browser):
"""The `Table` shows that initially no keywords are defined."""
browser.login('editor')
browser.open(browser.MASTER_DATA_URL)
browser.getLink('Keywords').click()
assert browser.KEYWORDS_LIST_URL == browser.url
assert '>No keywords defined yet.<'... | 41,465 |
def debug_error_message(msg):
"""Returns the error message `msg` if config.DEBUG is True
otherwise returns `None` which will cause Werkzeug to provide
a generic error message
:param msg: The error message to return if config.DEBUG is True
.. versionadded: 0.0.9
"""
if getattr(config, "DEBU... | 41,466 |
def join(
group_id: int,
db: Session = Depends(get_db),
user: UserModel = Depends(get_active_user),
):
"""Join the group."""
return service.join(db, group_id=group_id, user_id=user.id) | 41,467 |
def calc_correlation(cs, lab):
"""
calc the spearman's correlation
:param cs:
:param lab:
:return:
"""
rho, pval = spearmanr(cs, lab)
return rho | 41,468 |
def deploy(app: str):
"""Deploy model to a Flyte backend."""
typer.echo(f"[unionml] deploying {app}")
model = get_model(app)
model.remote_deploy() | 41,469 |
def normalize(df):
"""Pandas df normalisation
Parameters:
df (pd df) : input df
Returns:
result (pd df) : output df
"""
result = df.copy()
for feature_name in df.columns:
max_value = df[feature_name].max()
min_value = df[feature_name].min()
result[feat... | 41,470 |
def cbv_decorator(decorator):
"""
Turns a normal view decorator into a class-based-view decorator.
Usage:
@cbv_decorator(login_required)
class MyClassBasedView(View):
pass
"""
def _decorator(cls):
cls.dispatch = method_decorator(decorator)(cls.dispatch)
retu... | 41,471 |
def _shift_anchors(anchors, direction):
"""Shift anchors to the specified direction
"""
new_anchors = deepcopy(anchors)
if direction == 'center':
pass
elif direction == 'top':
heights = new_anchors[:,3] - new_anchors[:,1] + 1
heights = heights[:,np.newaxis]
new_ancho... | 41,472 |
def enumerate_all_features(dim: int, num_values: int) -> chex.Array:
"""Helper function to create all categorical features."""
features = jnp.array(list(itertools.product(range(num_values), repeat=dim)))
chex.assert_shape(features, [num_values ** dim, dim])
return features.astype(jnp.int32) | 41,473 |
def convert_pad_shape(pad_shape):
"""
Used to get arguments for F.pad
"""
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape | 41,474 |
def PotentialWalk(pos, tree, softening=0, no=-1, theta=0.7):
"""Returns the gravitational potential at position x by performing the Barnes-Hut treewalk using the provided octree instance
Arguments:
pos - (3,) array containing position of interest
tree - octree object storing the tree structure
... | 41,475 |
def setup():
"""Configures the paths of the DLLs"""
global _setup_loaded
if _setup_loaded:
return
os.environ['PATH'] = os.pathsep.join([os.environ['PATH'], str(magic_dir)])
os.environ['MAGIC'] = str(magic_dir.joinpath('magic.mgc'))
_setup_loaded = True | 41,476 |
def GetProjectUserEmail(git_repo):
"""Get the email configured for the project."""
output = RunGit(git_repo, ['var', 'GIT_COMMITTER_IDENT']).output
m = re.search(r'<([^>]*)>', output.strip())
return m.group(1) if m else None | 41,477 |
def decode_features(features_ext, resource_attr_range: Tuple[int, int]):
"""
Given matrix of features from extended configs, corresponding to
`ExtendedConfiguration`, split into feature matrix from normal
configs and resource values.
:param features_ext: Matrix of features from extended configs
... | 41,478 |
def get_event():
""" Get the event information of the group
:param room_id: the room_id of the group
"""
incoming = request.get_json()
event = Event.get_event_with_room_id(incoming['room_id'])
if event:
results = {'event_name': event.name,
'location': event.location, 'start_time'... | 41,479 |
def copy_decompress(source_fn):
"""Generate bash code to copy/decompress file to $TMPDIR.
"""
new_fn = os.path.basename(source_fn)
if source_fn.lower().endswith(".gz"):
new_fn = new_fn.strip(".gz")
cmd = "gunzip -C {source_fn} > $TMPDIR/{new_fn}"
elif source_fn.lower().endswith(".bz2... | 41,480 |
def test(model,X, y):
"""
Predicts given X dataset with given model
Returns mse score between predicted output and ground truth output
Parameters
----------
X: Test dataset with k features
y: Ground truth of X with k features
"""
return mse(model.predict(X).flatten... | 41,481 |
def set_time_of_last_turn(time: int):
"""
Set the time of the last turn
"""
store.time_of_last_turn = time | 41,482 |
def test_save(password_reset_token_factory):
"""
Saving the serializer with a valid token and password should reset
the associated user's password.
"""
token = password_reset_token_factory()
user = token.email.user
data = {"key": token.key, "password": "new_passw0rd"}
serializer = seri... | 41,483 |
def main(argv=None) -> None:
"""
Main function of loudify worker.
Args:
args: sys arguments
Returns:
none
"""
args = parse_args(argv)
setup_logging(args.loglevel)
_logger.info("Started loudify worker")
broker.main() | 41,484 |
def test_stateless_token_authentication_valid(rf, user):
"""Tests that StatelessTokenAuthentication returns a user if token is still valid"""
token = get_encoded_and_signed_subscription_token(user)
request = rf.get(
"api/v0/notification_settings", HTTP_AUTHORIZATION="Token {}".format(token)
)
... | 41,485 |
def solver(objectives):
"""Returns a solver for the given objective(s). Either a single objective
or a list of objectives can be provided.
The result is either an IKSolver or a GeneralizedIKSolver corresponding
to the given objective(s). (see klampt.robotsim.IKSolver and
klampt.robotsim.Gener... | 41,486 |
def bokeh_plot(ts, ys):
"""
Very experimental.
"""
from bokeh.plotting import figure, output_file, save
output_file("streams.html")
p = figure(plot_width=1200, plot_height=400, x_axis_type="datetime",
x_axis_label="Time",
y_axis_label="Number of publications")
... | 41,487 |
def model_fn_builder(config: NeatConfig):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params):
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name... | 41,488 |
def tail_generator(filename=os.path.expanduser("~/google.txt"), interval=0.5):
"""
Reads file and then `tails` it -- checking at interval seconds
Adapted from: http://code.activestate.com/recipes/157035-tail-f-in-python/
"""
with open(filename, 'r') as f:
while True:
where = f.te... | 41,489 |
def solve_case(rectangle, tree, io_obj):
"""
Main program to recursively fill a rectangle with pentominos
"""
return tuple(map(_solve_rect_with_x(rectangle)(tree)([
len(rectangle) // 2, len(rectangle) % 2,
len(rectangle[0]) // 2, len(rectangle[0]) % 2])(io_obj),
tupl... | 41,490 |
def keras_weights_to_caffemodel(keras_model):
"""
Only Implement the conv layer and fc layer
:param keras_model:
:return:
"""
net = caffe.Net()
layers = keras_model.layers
for layer in layers:
if type(layer) == keras.layers.Convolution2D:
w, b = layer.get_weights()
... | 41,491 |
def get_db():
"""
:return:
"""
db = getattr(g, "_database", None)
if db is None:
db = g._database = connect()
db.row_factory = make_dicts
return db | 41,492 |
def interpolate(X, Y, Z, x_coords, y_coords, factor=4, method='cubic'):
"""
:return: Interpolated X, Y, Z coordinate tuples, given by a factor, and a method
in `scipy.interpolate.griddata`
"""
X_f, Y_f, Z_f = X.flatten(), Y.flatten(), Z.flatten()
x_inter = scale(x_coords, factor=factor).resh... | 41,493 |
def weighted_rmsd(x, y, weights=None, dim=None, apply_nan_mask=True):
""" Compute weighted root-mean-square-deviation between two `xarray.DataArray` objects.
Parameters
----------
x, y : `xarray.DataArray` objects
xarray objects for which to compute `weighted_rmsd`.
weights : array_like, ... | 41,494 |
def _default_value(argument, default):
"""Returns ``default`` if ``argument`` is ``None``"""
if argument is None:
return default
else:
return argument | 41,495 |
def AutopilotControl(serial_ifc, throttle_SP, steer_SP, curr_data):
""" Autopilot interface provides direct control over throttle and steer
signals going to servo and motor via shared values. Autopilot is to be
stopped, when negative (breaking) throttle signal is detected.
"""
end = False
carSe... | 41,496 |
def setup(opp, config):
"""Set up the w800rf32 component."""
# Declare the Handle event
def handle_receive(event):
"""Handle received messages from w800rf32 gateway."""
# Log event
if not event.device:
return
_LOGGER.debug("Receive W800rf32 event in handle_receiv... | 41,497 |
def all_feature_functions():
"""
Returns all feature functions from the function module
:rtype list[callable]
:returns List of feature functions
"""
exclude = ['n_gram_frequency', 'term_frequency']
functions = []
for name in dir(features):
feature_function = getattr(features, nam... | 41,498 |
def unsupplied_buses(net, mg=None, slacks=None, respect_switches=True):
"""
Finds buses, that are not connected to an external grid.
INPUT:
**net** (pandapowerNet) - variable that contains a pandapower network
OPTIONAL:
**mg** (NetworkX graph) - NetworkX Graph or MultiGraph that rep... | 41,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.