content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _get_max_year(out_id_list):
"""Return the current maximum year for the specified ouptut."""
try:
indicator = database.fetch_tables(['Indicator'])[0]
ind_list = indicator[indicator['fk_indicator_output'].isin(out_id_list)]['id'].tolist()
ind_str = ', '.join([str(i) for i in ind_list])... | 5,306,900 |
def leaky_relu_prime(Z, alpha=0.01):
"""Applies differentiation of leaky relu function to an array/value
Arguments
---------
Z: float/int/array_like
Original Value
alpha: float
Negative slope coefficient
Returns
-------
A: same shape as input
Value after applying diff ... | 5,306,901 |
def runas_exit(request):
"""
Exits impersonation mode by deleting the session variable. The middleware
will not apply to further requests.
"""
user_admin_page = None
if _SESSION_KEY in request.session:
user_admin_page = reverse('admin:auth_user_change',
args=[request.s... | 5,306,902 |
def get_command(command_name):
"""Return the command of the given name.
:param str command_name: The name of the command to search for.
:rtype: Command
"""
global _COMMANDS
return _COMMANDS[command_name] | 5,306,903 |
def graphe_polynome(x_min, x_max, *polynomes,
largeur=600, hauteur=400):
"""affiche le graphe de polynômes passés en argument,
entre x_min et x_max"""
if "calcule_polynome" not in globals():
print("*** La fonction 'calcule_polynome(P, x)' n'est pas définie !")
print("*** abandon")
... | 5,306,904 |
def prepare(client, task):
"""Apply Server Profile and update the node when preparing.
This method is responsible for applying a Server Profile to the Server
Hardware and add the uri of the applied Server Profile in the node's
'applied_server_profile_uri' field on properties/capabilities.
:param c... | 5,306,905 |
def add_options(parser):
""" Add --option options to parser """
parser.add_argument('-o', '--option',
dest='options',
action='append',
help='Topology option to use upon submit. For example,'
' "-o topology.debu... | 5,306,906 |
def neighbours_from_centre(k=1):
"""
Gets all neighbours from the cube point (0, 0, 0).
:param k: The distance max distance of neighbours.
:return: A set of cube coords.
"""
return neighbours((0, 0, 0), k) | 5,306,907 |
def suitable_threshold(window, desired_probability):
"""Use cumulative binomial distribution to find the number of identical
bases which we expect a nucleotide window-mer to have with the desired
probability"""
cumulative_p = 0.0
for matches in range(window, 0, -1):
mismatches = window - mat... | 5,306,908 |
def plot_smoothing_length(
snap: SnapLike,
indices: List[int],
fac: float = 1.0,
units: Union[str, Quantity] = None,
x: str = 'x',
y: str = 'y',
ax: Any = None,
**kwargs
) -> Any:
"""Plot smoothing length around particle.
Also works for plotting the accretion radius on a sink pa... | 5,306,909 |
def _run(cmd):
"""Invokes your algorithm."""
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, env=os.environ)
_, stderr = process.communicate()
return_code = process.poll()
if return_code:
error_msg = 'Return Code: {}, CMD: {}, Err: {}'.format(return_code, cmd, stderr)
raise ... | 5,306,910 |
def asarray(arraylike, strict=True):
"""
Converts arraylike objects to NumPy ndarray types. Errors if
object is not arraylike and strict option is enabled.
"""
if isinstance(arraylike, np.ndarray):
return arraylike
elif isinstance(arraylike, list):
return np.asarray(arraylike, dt... | 5,306,911 |
def parameter_map(parameter_map, fig=None, ax=None, alpha=1,
cmap='viridis', vmin=0, vmax=None, colorbar=True):
"""
This method will create a Matplotlib plot based on imshow to display the
given parameter map in different colors. The parameter map is plotted to
the current axis and fig... | 5,306,912 |
def factory(class_name: str = None, **kwargs):
"""Simple factory to create a class with attributes from kwargs"""
class FactoryGeneratedClass:
pass
rewrite = {
"__randint": lambda *args: randint(100_000_000, 999_999_999),
}
for key, value in kwargs.items():
if value in rew... | 5,306,913 |
def which_type(statement: StatementData, choices: Tuple[StatementKey, StatementKey]) -> str:
"""Return whichever of the choices of keys is in the statement.
Note: All policy statements must have exactly one of these keys, so this raises an error if
that isn't true.
"""
left, right = choices
ha... | 5,306,914 |
def counter(name: str, documentation: str, labels: tuple = ()) -> Type[Counter]:
"""Builds a counter with configured namespace / subsystem."""
return Counter(
name,
documentation,
labelnames=labels,
namespace=s.PROMETHEUS_NAMESPACE,
subsystem=s.PROMETHEUS_SUBSYSTEM,
... | 5,306,915 |
def test_good_input4():
""" Runs on good input """
run(DNA, './inputs/codons.rna', 'E-H----') | 5,306,916 |
def give_me_files():
"""
Show all json files is settings folder.
:return: list of files.
"""
path = CURRENT_PATH + "\\settings"
files = []
for r, d, f in os.walk(path):
for file in f:
if '.json' in file:
files.append(file)
return files | 5,306,917 |
def cached(producer):
"""Calls to a function wrapped with this decorator are cached using ``self.cache.lookup``"""
@functools.wraps(producer)
def wrapper(self):
return self.cache.lookup(data_path=os.path.join(self.category_name, producer.__name__),
plot=self, produc... | 5,306,918 |
def generate_linear_model_data(n=300):
"""
Generates n samples from a linear model with a small variability.
"""
m = randint(-3,3)
b = randint(-10,10)
x = np.random.rand(n)*100
errors = np.random.normal(0, .4, n) # Gaussian samples for errors
y = m*x+b + errors
return Message({'x':x... | 5,306,919 |
def prediction_error(X, y, obj_function=huber_approx_obj):
"""
Train GBMs to predict y from X.
Use obj_function during training, and test_error_function for the test evaluation.
"""
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=0.3)
regressor = xgb.... | 5,306,920 |
def get_staking_contracts(chain):
"""Returns list of supported staking contracts for the specified chain. Pulled from hardcoded values in contracts.json.
:param chain: network to query data for
:type chain: string e.g. 'testnet'
:return: list of supported staking contracts
:rtype: list
"""
... | 5,306,921 |
def listify(trace, length=-1):
"""
Takes a trace as an instance of int, slice, or list and returns a list
"""
if isinstance(trace, int) or isinstance(trace, str):
return [trace]
if isinstance(trace, slice):
if trace.stop < 0 and trace.step < 0 and length < 0:
length = abs... | 5,306,922 |
def downcast_numbers(data: pd.DataFrame):
"""Downcast numerics"""
def downcast(ser: pd.Series) -> pd.Series:
ser = pd.to_numeric(ser, downcast="signed")
ser = pd.to_numeric(ser, downcast="unsigned")
return ser
df_num = data.select_dtypes("number")
data[df_num.columns] = df_num.... | 5,306,923 |
def create_group(module, client):
"""
Creates a group.
module : AnsibleModule object
client: authenticated ionoscloud object.
Returns:
The group instance
"""
name = module.params.get('name')
create_datacenter = module.params.get('create_datacenter')
create_snapshot = module... | 5,306,924 |
def is_datetime_string(string: str) -> bool:
"""
Check if the string is date-like.
Parameters
----------
string : str
Returns
-------
is_date: bool
"""
from dateutil.parser import parse
try:
parse(string)
return True
except ValueError:
return F... | 5,306,925 |
def _determine_local_import_names(start_dir):
"""Determines all import names that should be considered "local".
This is used when running the linter to insure that import order is
properly checked.
"""
file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)]
return [
... | 5,306,926 |
def _seek_generator(f):
"""Yields seek position for each line.
Args:
f (file): the file object.
"""
yield 0
for line in f:
yield f.tell() | 5,306,927 |
def _train(dataset, initial_ckpt, supervison, learning_rate, logs_path, max_training_iters, save_step, display_step,
global_step, number_slices=1, volume=False, iter_mean_grad=1, batch_size=1, task_id=1, loss=1, momentum=0.9, resume_training=False, config=None, finetune=1):
"""Train network
Args:
... | 5,306,928 |
def getDatasetInfo(datasetName="MyDB"):
"""
Gets information related to a particular dataset (more info in http://www.voservices.net/skyquery).
:param datasetName: name of dataset (string).
:return: returns a dictionary containing the dataset information.
:raises: Throws an exception if the user is... | 5,306,929 |
async def send_reaction(client, room_id, event_id: str, reaction: str):
"""
Send a reaction to a specific event
:param client: (nio.AsyncClient) The client to communicate to matrix with
:param room_id: (str) room_id to send the reaction to (is this actually being used?)
:param event_id: (str) event_... | 5,306,930 |
def user_passes_test(
test_fn: Callable[["models.User"], bool],
exception: Exception = PermissionDenied(PERMISSION_REQUIRED_ERROR),
):
"""
Create a decorator for a function that checks if the user passes the given test.
Parameters
----------
test_fn : Callable[[models.User], bool]
T... | 5,306,931 |
def is_valid_perioddata(data):
"""Check that a dictionary of period data has enough information
(based on key names) to set up stress periods.
Perlen must be explicitly input, or 3 of start_date_time, end_date_time,
nper and/or freq must be specified. This is analogous to the input
requirements for ... | 5,306,932 |
def check_for_update(current_version, callback):
"""
Perform a plugin update check.
"""
update_thread = threading.Thread(
target=async_update_check,
args=(current_version, callback,),
name="UpdateChecker"
)
update_thread.start() | 5,306,933 |
def serve():
"""
Serve the index.html for the UI.
"""
text = textwrap.dedent(
"""
Unable to display Nectar UI - landing page (index.html) not found.
"""
)
return Response(content=text, media_type="text/plain") | 5,306,934 |
def convert(coeffs_in, normalization_in=None, normalization_out=None,
csphase_in=None, csphase_out=None, lmax=None):
"""
Convert an array of spherical harmonic coefficients to a different
normalization convention.
Usage
-----
coeffs_out = convert(coeffs_in, [normalization_in, normal... | 5,306,935 |
def list_runs(ctx, args):
"""List runs.
Run lists may be filtered using a variety of options. See below
for details.
By default, the last 20 runs are shown. Use `-a, --all` to show
all runs, or `-m` to show more 20 more runs. You may use `-m`
multiple times.
Run indexes are included in li... | 5,306,936 |
def plot_grid_3_path(gps_lon, gps_lat, alg_lon, alg_lat, alg_time, time, KF_lon, KF_lat, step_x, step_y):
"""
画出完整的路径图带有网格线和时间标签
:param gps_lon:
:param gps_lat:
:param alg_lon:
:param alg_lat:
:param time:
:param step:
:return:
"""
x_tickvals = np.arange(np.min(alg_lon), np.m... | 5,306,937 |
def showcase_unit(session):
"""Run the generated unit tests against the Showcase library."""
# Install pytest and gapic-generator-python
session.install('coverage', 'pytest', 'pytest-cov')
session.install('.')
# Install a client library for Showcase.
with tempfile.TemporaryDirectory() as tmp_d... | 5,306,938 |
def test_user_with_no_books_has_access_to_books_list(one_user):
"""Test that a User has access to a list of their books."""
assert isinstance(one_user.books, list)
assert len(one_user.books) == 0 | 5,306,939 |
def doubletrace(tt):
"""Determine the double trace corresponding to tt"""
(cn,vts,edgs,gp,prt) = skeleton(tt)
v = len(vts)
e = len(edgs)//2
# print(v,e)
ts = set(tt)
oriented = len(tt) == len(ts)
chi = v - e + 1
genus = 2 - chi
if oriented:
genus = genus//2
(anti,par) ... | 5,306,940 |
def get_job_definition(account, region, container_name, job_def_name, job_param_sagemakerendpoint, memoryInMB, ncpus,
role_name):
"""
This is the job definition for this sample job.
:param account:
:param region:
:param container_name:
:param job_def_name:
:param memoryInM... | 5,306,941 |
def get_documents():
"""
Queries a given page from Solr and sends them to the front end
:param page: The page number
:param num_per_page: Number of entries per page
:param sort_field: The field used for sorting (all fields in SolrDoc)
:param sort_order: asc / desc
:param search_term: string... | 5,306,942 |
def session_read_wamp_data_with_diff(con:Connection, eventId=None,tsBegin=None, num=10) -> list[dict]:
"""collect a number of messages from table WAMPDATA.
the first row of the result is the full data from the database and will be included "as is" (MessageType.STATE)
the following rows contain just the delt... | 5,306,943 |
def get_random_request():
"""Random test case.
This function sets up a random test case that differs depending on whether MPI capabilities
are available or not.
"""
num_tasks = np.random.randint(5, 25)
num_proc = np.random.randint(1, num_tasks)
# We need to check whether MPI was set up be... | 5,306,944 |
def test_return_false_with_maybe_container():
"""Ensures `is_io` function will return False for Maybe."""
assert is_io(Maybe.from_value(None)) is False | 5,306,945 |
def random_subsample(
data: np.ndarray, n_samples: int, random_state: Optional[int] = None
) -> Tuple[np.ndarray, np.ndarray]:
"""Random uniform subsample without replacement of data.
Parameters
----------
data
point cloud
n_samples
Number of points to sample.
random_state... | 5,306,946 |
def get_instance_ips():
"""
Function to get instance IPs of your servers.
Sometimes you'd want to do this, if your IPs are
allocated dynamically, e.g. an auto-scaling group
within AWS.
if you have only one system. you can simpley use localhost or its ip for that.
Returns: None
"""
r... | 5,306,947 |
def ellipse(shape):
"""
This function ...
:param shape:
:return:
"""
x_center, y_center, x_radius, y_radius, angle = ellipse_parameters(shape)
return Ellipse(Position(x_center, y_center), Extent(x_radius, y_radius), Angle(angle, u.Unit("deg"))) | 5,306,948 |
def __parse_db(db_exp: str) -> List[Union[str, int]]:
"""
Parse a DB directive returning its contents as a list.
:param db_exp: DB directive command.
:return: Contents of the db as the directive.
"""
db_exp_ = db_exp.split(" ", 1)[1]
db_params = [eval(param) for param in db_exp_]
params:... | 5,306,949 |
def trimap(adata: AnnData, *args, **kwargs):
"""\
Scatter plot with trimap basis.
Parameters
----------
adata: :class:`~anndata.AnnData`
an Annodata object.
%(scatters.parameters.no_adata|basis)s
Returns
-------
Nothing but plots the pca embedding of the adata o... | 5,306,950 |
def _fspath(path):
"""Return the path representation of a path-like object.
If str or bytes is passed in, it is returned unchanged. Otherwise the
os.PathLike interface is used to get the path representation. If the
path representation is not str or bytes, TypeError is raised. If the
provided path i... | 5,306,951 |
def border(img, amount=1, value=0):
"""
Adds requested amount of padding in each direction.
"""
if len(img.shape) == 3:
# Handle multiple channels.
h,w,c = img.shape
out = np.zeros((h+amount*2, w+amount*2, c), dtype=img.dtype)
for i in range(c):
out[:, :, i] = border(img[:, :, i], amount, ... | 5,306,952 |
def fibonacci():
"""
Fibonacci Sequence: Sum of successive terms, special case of a Lucas Sequence of the 1st kind\n
OEIS A000045
"""
a,b = 0,1
while True:
yield a
a, b = b, a+b | 5,306,953 |
def test2():
"""
Test that H and Hinv are stable numerical inverses.
"""
print "\nTEST 2"
## input ##
s = np.linspace(-20.,20.,2001)
k = 1.
##
## test H
x = s
y = H(s, k)
xnew = Hinv(y, k)
ynew = H(xnew, k)
for i in range(4):
xnew = Hinv(ynew, k)
ynew = H(xnew, k)
if False:
print "x = ", x
print ... | 5,306,954 |
async def test_setup_updates_from_ssdp(hass: HomeAssistant) -> None:
"""Test setting up the entry fetches data from ssdp cache."""
entry = MockConfigEntry(domain="samsungtv", data=MOCK_ENTRYDATA_WS)
entry.add_to_hass(hass)
async def _mock_async_get_discovery_info_by_st(hass: HomeAssistant, mock_st: str... | 5,306,955 |
def hcolor(data, thresholds):
""" Multicolor a graph according to thresholds
:param data: the data
:type data: list of tuples (info, value)
:param thresholds: dict of thresholds, format
{<threshold>: <color>,}
:type thresholds: dict
:return: the colored graph
:rtype: list of arrays
... | 5,306,956 |
def rank_documents(query, idx, years, citations, n=10, k=1.2, b=0.75, y=0.1, c=1):
"""
Rank documents according the ranking function score
"""
print('Finding relevant documents to the search term: "%s"' % query)
# Stem the query before passing into the score for standardization
stemmer = nltk.stem.porter.Porte... | 5,306,957 |
def get_unique_id(x):
"""Returns the creation number of the object 'x'. For objects created
by the program, it is globally unique, monotonic, and reproducible
among multiple processes. For objects created by a debug command,
this returns a (random) negative number. Right now, this returns 0
for a... | 5,306,958 |
def main():
"""Read command-line arguments and convert given digits between bases."""
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) == 3:
digits = args[0]
base1 = int(args[1])
base2 = int(args[2])
# Convert given digits between bases
resul... | 5,306,959 |
def test_ipo3_ipo_2(mode, save_output, output_format):
"""
International Purchase Order 3
"""
assert_bindings(
schema="boeingData/ipo3/ipo.xsd",
instance="boeingData/ipo3/ipo_2.xml",
class_name="PurchaseOrder",
version="1.1",
mode=mode,
save_output=save_ou... | 5,306,960 |
def add_to_act(actapi: act.api.Act, doc: Dict, output_format: Text = "json") -> None:
"""Add a report to the ACT platform"""
report_id: Text = doc["hexdigest"]
filename: Text = os.path.basename(doc.get("filename", "NN"))
title: Text = doc.get("title", filename)
indicators: Dict = doc.get("indicato... | 5,306,961 |
def topo2kml(topo_file_name, topo_type, color='00FF00'):
"""
Create a kml file putting a box around the region covered by a topofile.
Color is green by default.
"""
import os
from clawpack.geoclaw import topotools
topo = topotools.Topography(topo_file_name, topo_type=topo_type)
t... | 5,306,962 |
def euler_problem_6(n=100):
"""
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numb... | 5,306,963 |
def delete_wishlists(wishlist_id):
"""
Delete a Wishlist
This endpoint will delete a wishlist based the id specified in the path
"""
app.logger.info(f'Request to delete wishlist with id: {wishlist_id}')
wishlist = WishList.find(wishlist_id)
if wishlist:
wishlist.delete()
app.lo... | 5,306,964 |
def connect_db(config):
"""Connects to the database and initializes the client
Parameters:
config (Config): The Config containing the DB connection info
"""
if config.client is None:
# https://www.influxdata.com/blog/getting-started-python-influxdb/
config.client = DataFrameClient(h... | 5,306,965 |
def _parse_http_429_5xx_retry_after(result=None, **ignored):
"""Return seconds to throttle"""
assert result is not None, """
The signature defines it with a default value None,
only because the its shape is already decided by the
IndividualCache's.__call__().
In actual code path,... | 5,306,966 |
def inject_local_assets():
"""only ever run from forge-generate"""
return [
{'when': {'platform_is': 'ios'}, 'do': {'inject_local_assets': ()}},
{'when': {'platform_is': 'android'}, 'do': {'inject_local_assets': ()}},
] | 5,306,967 |
def retrieve_normally_documents(big_collection):
"""
"""
big_collection.documents() | 5,306,968 |
def makeSnap(datfile, pngfile, \
bHeader=True, \
m_sun=1.0, \
xrange=None, \
yrange=None, \
axis="a-e", \
m_cut=0., \
m_emp=0., \
size=10., \
color0="blue",\
color1="midnightblue") :
"""... | 5,306,969 |
def islamic_add(request):
""" Add new package and see the list of packages """
success_message, error_message = None, None
form = IslamicForm
islamics = Islamic.objects.all()
if request.method=="POST":
form = IslamicForm(request.POST)
if form.is_valid():
obj ... | 5,306,970 |
def details(id):
"""
This page allows recruiters to view and edit a member's details.
Methods:
GET
POST
Args:
id (int) - id of the member to examine
Returns:
rendered template 'details.html'
"""
if not current_user.recruiter and not current_user.mentor and ... | 5,306,971 |
def main():
"""Show the current OpenGL connection strings."""
GLUT.glutInit(sys.argv)
GLUT.glutInitContextVersion(3, 3)
GLUT.glutInitContextProfile(GLUT.GLUT_CORE_PROFILE)
GLUT.glutInitDisplayMode(
GLUT.GLUT_DOUBLE | GLUT.GLUT_RGBA | GLUT.GLUT_DEPTH)
win = GLUT.glutCreateWindow(b'NO TIT... | 5,306,972 |
def deploy_func_two_phase(imageList, thresh, nms, approach):
"""object detection pipeline for two-phase approach
Args:
imageList (list): list of image paths to predict
thresh (float): threshold value for detector
nms (float): nms threshold value
approach (object): informatio... | 5,306,973 |
def pa_cmd(args, cmd):
"""List lGTWs parser method.
usage: empower-ctl.py list-lgtws <options>
optional arguments:
-h, --help show this help message and exit
-g LGTW_EUID, --lgtw_euid LGTW_EUID
show results for specified lGTW id only
-c, --config ... | 5,306,974 |
def notas():
"""Renders the overview of the Notas state."""
usuario = mdl.Usuario.objects.get(user_id=session['user_id'])
trimestres = mdl.Trimestre.objects
trimestre = trimestres.get(id=session.get('trimestre_id'))
notas_trim = trimestre.notas # Notas de este trimestre
notas_trim.sort(key=lamb... | 5,306,975 |
def to_float(val):
"""
Parse a string to float
"""
return None if val in NULL_VALUES else float(val) | 5,306,976 |
def handle_args(args):
"""arg handle """
global IS_DOWNLOAD_ACTIVE, PATH
if args.update:
print ("Updating database...")
update_database()
print ("Update completed...")
if args.download:
IS_DOWNLOAD_ACTIVE = True
if args.check is None:
sys.exit(">>> -c... | 5,306,977 |
def freedom(L=5):
"""
DOES NOT DO ANYTHING
"""
return -1 | 5,306,978 |
def expected_config_dict():
"""Used to validate `self_check()` and `test_yaml_config()` outputs."""
config = {
"class_name": "InferredAssetGCSDataConnector",
"data_asset_count": 2,
"example_data_asset_names": ["directory", "path"],
"data_assets": {
"directory": {
... | 5,306,979 |
def get_num_classes(dataset_name: str) -> int:
"""
Get the number of supervised loss given a dataset name.
:param dataset_name: dataset name
:return: number of supervised class.
"""
if dataset_name == "cifar10":
return 10
elif "cifar100" in dataset_name:
return 100
else:
... | 5,306,980 |
def syn_gemm(A, B, C, mc, kc, nc, mr=1, nr=1, gepb_mode = gepb_simple):
"""
"""
cgepb = synppc.Program()
cpackb = synppc.Program()
proc = synppc.Processor()
gepb = SynGEPB(gepb_mode)
packb = SynPackB()
M, N = C.shape
K = A.shape[0]
nc = min(nc, N)
kc = min(kc, K)
mc = min(mc, M)
tA = ... | 5,306,981 |
def add_task(title):
"""
Purpose:
Add Task to the board in To Do list
Args:
title (string)
"""
# Create random label category
idLabels=[]
idLabels.append(random.choice(list(task_lbls.values())))
url = "https://api.trello.com/1/cards"
payloads = {'key': TR... | 5,306,982 |
def config_event():
"""Configure parameters for scraping."""
print('-=-Definição do evento-=-\n')
event = str(input(
'- Opções:\n'
'38 - 2017\n'
'39 - 2019\n'
'40 - 2021\n'
'Todos\n'
'Digite o número corresponden... | 5,306,983 |
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a... | 5,306,984 |
def read_csv(file_name, skip_header=True, char_det=False):
"""
CSVを読み込んで辞書を作成する。
1列目と2列目のみ処理をして3列目以降は無視をする。
Args:
file_name (str): CSVファイル名
skip_header (bool): 一行目をヘッダとしてスキップするかどうか
Returns:
dict: 作成した辞書
"""
db = {}
n = 0
if char_det:
# 文字コードの判定 (フ... | 5,306,985 |
def get_update_status(current_version: str, versions: Versions) -> str:
"""Given a version, determine the definitive status of the application."""
if not versions:
return ""
latest = get_latest_version(versions)
if not latest or StrictVersion(latest) <= StrictVersion(current_version):
r... | 5,306,986 |
def terminate_job(jobId=None, reason=None):
"""
Terminates a job in a job queue. Jobs that are in the STARTING or RUNNING state are terminated, which causes them to transition to FAILED . Jobs that have not progressed to the STARTING state are cancelled.
See also: AWS API Documentation
Exceptions
... | 5,306,987 |
def gh_projects_d(**kw): # pragma: no cover
"""
List projects in $GH_ROOT
"""
if kw['d']:
pdb.set_trace()
print(gh_projects_t(**kw)) | 5,306,988 |
def get_bsse_section(natoms_a, natoms_b, mult_a=1, mult_b=1, charge_a=0, charge_b=0):
"""Get the &FORCE_EVAL/&BSSE section."""
bsse_section = {
'FORCE_EVAL': {
'BSSE' : {
'FRAGMENT': [{
'LIST': '1..{}'.format(natoms_a)
},
{
... | 5,306,989 |
def apply_bucketize_op(x, boundaries, remove_leftmost_boundary=False):
"""Applies the bucketize op to every value in x.
x and boundaries are expected to be in final form (before turning to lists).
Args:
x: a `Tensor` of dtype float32 with no more than one dimension.
boundaries: The bucket boundaries re... | 5,306,990 |
def query_quadrangle(client, partition_key, *args):
"""
Iterates the values that fail within the defined quadrangle
for the geospatial key.
Arguments:
client - the Redis client instance
partition_key - the geospatial set key
bounds - the bounds as an array of [nw,se]
- or -
nw - the north we... | 5,306,991 |
def load_placement(placement_file):
"""
Loads VPR placement file. Returns a tuple with the grid size and a dict
indexed by locations that contains top-level block names.
"""
RE_PLACEMENT = re.compile(
r"^\s*(?P<net>\S+)\s+(?P<x>[0-9]+)\s+(?P<y>[0-9]+)\s+(?P<z>[0-9]+)"
)
RE_GRID_SIZ... | 5,306,992 |
def find_matching_geoloc_file(radiance_filename, myd03_dir):
"""
:param radiance_filename: the filename for the radiance .hdf, demarcated with "MYD02".
:param myd03_dir: root directory of MYD03 geolocational files
:return geoloc_filename: the path to the corresponding geolocational file, demarcated with... | 5,306,993 |
def license_path(licenses):
"""Get license path."""
# return license if there is exactly one license
return licenses[0] if len(licenses) == 1 else None | 5,306,994 |
def enable_caching(_option, _opt_str, _value, _parser):
"""Turns off caching by replacing the tree with one that only takes BlockingNodes"""
debug.debug("Enabling Caching")
# Feels filthy using the global keyword,
# but I can't figure another way to ensure that
# the code gets called and overwrites ... | 5,306,995 |
def main():
"""Run the program!"""
job = AbstractJob.init_from_environment()
(stdout, stderr) = job.run()
sys.stdout.write(stdout)
sys.stderr.write(stderr) | 5,306,996 |
def send_messages(messages, sent):
"""Wyświetla komunikat z listy i przenosi go na inną listę"""
message = 0
while messages:
msg = messages.pop()
message += 1
print(f"Komunikat nr {message}: {msg}")
sent.append(msg) | 5,306,997 |
def get_next_run(exp_dir):
"""
get run id by looking at current exp_dir
"""
next_run = 0
files = glob.glob(os.path.join(exp_dir, "*.log"))
for file in files:
filename = os.path.basename(file)
run = filename.split('.')[0]
id = int(run[3:])
if id >= next_run:
... | 5,306,998 |
def save_positions_recursively_up(user, request, field_data_cache, xmodule, course=None):
"""
Recurses up the course tree starting from a leaf
Saving the position property based on the previous node as it goes
"""
current_module = xmodule
while current_module:
parent_location = modulest... | 5,306,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.