content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_students(path):
""" Read a tab-separated file of students. The only required field is 'github_repo', which is this
student's github repository. """
students = [line for line in csv.DictReader(open(path), delimiter='\t')]
check_students(students)
return students | 7,300 |
def get_extended_attention_mask(
attention_mask: Tensor,
input_shape: Tuple[int],
device: torch.device,
is_decoder=False,
) -> Tensor:
"""
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
Arguments:
attention_mask (:obj:`to... | 7,301 |
def ci_generate(args):
"""Generate jobs file from a spack environment file containing CI info.
Before invoking this command, you can set the environment variable
SPACK_CDASH_AUTH_TOKEN to contain the CDash authorization token
for creating a build group for the generated workload and registering... | 7,302 |
def setup(c): # type: ignore
"""Set this project up for Development."""
c.run("ls -lah --color=yes .venv")
c.run("poetry env info --path")
c.run("poetry debug info")
c.run("poetry run pre-commit install") | 7,303 |
def getdiskuuidvm(diskuuid):
"""
get vm uuid from disk uuid and return it
"""
if debug:
print 'vm from disk uuid :',diskuuid
cmd='xe vbd-list vdi-uuid='+diskuuid
response=docmd(cmd).split('vm-uuid ( RO): ')
vmuuid=response[1].split('\n')[0]
return vmuuid | 7,304 |
def storedata():
""" Upload a new file """
#path = os.path.join(app.config['UPLOAD_DIR'],current_user.name)
path = os.path.join(app.config['UPLOAD_DIR'])
dirs = os.listdir(path)
if dirs!="": # If user's directory is empty
dirs.sort(key=str.lower)
if request.method == 'POST':
if... | 7,305 |
def run_fpp_locs(
build: Build,
parsed: argparse.Namespace,
_: Dict[str, str],
make_args: Dict[str, str],
):
"""Runs the fpp_locs command
Args:
build: build cache
parsed: parsed arguments object
_: cmake args, not used
make_args: make arguments passed to the fpp-... | 7,306 |
def adler32(string, start=ADLER32_DEFAULT_START):
"""
Compute the Adler-32 checksum of the string, possibly with the given
start value, and return it as a unsigned 32 bit integer.
"""
return _crc_or_adler(string, start, _adler32) | 7,307 |
def list_projects(sortBy=None, sortOrder=None, nextToken=None):
"""
Gets a list of build project names, with each build project name representing a single build project.
See also: AWS API Documentation
:example: response = client.list_projects(
sortBy='NAME'|'CREATED_TIME'|'LAST_MODIFI... | 7,308 |
def find_earliest_brs_idx(g: Grid, V: np.ndarray, state: np.narray, low: int, high: int) -> int:
"""
Determines the earliest time the current state is in the reachable set
Args:
g: Grid
V: Value function
state: state of dynamical system
low: lower bound of search range (inclu... | 7,309 |
def italic(s):
"""Returns the string italicized.
Source: http://stackoverflow.com/a/16264094/2570866
"""
return r'\textit{' + s + '}' | 7,310 |
def skip_if_disabled(func):
"""Decorator that skips a test if test case is disabled."""
@functools.wraps(func)
def wrapped(*a, **kwargs):
func.__test__ = False
test_obj = a[0]
message = getattr(test_obj, 'disabled_message',
'Test disabled')
if getatt... | 7,311 |
def _compare_keys(target: Any, key: Any) -> bool:
"""
Compare `key` to `target`.
Return True if each value in `key` == corresponding value in `target`.
If any value in `key` is slice(None), it is considered equal
to the corresponding value in `target`.
"""
if not isinstance(target, tuple):
... | 7,312 |
def parser(_, objconf, skip=False, **kwargs):
""" Parses the pipe content
Args:
_ (None): Ignored
objconf (obj): The pipe configuration (an Objectify instance)
skip (bool): Don't parse the content
kwargs (dict): Keyword arguments
Kwargs:
assign (str): Attribute to a... | 7,313 |
def predict_xr(result_ds, regressors):
"""input: results_ds as came out of MLR and saved to file, regressors dataset"""
# if produce_RI isn't called on data then you should explicitely put time info
import xarray as xr
import aux_functions_strat as aux
rds = result_ds
regressors = regressors.sel... | 7,314 |
def _set_chap_security(module, array):
"""Set CHAP usernames and passwords"""
pattern = re.compile("[^ ]{12,255}")
if module.params["host_user"]:
if not pattern.match(module.params["host_password"]):
module.fail_json(
msg="host_password must contain a minimum of 12 and a ... | 7,315 |
async def list_features(location_id):
"""
List features
---
get:
summary: List features
tags:
- features
parameters:
- name: envelope
in: query
required: false
description: If set, the returned list will be wrapped in an enve... | 7,316 |
def delete_hosts(ec2_conn, ipa_client, hostnames):
""" Unenrolls hosts from IPA and AWS """
for hostname in hostnames:
try:
ipa_client.unenroll_host(hostname=hostname)
except (KeyError, ipaclient.NotFoundError):
pass
ec2client.delete_instances(ec2_conn, hostnames=hos... | 7,317 |
def shot_start_frame(shot_node):
"""
Returns the start frame of the given shot
:param shot_node: str
:return: int
"""
return sequencer.get_shot_start_frame(shot_node) | 7,318 |
def word1(x: IntVar) -> UInt8:
"""Implementation for `WORD1`."""
return word_n(x, 1) | 7,319 |
def _getCols1():
"""
Robs Version 1 CSV files
"""
cols = 'Date,DOY,Time,Location,Satellite,Collection,Longitude,Latitude,SolarZenith,SolarAzimuth,SensorZenith,SensorAzimuth,ScatteringAngle,nval_AOT_1020_l20,mean_AOT_1020_l20,mean_AOT_870_l20,mean_AOT_675_l20,sdev_AOT_675_l20,mean_AOT_500_l20,mean_AOT_44... | 7,320 |
def extract_tmt_reporters(mzml_files: List[Path], output_path: Path, correction_factor_path: Path, num_threads: int = 1,
extraction_level: int = 3):
"""
Takes about 1.5 minute for a 700MB file with 40k MS2 scans
"""
if not output_path.is_dir():
output_path.mkdir(parents... | 7,321 |
def sendMail(sendTo, msg):
"""
To send a mail
Args:
sendTo (list): List of mail targets
msg (str): Message
"""
mail = smtplib.SMTP('smtp.gmail.com', 587) # host and port
# Hostname to send for this command defaults to the FQDN of the local host.
mail.ehlo()
mail.starttl... | 7,322 |
def main():
"""
main
"""
Session = sessionmaker(bind=engine)
session = Session()
NRFBase.metadata.create_all(engine)
sdk_dir = "developer.nordicsemi.com/nRF5_SDK/"
download_sdk(sdk_dir, "http://" + sdk_dir)
sdks = SDKs(sdk_dir)
for sdk_v, zip_path in sdks.dict.items():
sd... | 7,323 |
def run_primer3(sequence, region, primer3_exe: str, settings_dict: dict,
padding=True, thermodynamic_params: Optional[Path] = None):
"""Run primer 3. All other kwargs will be passed on to primer3"""
if padding:
target_start = region.padding_left
target_len = len(sequence) - regio... | 7,324 |
def plot_analytic(axespdf, axescdf,
z_cut, beta=2., f=1.,
jet_type='quark',
bin_space='lin', plotnum=0,
label='Analytic, LL'):
"""Plots the analytic groomed GECF cdf on axescdf,
and the groomed GECF pdf on axespdf.
"""
verify_bin_sp... | 7,325 |
def filter_safe_dict(data, attrs=None, exclude=None):
"""
Returns current names and values for valid writeable attributes. If ``attrs`` is given, the
returned dict will contain only items named in that iterable.
"""
def is_member(cls, k):
v = getattr(cls, k)
checks = [
n... | 7,326 |
def get_member_from_list():
"""
GET /lists/<address>/members/<member_address>
:return:
"""
req = client.lists_members.get(domain=domain, address="everyone@mailgun.zeefarmer.com",
member_address="zerreissen@hotmail.com")
print(req.json()) | 7,327 |
def checkUdimValue(udim):
"""None"""
pass | 7,328 |
def fixture_loqus_exe():
"""Return the path to a loqus executable"""
return "a/path/to/loqusdb" | 7,329 |
def setup_nat():
"""
Make sure IP forwarding is enabled
"""
import fabtools
fabtools.require.system.sysctl('net.ipv4.ip_forward', 1) | 7,330 |
def test_cases():
"""Some sample test cases"""
assert count('aba') == {'a': 2, 'b': 1}
assert count('abcddbacdb') == {'a': 2,'b': 3,'c': 2,'d': 3}
assert count('') == {}
print("Test Success!") | 7,331 |
def inference(tasks, name, convnet_model, convnet_weight_path, input_patch_size,
output_patch_size, output_patch_overlap, output_crop_margin, patch_num,
num_output_channels, dtype, framework, batch_size, bump, mask_output_chunk,
mask_myelin_threshold, input_chunk_name, output_c... | 7,332 |
def set_command_line_flags(flags: List[str]):
"""Set the command line flags."""
sys.argv = flags
FLAGS.unparse_flags()
FLAGS(flags) | 7,333 |
def get_reads_section(read_length_r1, read_length_r2):
"""
Yield a Reads sample sheet section with the specified R1/R2 length.
:rtype: SampleSheetSection
"""
rows = [[str(read_length_r1)], [str(read_length_r2)]]
return SampleSheetSection(SECTION_NAME_READS, rows) | 7,334 |
def dummy_user_as_group_manager(logged_in_dummy_user, dummy_group):
"""Make the dummy user a manager of the dummy-group group."""
ipa_admin.group_add_member(a_cn="dummy-group", o_user="dummy")
ipa_admin.group_add_member_manager(a_cn="dummy-group", o_user="dummy")
yield | 7,335 |
def RegisterCallback(callback, msgtype):
"""Register a callback method for the given message type
@param callback: callable
@param msgtype: message type
"""
if isinstance(msgtype, tuple):
mtype = '.'.join(msgtype)
else:
mtype = msgtype
if mtype not in _CALLBACK_REGISTRY:
... | 7,336 |
def validate(number):
"""Check if the number is valid. This checks the length, format and check
digit."""
number = compact(number)
if not all(x in _alphabet for x in number):
raise InvalidFormat()
if len(number) != 16:
raise InvalidLength()
if number[-1] == '-':
raise Inv... | 7,337 |
def find_atom(i):
"""
Set the anchor to the atom with index `i`.
"""
gcv().find_atom(i) | 7,338 |
def parse_directory(filename):
""" read html file (nook directory listing),
return users as [{'name':..., 'username':...},...] """
try:
file = open(filename)
html = file.read()
file.close()
except:
return []
users = []
for match in re.finditer(r'<b>([^<]+)</b>... | 7,339 |
def ShortAge(dt):
"""Returns a short string describing a relative time in the past.
Args:
dt: A datetime.
Returns:
A short string like "5d" (5 days) or "32m" (32 minutes).
"""
# TODO(kpy): This is English-specific and needs localization.
seconds = time.time() - UtcToTimestamp(dt)
minutes = int(se... | 7,340 |
def test_finder_installs_pre_releases_with_version_spec():
"""
Test PackageFinder only accepts stable versioned releases by default.
"""
req = InstallRequirement.from_line("bar>=0.0.dev0", None)
links = ["https://foo/bar-1.0.tar.gz", "https://foo/bar-2.0b1.tar.gz"]
finder = PackageFinder(links,... | 7,341 |
def _raxml(exe, msa, tree, model, gamma, alpha, freq, outfile):
"""
Reconstruct ancestral sequences using RAxML_.
:param exe: str, path to the executable of an ASR program.
:param msa: str, path to the MSA file (must in FASTA format).
:param tree: str, path to the tree file (must in NEWICK form... | 7,342 |
def dec_multiply(*args) -> Optional[Decimal]:
"""
Multiplication of numbers passed as *args.
Args:
*args: numbers we want to multiply
Returns:
The result of the multiplication as a decimal number
Examples:
>>> dec_multiply(3, 3.5, 4, 2.34)
Decimal('98.280')
>... | 7,343 |
def get_networks():
"""
Returns a list of all available network names
:return: JSON string, ex. "['bitcoin','bitcoin-cash','dash','litecoin']"
"""
return json.dumps([x[0] for x in db.session.query(Node.network).distinct().all()]) | 7,344 |
def consume(queue):
"""
"""
while True:
data = queue.get()
print(f"consume: {id(data)}")
queue.task_done() | 7,345 |
def test_no_update_existing(api: KeepApi, config: Config, fsync: FileSync) -> None:
"""Existing note files are not updated if id not in the updated list"""
fsync.start(None)
config.state = State.InitialSync
note = Note()
note.title = "My Note"
note.text = "Initial text"
fname = write_note(ap... | 7,346 |
def get_cache_key_generator(request=None, generator_cls=None, get_redis=None):
"""Return an instance of ``CacheKeyGenerator`` configured with a redis
client and the right cache duration.
"""
# Compose.
if generator_cls is None:
generator_cls = CacheKeyGenerator
if get_redis is None:
... | 7,347 |
def is_from_derms(output):
"""Given an output, check if it's from DERMS simulation.
Parameters
----------
output: str or pathlib.Path
"""
if not isinstance(output, pathlib.Path):
output = pathlib.Path(output)
derms_info_file = output / DERMS_INFO_FILENAME
if derms_info_... | 7,348 |
def create_property():
"""
Check setting some RDF node as an RDF:Property dependent on rdflib.
"""
g = rdflib.Graph()
node = rdflib.BNode()
rdflib_model.type_property(g, node)
assert (
list(g.triples((None, None, None)))[0] ==
node, rdflib.RDF.type, rdflib.RDF.Property
... | 7,349 |
def js_squeeze(parser, token):
"""
{% js_squeeze "js/dynamic_minifyed.js" "js/script1.js,js/script2.js" %}
will produce STATIC_ROOT/js/dynamic_minifyed.js
"""
bits = token.split_contents()
if len(bits) != 3:
raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % bi... | 7,350 |
def view_extracted_data() -> str:
"""
Display Raw extracted data from Documents
"""
extracted_data = read_collection(FIRESTORE_PROJECT_ID, FIRESTORE_COLLECTION)
if not extracted_data:
return render_template("index.html", message_error="No data to display")
return render_template("index.h... | 7,351 |
def get_lstm_trump_text():
"""Use the LSTM trump tweets model to generate text."""
data = json.loads(request.data)
sl = data["string_length"]
st = data["seed_text"]
gen_text = lstm_trump.generate_text(seed_text=st, pred_len=int(sl))
return json.dumps(gen_text) | 7,352 |
def calc_and_save_YLMs(measure_obj):
"""
COMPUTE YLMS SEQUENTIALLY AND SAVE.
xmiydivr = e^(-iφ)sin(θ) = (x - iy)/r
zdivr = cos(θ) = z/r
xmidivrsq = e^(-2iφ)sin^2(θ) = [(x - iy)/r]^2
zdivrsq = cos^2(θ) = [z/r]^2
..cu means cubed
..ft means to the fourth power
..fi means to the fifth p... | 7,353 |
def collect_bazel_rules(root_path):
"""Collects and returns all bazel rules from root path recursively."""
rules = []
for cur, _, _ in os.walk(root_path):
build_path = os.path.join(cur, "BUILD.bazel")
if os.path.exists(build_path):
rules.extend(read_bazel_build("//" + cur))
return rules | 7,354 |
def countSort(alist):
"""计数排序"""
if alist == []:
return []
cntLstLen = max(alist) + 1
cntLst = [0] * cntLstLen
for i in range(len(alist)):
cntLst[alist[i]] += 1 #数据alist[i] = k就放在第k位
alist.clear()
for i in range(cntLstLen):
while cntLst[i] > 0: #将每个位置的数据k循环输出多次
... | 7,355 |
def _FloatsTraitsBase_read_values_dataset(arg2, arg3, arg4, arg5):
"""_FloatsTraitsBase_read_values_dataset(hid_t arg2, hid_t arg3, hid_t arg4, unsigned int arg5) -> FloatsList"""
return _RMF_HDF5._FloatsTraitsBase_read_values_dataset(arg2, arg3, arg4, arg5) | 7,356 |
def TRI_Query(state=None, county=None,area_code=None, year=None,chunk_size=100000):
"""Query the EPA Toxic Release Inventory Database
This function constructs a query for the EPA Toxic Release Inventory API, with optional arguments for details such as the two-letter state, county name, area code, and year.... | 7,357 |
def get_monthly_schedule(year, month):
"""
:param year: a string, e.g. 2018
:param month: a string, e.g. january
:return schedule: a pd.DataFrame containing game info for the month
"""
url = f'https://www.basketball-reference.com/leagues/NBA_{year}_games-{month}.html'
page = requests.get(u... | 7,358 |
def test_erroring(mock_send_report, handler_that_errors, mock_context):
"""Assert that the agent catches and traces uncaught exceptions"""
iopipe = IOpipeCore()
assert iopipe.report is None
try:
iopipe.error(Exception("Before report is created"))
except Exception:
pass
assert iop... | 7,359 |
async def test_discovery_update_attr(opp, mqtt_mock, caplog):
"""Test update of discovered MQTTAttributes."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(opp, "openpeerpower", {}, entry)
data1 = (
'{ "name": "Beer",'
' "command_topic": "test_topic",'
' "json_a... | 7,360 |
def get_gzip_guesses(preview, stream, chunk_size, max_lines):
"""
:type preview: str
:param preview: The initial chunk of content read from the s3
file stream.
:type stream: botocore.response.StreamingBody
:param stream: StreamingBody object of the s3 dataset file.
:type chunk_size: in... | 7,361 |
def remove_user(ctx, username, endpoint):
"""Remove a user's access from a server
This command is used to remove a user from the system after they have been removed from the external auth provider.
This step is required because even if a user can no longer log in, the could in theory still exchange a PAT f... | 7,362 |
def commit(image):
"""
Commit changes from a poured container to an image
"""
if image != "None":
os.environ["maple_image"] = str(image)
Backend().container.commit() | 7,363 |
def make_preds_epoch(classifier: nn.Module,
data: List[SentenceEvidence],
batch_size: int,
device: str=None,
criterion: nn.Module=None,
tensorize_model_inputs: bool=True):
"""Predictions for more than one b... | 7,364 |
def array_3_1(data):
"""
功能:将3维数组转换成1维数组 \n
参数: \n
data:图像数据,3维数组 \n
返回值:图像数据,1维数组 \n
"""
# 受不了了,不判断那么多了
shape = data.shape
width = shape[0]
height = shape[1]
# z = list()
z = np.zeros([width * height, 1])
for i in range(0, width):
for j in range(0, heigh... | 7,365 |
def UpdateString(update_intervals):
"""Calculates a short and long message to represent frequency of updates.
Args:
update_intervals: A list of interval numbers (between 0 and 55) that
represent the times an update will occur
Returns:
A two-tuple of the long and short message (respectively) corr... | 7,366 |
def coalesce(*xs: Optional[T]) -> T:
"""Return the first non-None value from the list; there must be at least one"""
for x in xs:
if x is not None:
return x
assert False, "Expected at least one element to be non-None" | 7,367 |
def deleteqospolicy(ctx,
# Mandatory main parameter
qospolicyid):
"""You can use the DeleteQoSPolicy method to delete a QoS policy from the system."""
"""The QoS settings for all volumes created of modified with this policy are unaffected."""
cli_utils.establish_connection(ctx)
... | 7,368 |
def test_upgrade_db_2_to_3(data_dir, username):
"""Test upgrading the DB from version 2 to version 3, rename BCHSV to BSV"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
with creation_patch:
data.unlock(username, '123', create_new=True)
# Manually set ve... | 7,369 |
def check_phil(phil, scope=True, definition=True, raise_error=True):
"""
Convenience function for checking if the input is a libtbx.phil.scope
only or a libtbx.phil.definition only or either.
Parameters
----------
phil: object
The object to be tested
scope: bool
Flag to check if phil is a... | 7,370 |
def get_ssm_environment() -> dict:
"""Get the value of environment variables stored in the SSM param store under $DSS_DEPLOYMENT_STAGE/environment"""
p = ssm_client.get_parameter(Name=fix_ssm_variable_prefix("environment"))
parms = p["Parameter"]["Value"] # this is a string, so convert to dict
return j... | 7,371 |
def remove_tags(modeladmin, request, queryset):
"""Remove tags."""
logger.debug('MA: %s, request: %s', modeladmin, request)
for obj in queryset:
obj.tags.clear() | 7,372 |
def test_failure(database):
""" Test that its fails when cfda_number does not exists. """
# test for cfda_number that doesn't exist in the table
cfda = CFDAProgram(program_number=12.340)
det_award_1 = DetachedAwardFinancialAssistanceFactory(cfda_number="54.321")
det_award_2 = DetachedAwardFinancial... | 7,373 |
def get_default_date_stamp():
"""
Returns the default date stamp as 'now', as an ISO Format string 'YYYY-MM-DD'
:return:
"""
return datetime.now().strftime('%Y-%m-%d') | 7,374 |
def prepifg_handler(config_file):
"""
Perform multilooking and cropping on geotiffs.
"""
config_file = os.path.abspath(config_file)
params = cf.get_config_params(config_file, step=PREPIFG)
prepifg.main(params) | 7,375 |
def check_for_launchpad(old_vendor, name, urls):
"""Check if the project is hosted on launchpad.
:param name: str, name of the project
:param urls: set, urls to check.
:return: the name of the project on launchpad, or an empty string.
"""
if old_vendor != "pypi":
# XXX This might work f... | 7,376 |
def hook_mem_write(uc, access, address, size, value, data_entries):
"""Callback for memory write."""
is_64bit = (uc._mode == UC_MODE_64)
eip = uc.reg_read(UC_X86_REG_RIP if is_64bit else UC_X86_REG_EIP)
do_skip = False
# Decode instruction
insn = ida_ua.insn_t()
inslen = ida_ua.decode_in... | 7,377 |
def apply_file_collation_and_strip(args, fname):
"""Apply collation path or component strip to a remote filename
Parameters:
args - arguments
fname - file name
Returns:
remote filename
Raises:
No special exception handling
"""
remotefname = fname.replace(os.path.s... | 7,378 |
def constructRBFStates(L1, L2, W1, W2, sigma):
"""
Constructs a dictionary dict[tuple] -> torch.tensor that converts
tuples (x,y) representing positions to torch tensors used as input to the
neural network. The tensors have an entry for each valid position on the
race track. For each position (x,y),... | 7,379 |
def gather_data(path, save_file=None, path_json='src/python_code/settings.json'):
"""
Gather data from different experiments
:param path: path of the experiments
:param save_file: path if you want to save data as csv (Default None)
:param path_json: setting file
:return: dataframe
"""
ex... | 7,380 |
def tile_grid_intersection(
src0: DatasetReader,
src1: DatasetReader,
blockxsize: Union[None, int] = None,
blockysize: Union[None, int] = None
) -> tuple[Iterator[Window], Iterator[Window], Iterator[Window], Affine, int, int]:
"""Generate tiled windows for the intersection between two grids.
Gi... | 7,381 |
def etapes_index_view(request):
"""
GET etapes index
"""
# Check connected
if not check_connected(request):
raise exc.HTTPForbidden()
records = request.dbsession.query(AffaireEtapeIndex).filter(
AffaireEtapeIndex.ordre != None
).order_by(AffaireEtapeIndex.ordre.asc()).al... | 7,382 |
def brute_force(ciphered_text: str, charset: str = DEFAULT_CHARSET, _database_path: Optional[str] = None) -> int:
""" Get Caesar ciphered text key.
Uses a brute force technique trying the entire key space until finding a text
that can be identified with any of our languages.
**You should not use this ... | 7,383 |
def mk_data(yml,
sep_ext_kwargs=';', sep_key_val='='):
"""Generate data files from a YAML file.
Arguments
---------
yml : dict
YAML-generated dict containing data specifications.
sep_ext_kwargs : str
Separator for a file extension and pandas keyword args. (default ';')
... | 7,384 |
def SqZerniketoOPD(x,y,coef,N,xwidth=1.,ywidth=1.):
"""
Return an OPD vector based on a set of square Zernike coefficients
"""
stcoef = np.dot(zern.sqtost[:N,:N],coef)
x = x/xwidth
y = y/ywidth
zm = zern.zmatrix(np.sqrt(x**2+y**2),np.arctan2(y,x),N)
opd = np.dot(zm,stcoef)
return opd | 7,385 |
def build_voterinfo(campaign, state):
"""Render a tweet of voting info for a state"""
state_info = campaign.info_by_state[state]
num_cities = len(state_info[CITIES])
assert num_cities == len(set(state_info[CITIES])), f"Duplicate entries in CITIES for {state}."
city_ct = num_cities
effective_length = 0
tweet_tex... | 7,386 |
def test_check_badusernames(state: State):
"""Verify logged-in base_admin can test usernames, gets correct result - nonexistant user """
# Build auth string value including token from state
b_string = 'Bearer ' + state.state['base_admin']
assert len(b_string) > 24
auth_hdr = {'Authorization' : b_st... | 7,387 |
def blync_callback(
ctx: typer.Context,
light_id: int = typer.Option(
0,
"--light-id",
"-l",
show_default=True,
help="Light identifier",
),
red: int = typer.Option(
0,
"--red",
"-r",
is_flag=True,
show_default=True,
... | 7,388 |
def train_model(training_df, stock):
"""
Summary: Trains XGBoost model on stock prices
Inputs: stock_df - Pandas DataFrame containing data about stock price, date, and daily tweet sentiment regarding that stock
stock - String representing stock symbol to be used in training
Return value: T... | 7,389 |
def find_ext(files, ext):
"""
Finds all files with extension `ext` in `files`.
Parameters
----------
files : list
List of files to search in
ext : str
File extension
Returns
-------
dict
A dictionary of pairs (filename, full_filename)
"""
dic = defau... | 7,390 |
def create_test_node(context, **kw):
"""Create and return a test Node object.
Create a node in the DB and return a Node object with appropriate
attributes.
"""
node = get_test_node(context, **kw)
node.create()
return node | 7,391 |
def get_physical_id(r_properties):
""" Generated resource id """
bucket = r_properties['Bucket']
key = r_properties['Key']
return f's3://{bucket}/{key}' | 7,392 |
def entity_test_models(translation0, locale1):
"""This fixture provides:
- 2 translations of a plural entity
- 1 translation of a non-plural entity
- A subpage that contains the plural entity
"""
entity0 = translation0.entity
locale0 = translation0.locale
project0 = entity0.resource.pr... | 7,393 |
def process_block( cond, loglines, logname ):
"""Apply a block condition to lines of text
Parameters:
cond (a YAML thing): a condition
loglines (string): the contents of the log file
Raises:
LogCheckFail: if the block does not satisfy the condition
"""
err_return =''
diffco... | 7,394 |
def paris_topology(self, input_path):
"""Generation of the Paris metro network topology
Parameters:
input_path: string, input folder path
Returns:
self.g: nx.Graph(), Waxman graph topology
self.length: np.array, lengths of edges
"""
adj_file = open(input_path + "adj.dat", ... | 7,395 |
def show_layouts(kb_info_json, title_caps=True):
"""Render the layouts with info.json labels.
"""
for layout_name, layout_art in render_layouts(kb_info_json).items():
title = layout_name.title() if title_caps else layout_name
cli.echo('{fg_cyan}%s{fg_reset}:', title)
print(layout_art... | 7,396 |
def _rescale(vector):
"""Scale values in vector to the range [0, 1].
Args:
vector: A list of real values.
"""
# Subtract min, making smallest value 0
min_val = min(vector)
vector = [v - min_val for v in vector]
# Divide by max, making largest value 1
max_val = float(max(vector)... | 7,397 |
def censor_contig(contig_end, u_contigs, o_dict):
"""
removes the entries for both ends of a contig in a contig list and overlap dict
"""
for c_e in [contig_end, other_end(contig_end)]:
if c_e in u_contigs:
u_contigs.remove(c_e)
if c_e in o_dict:
o_dic = o_dict[c_... | 7,398 |
def validate_travel_dates(departure, arrival):
"""It validates arrival and departure dates
:param departure: departure date
:param arrival: arrival date
:returns: error message or Boolean status
"""
date_format = "%Y-%m-%dT%H:%M:%SZ"
status = True
error_message = ""
if datetime.str... | 7,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.