anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
def s(self, s: ComType):
self._pwr = s | Set power as voltamps. If passed as a complex insulation_code no checking or manipulation of the insulation_code is completed. The existing insulation_code of self._pwr is overwritten. |
def image_needs_pushing(image):
d = docker_client()
try:
d.images.get_registry_data(image)
except docker.errors.APIError:
# image not found on registry, needs pushing
return True
else:
return False | Return whether an image needs pushing |
def _set_priority(self, v, load=False):
try:
t = YANGDynClass(v,base=np.uint8, is_leaf=True, yang_name="priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True)
except (TypeError, ValueError):
raise ValueError("""priority must be of a type compatible w... | Setter method for priority, mapped from YANG variable /input/LocatorRecord/priority (uint8) |
def test_auth_sharable_owned(self):
self.do_sharable(True, 'pattieblack', None, tenant='pattieblack') | Tests that an authenticated context (with is_admin set to False) can share an image it owns, even if it is not shared with it. |
def handle_build_error(error):
sys.stderr.write('Error running command `%s`. Returned %s.\n' % (
' '.join(error.argv), str(error.error_code))) | Prints an error message to stderr for BuildErrors. |
def show_scores(self):
for text in self.score_text:
text.draw() | Blit all the high score related text to the screen |
def zero(*_, **__) -> None:
return | take anything, return nothing |
def dt_last_update(self):
return self.last_update | return when was the last update. Once again this is used in the scraper to determine newly updated data. |
def dataproduct_contacts(self, ows_layer, session):
# collect contacts for layer and related GDI resources
gdi_oids = [ows_layer.gdi_oid]
if ows_layer.type == 'data':
# include data source
gdi_oids.append(
ows_layer.data_set_view.data_set.gdi_oid_data_sour... | Return contacts metadata for a dataproduct. |
def main():
handler = PlanetSourceHandler()
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_namespaces, 1)
parser.setContentHandler(handler)
parser.parse(sys.stdin)
print simplejson.JSONEncoder(indent=True).encode(handler.sources) | Main driver, parse the feed and output the JSON list of sources |
def main():
print_banner()
params = read_steering()
s, x, y, cur, theta = build_kinoshita()
s, x, y, cur, theta = read_centerline(s, x, y, cur, theta)
s, x, y, cur, theta = extend_centerline(s, x, y, cur, theta)
for t in range(TSTEPS+1):
cur, theta = tan2curv(s, x, y)
cur_ori = n... | Execute the workflow of pyRiverBed. |
def see_raw_data(city):
while True:
try:
see_raw_data_input = input('\nIn addition of the stats above, would you like to scroll through the raw data? (y/n)\n')
if see_raw_data_input not in ('y', 'n'):
raise Exception ('Invalid answer')
if see_raw_data_inp... | Allow to scroll through the raw data of the csv file selected |
def pile_shuffle(array, n):
result = []
for i in reversed(range(n)):
result += array[i::n]
return result | Shuffle a list by partition into n piles. |
def get_dates(raw_table) -> "list of dates":
dates = []
found_first = False
for i, dstr in enumerate([raw_table[i][0] for i in range(0, len(raw_table))]):
if dstr:
if len(dstr.split("/")) == 3:
d = datetime.datetime.strptime(dstr, '%m/%d/%Y')
... | Goes through the first column of input table and returns the first sequence of dates it finds. |
def get_sigma_map(start_x = 0,field_height=100,field_width=100,viewing_distance=12.0,screen_pixel_size=0.282,debug=False):
start_x_pixels = np.round(get_pixels_at_degrees(degrees=start_x,viewing_distance=viewing_distance,screen_pixel_size=screen_pixel_size))
optical_nodal_distance = 17.0 # mm from lens to fovea... | For each point on the image (image_height x image_width) returns the sigma associated with each point due to the offset from the fovea of the image. The average of all the sigmas may be used as an approximation to the full set of all sigmas. Each sigma is used as the basis for creating the J operator which is the weigh... |
def init_weights(m: Union[torch.nn.Conv3d, torch.nn.BatchNorm3d]) -> None:
import torch
if isinstance(m, torch.nn.Conv3d):
torch.nn.init.normal_(m.weight, 0, 0.01)
elif isinstance(m, torch.nn.BatchNorm3d):
torch.nn.init.constant_(m.weight, 1)
torch.nn.init.constant_(m.bias, 0) | Initialize the weights of a Pytorch module. |
def get_public_key_fingerprint(curve: object, temp_public_key: object) \
-> object:
vk = VerifyingKey.from_string(bytes.fromhex(temp_public_key), curve=curve)
uncompressed_pub_key = vk.to_string('uncompressed')
pub_key_hash_fingerprint = hashlib.sha256(uncompressed_pub_key)
return pub_key_ha... | Validate the public key if it is related to the given EC curve and formats the public key to a uncompressed byte string. Afterwards the function create a hash value of the uncompressed public key value |
def get_cosine_similarity(self, query: list):
question_vector = self.get_vector(query)
return cosine_similarity(question_vector, self.vectors).flatten() | Returns cosine similarity between the input question and our dataset questions |
def fusion_api_update_deployment_manager(self, body=None, uri=None, api=None, headers=None):
return self.dep_mgr.update(body=body, uri=uri, api=api, headers=headers) | Updates a Deployment Manager. [Arguments] |
def replace_accented(input_str):
nkfd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nkfd_form if not unicodedata.combining(c)]) | replace the accented char to unicode |
def last_executed_query(self, cursor, sql, params):
return super(DatabaseOperations, self).last_executed_query(cursor, cursor.last_sql, cursor.last_params) | Returns a string of the query last executed by the given cursor, with placeholders replaced with actual values. `sql` is the raw query containing placeholders, and `params` is the sequence of parameters. These are used by default, but this method exists for database backends to provide a better implementation according... |
def visit_List(self, node):
self.generic_visit(node)
if isinstance(node.ctx, ast.Load):
return to_call(to_attribute(self.operator, '__list__'), node.elts)
return node | Convert list literal to function call. |
def color(self):
return self._color | The color of this turtle. All subsequent draw commands (forward/back) draw using this color. If the color changes, it only affects future draw commands, not past ones. |
def is_horizontal(line:tuple)->bool:
return line[0][1] == line[1][1] | Determines if a line is horizontal. |
def conv2d_weight(input, weight_size, grad_output, stride=1, padding=0, dilation=1, groups=1):
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
in_channels = input.shape[1]
out_channels = grad_output.shape[1]
min_batch = input.shape[0]
grad_output = grad_output.con... | r""" Computes the gradient of conv2d with respect to the weight of the convolution. |
def CreateConfig(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Creates a new RuntimeConfig resource. The configuration name must be unique within project. |
def run( theNetwork ):
# set up and run the simulation
#cell_input = make_input_dict( theNetwork )
soln = run_simulation( theNetwork,
options.tfinal )
# if necessary, move tmp time series to proper file
# should always have a /var/tmp folder, right??
# TEMP = '/data/j... | options object is global |
def __init__(self):
self.items = [] | __init__ is used to establish baseline of calss for each instantiation |
def dist(self, x: torch.Tensor) -> torch.Tensor:
feature = self.feature_layer(x)
adv_hid = F.relu(self.advantage_hidden_layer(feature))
val_hid = F.relu(self.value_hidden_layer(feature))
advantage = self.advantage_layer(adv_hid).view(
-1, self.out_dim, self.atom_size... | Get distribution for atoms. |
def test_reset_to_remote_after_rebase(self) -> None:
(
self.repo_sandbox
.new_branch("branch-0")
.commit()
.push()
.new_branch("branch-1")
.commit()
.push()
.check_out("branch-0")
.commit()
)
... | Very unlikely case; can happen only in case of divergence of clocks between local and remote (which is simulated in this test). |
def color_segmentation(self):
cv.namedWindow("Segmentation parameters")
self.create_trackbar("h-u", "Segmentation parameters")
self.create_trackbar("h-l","Segmentation parameters")
self.create_trackbar("s-u","Segmentation parameters")
self.create_trackbar("s-l","Segmentation para... | This is a method to make the color segmentation of the image called 'fachada1.png', the segmentation will be using six different trackbars two per channel (H,S,V). |
def test_class_method() -> None:
assert inspect.signature(lmp.tknzr._bpe.BPETknzr.add_CLI_args) == inspect.signature(BaseTknzr.add_CLI_args) | Ensure class methods' signatures. |
def get_government_trading(gov_type: str, ticker: str = "") -> pd.DataFrame:
if gov_type == "congress":
if ticker:
url = (
f"https://api.quiverquant.com/beta/historical/congresstrading/{ticker}"
)
else:
url = "https://api.quiverquant.com/beta/live... | Returns the most recent transactions by members of government |
def appendvars(self,num_):
res = __library__.MSK_XX_appendvars(self.__nativep,num_)
if res != 0:
_,msg = self.__getlasterror(res)
raise Error(rescode(res),msg) | Appends a number of variables to the optimization task. appendvars(self,num_) |
def uturuncu_map(surfaceFile,dem,comp=2):
fig = plt.figure()
ax = fig.add_subplot(111)
#print(datadir)
#print(dem)
geosurface = pu.surface2geotiff(dem,surfaceFile,outname=None,comp=comp,nanval=-9999)
#load georeferenced fem output from pu.surface2geotiff
#geosurface = '/home/scott/research... | Plot transparent fem result on highres srt hillshade with summit and stations, etc comp=0,1,2,3 > ux, uy, uz, ur |
def get_hosts_fanout(self, target, listener_type): | Get all hosts for fanout from nameserver by target. |
def _op_and_(self, left: Any, right: Any) -> Any:
if isinstance(left, list):
# induce an intersect with Collection
return Intersect(left, right)
left, right = _recycle_left_right(left, right)
left = Series(left).fillna(False)
right = Series(right).fillna(False)
... | Mimic the & operator in R. This has to have Expression objects to be involved to work |
def densenet121(growth_rate=32, compression=1.0):
init = K.initializers.he_normal(seed=None)
X = K.Input(shape=(224, 224, 3))
batch_1 = K.layers.BatchNormalization()(X)
activation_1 = K.layers.Activation('relu')(batch_1)
conv_1 = K.layers.Conv2D(filters=64,
kernel_siz... | Function that builds the DenseNet121 architecture |
def compile_resources(resourcename="images", location="."):
res_count_ok = 0
res_count_ko = 0
for qrc_file in os.listdir(location):
# Loop through directory
if qrc_file.endswith(".qrc"):
# We have a candidate file
print(f"---> Found {qrc_file}")
# get the... | Compile the .qrc (Qt Designer resource files) into .py files. |
def bump_release(
self: _R,
release_type: Literal["major", "minor", "micro"] = VersionParts.MICRO,
inc: int = 1,
) -> _R:
if release_type == VersionParts.MAJOR:
return self.bump_major(inc)
if release_type == VersionParts.MINOR:
return self.bump_minor(i... | Get next release version. |
def shift_1_cust(self, sol_in1, cust, c_loc, curr_temp, sol_type1, sa_lns):
route_ing = copy.deepcopy(sol_in1[c_loc[0]])
route_new = route_ing
move_to_route = c_loc[0]
orgn_type1 = sol_type1[c_loc[0]]
origin_cost1 = check_violation(route_ing, orgn_type1)[1]
route_... | Try to move 1 customer to anywhere it can be put, and see if the move can cut the total cost. |
def compare(isamAppliance1, isamAppliance2):
ret_obj1 = get_all(isamAppliance1)
ret_obj2 = get_all(isamAppliance2)
return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2) | Compare the list of groups between two appliances |
def bin2dec(x):
return int(x, 2) | Convert binary string to decimal number. |
def get_config():
return json.loads(CONFIG_FILE.read_text()) | Return the parsed contents of the config file. |
def niw_ml(X, lambda_0, mu_0, kappa_0, nu_0, Z_0):
X = __check_2d_and_reshape(X)
ml = lgniwml(X, mu_0, lambda_0, kappa_0, nu_0, Z_0)
return ml | log Normal, NormalinverseWishart marginal likelihood |
def split_tag(elem, tags):
splited_tag = elem.split(TAG_SEP)
if len(splited_tag) > 1:
tag_prefix, tag = splited_tag
assert tag in tags.tags
assert tag_prefix in tags.iob
else:
tag = elem
tag_prefix = None
assert tag == tags.default
return tag_prefix, tag | split IOB2format tag on iobprefix and tag assert if default tag('O') is not allowed default tag assert if iobprefix not in allowed prefixes assert if tag not in allowed tags |
def test_badxvaluewithsets(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, {1, 2, 3}, 2, 3)
self.assertEqual(str(e.exception), 'x must be an integer') | This function tests for bad x value with sets |
def list(username, verbose, token=None, indent=None):
mapbox_api = _get_api()
mapbox_token = _get_token(token)
url = "{0}/tilesets/v1/{1}?access_token={2}".format(
mapbox_api, username, mapbox_token
)
r = requests.get(url)
if r.status_code == 200:
if verbose:
for tile... | List all tilesets for an account. By default the response is a simple list of tileset IDs. If you would like an array of all tileset's information, use the versbose flag. tilests list |
def numRunningProcesses():
try:
proc = subprocess.run("ps -Af|grep -i \"online2-wav-nnet3-latgen-faster\"", stdout=subprocess.PIPE, shell=True)
np = (len(str(proc.stdout).split("\\n")) - 3)
if(np == None):
np = 0
return np
except Exception ... | gets the number of runnning transcription processes |
def add_commit(self, commit):
sha1 = commit.hex
if sha1 in self._commits:
return self._commits[sha1]
title, separator, body = commit.message.partition("\n")
commit = {
'explored': False,
'sha1': sha1,
'name': GitUtils.abbreviate_sha1(sha1),... | Adds the commit to the commits array if it doesn't already exist, and returns the commit's index in the array. |
def prepare_session(self, writer, session):
# Get information about the CLIENT
session['client']['ip'], port = writer.get_extra_info('peername')
# Try Database connection
try:
self.connect_database(session)
except DbException as err:
LOG.debug('Could not p... | Prepare session; attempts database connection, verify provided credentials and validate. |
def generateStateTable(C, ruleSet, terminals, indexFunc):
#initialize the state dictionary
stateDict = {}
for i in range(len(C)):
stateDict[i] = {}
gotoDict = {}
for i in range(len(C)):
gotoDict[i] = {}
#compute the states
for state in range(len(C)):
for item in... | Generate an LR(1) state table |
def change_root(new_root, pathname):
if os.name == 'posix':
if not os.path.isabs(pathname):
return os.path.join(new_root, pathname)
else:
return os.path.join(new_root, pathname[1:])
elif os.name == 'nt':
(drive, path) = os.path.splitdrive(pathname)
if pat... | Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS. |
def get_dns_resource_for_domain_name(session, domain_name, dns_resource, hosted_zone):
if session is None:
return None
client = session.client('route53')
hosted_zone_id = get_hosted_zone_id(session, hosted_zone)
if hosted_zone_id is None:
print("Error: Unable to find Route 53 Hosted Zo... | gets to resource name attached to a domain name |
def drop_calculated_rates(df):
if not _all_na_or_values(df["so2_rate_measure_flg"], {"Calculated"}):
raise AssertionError()
if not _all_na_or_values(df["co2_rate_measure_flg"], {"Calculated"}):
raise AssertionError()
del df["so2_rate_measure_flg"], df["so2_rate_lbs_mmbtu"]
del df["co2_... | Drop these calculated rates because they don't provide any information. If you want these, you can just use a view. |
def prox(self, x, lmbda=1):
return proj_nneg(x) | Projection onto the nonnegative reals (negatives set to zero). |
def jointly_transformed_equally_distributed(
class1: Av, class2: Av, n: int = 6, dim: int = 2
) -> Iterator[Tuple[Tuple[str, ...], Tuple[str, ...]]]:
return (
(tuple(stat[0] for stat in stats1), tuple(stat[0] for stat in stats2))
for stats1, stats2 in combinations(
... | Check if a combination of statistics in one class is equally distributed to any combination of statistics in the other class, up to a max length. |
def drag(source, dest, speed=1000):
m = PyMouse()
m.press(*source)
time.sleep(0.1)
# number of intermediate movements to make for our given speed
npoints = int(sqrt((dest[0]-source[0])**2 + (dest[1]-source[1])**2 ) / (speed/1000))
for i in range(npoints):
x = int(source[0] + ((dest[0]-... | Simulates a smooth mouse drag |
def one_dim_index(self, i, j):
return int(i + j * self.nx) | Convert two dimensional index to 1d. |
def gamma_hat(self, xi_gamma_bar_hat):
_, gamma_bar_hat = tf.split(xi_gamma_bar_hat, num_or_size_splits=2, axis=-1)
gamma_hat = self.gamma_map.inverse(gamma_bar_hat)
return gamma_hat | A posteriori SNR estimate. |
def ultratio(chrlength, uniqueratio, chrtotalreads, frcount):
ultratio = chrlength * uniqueratio / (chrtotalreads - frcount)
return ultratio | ultraio = chrlength uniqueratio / chr_total_reads |
def setPlotTitle(self):
plot_title = self.input_plot_title.text()
if plot_title:
self.plot_title = self.input_plot_title.text()
# Redraw the plot with given title
if not self.plot_inverted:
self.drawPlot(self.data_x_axis, self.data_y_axis, self.label_x... | Sets the plot title when the button is clicked with the value present in the title input box |
def __init__(self, router, uri=None, host='', port=8082, simplex=False):
super(EventRelayHTTPC, self).__init__(uri)
self._router = router
self._queue = Queue()
self._event = threading.Event()
self._closing = False
self._queueEvent = threading.Event()
self._si... | Initialize a new HTTP client event passing object An HTTP client is associated with an existing event router, and sends all messages received from that router to the HTTP connection, and forwards all messages received from the HTTP connection to the router. Interaction with the indicated EventRouter object takes place ... |
def reduce2lat_seasonal( mv, seasons=seasonsyr, vid=None ):
if vid==None:
vid = 'reduced_'+mv.id
# Note that the averager function returns a variable with meaningless id.
# The climatology function returns the same id as mv, which we also don't want.
# The slicers in time.py require getBounds()... | as reduce2lat, but data is used only for time restricted to the specified season. The season is specified as an object of type cdutil.ties.Seasons, and defaults to the whole year. The returned variable will still have a time axis, with one value per season specified. |
def test_process_packet(self):
packet = {'a': 7}
self.assertEqual(self.foo.a, 4)
self.handler.process_packet(packet)
self.assertEqual(self.foo.a, 7)
packet = {'b': 9, 'a': 20}
self.handler.process_packet(packet)
self.assertEqual(self.foo.a, 20)
self.assert... | A test to see if the packets get processed correctly. |
def href(self, request) -> str:
raise NotImplementedError() | Compute and return the link. |
def donor_participant(self, donor_participant: Object):
self._donor_participant = donor_participant | Sets the donor_participant of this AllOfCreateClaimResponseClaim. |
def test_private(self):
content = self.unique()
self.assertViewBehavior(
{"cache_control_public": False, "get": content},
status_code=200,
content=content,
headers_exact={"Cache-Control": "private"}) | Check that the private cache control header is set on the resopnse. |
def to_dict(self, exclusions=[]) -> dict:
dump = {}
for (name, value) in self.__dict__.items():
if name == "data" and isinstance(value, pd.DataFrame):
df_dict = value.to_dict(orient="split")
dump[encoder(name)] = encoder(df_dict)
else:
... | Exports the data for storage in a json file. The encoding to a json serialisable form has to be defined, it is not applied as an encoder to the json funciton. Returns |
def make_move(self, move, player, board):
#nBoard = board.copy()
board[move] = player
for d in core.DIRECTIONS:
if self.find_bracket(move, player, board, d)!=None:
self.make_flips(move, player, board, d)
return board | Update the board to reflect the move by the specified player. |
def describe_sharding_network_address_with_options(
self,
request: dds_20151201_models.DescribeShardingNetworkAddressRequest,
runtime: util_models.RuntimeOptions,
) -> dds_20151201_models.DescribeShardingNetworkAddressResponse:
UtilClient.validate_model(request)
query = {}
... | This operation supports sharded cluster instances only. |
def get_subcommand_query(query_str: str) -> Optional[SubcommandQuery]:
if not query_str:
return None
# spilt:
# "subcommand_name rest of query" -> ["subcommand_name", "rest of query""]
query_parts = query_str.strip().split(None, maxsplit=1)
if len(query_parts) < 2:
query_str = ""
... | Determine whether current query is of a subcommand. If so first returned the corresponding SubcommandQeury object. |
def serialize(self) -> bytes:
headers = "\r\n".join(
f"{header}: {value}" for header, value in self.headers.items()
)
return (
f"HTTP/1.0 {self.status} {STATUS_CODES[self.status]}\r\n"
f"{headers}\r\n"
"\r\n"
).encode("utf-8") | Returns HTTP response as raw bytes |
def generate_dataset(
datasets, networks, parents, mode='train', mean=None,
verbose=1, **params):
# Parameters
classes = params.setdefault('classes', [-1,0,1])
data_type = params.setdefault('data_type', 'spikes')
thres = params.setdefault('thres', 150.0)
target = params.setdefault('target',... | Generates a balanced set of training examples from one or more datasets. |
def filter_string(self):
logger.info("Information Gathering Finished!")
pattern_street = re.compile(r'[A-Za-z]+\s?\w+(?=\s[Nn]o\s\d+$) |'
r' [A-Za-z]+\s?\w+\s?[A-Za-z]+\s?[A-Za-z]+',
re.X) # street pattern
match_street = p... | Given the input string, tries to separate them into "street" & "house number" variables |
def makeinputstring(variabel):
if type(variabel) == int:
return str(variabel)
elif type(variabel) == float:
return str(int(float(variabel)))
else:
return str(variabel) | takes input and returns a string |
def UpdateVariable(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Updates an existing variable with a new value. |
def test_calculate_deuces(self):
board = ['4h', '5h', '8h', '7h', '9c']
hand = ['2s', '3s']
deuces = calculate_deuces(board, hand)
self.assertEqual(deuces[0], 7414)
self.assertEqual(deuces[1], 'High Card') | Method for getting the deuces score |
def optimizermt(self,server_,port_):
if isinstance(server_,unicode):
server_ = server_.encode("utf-8",errors="replace")
if isinstance(port_,unicode):
port_ = port_.encode("utf-8",errors="replace")
trmcode_ = ctypes.c_int32()
res = __library__.MSK_XX_optimizermt(self.__nativep,server_,port_,c... | Offload the optimization task to a solver server. optimizermt(self,server_,port_) |
def main(url, ip):
doc = {'url' : url}
#get the whois and domain info
print('[*] Getting whois')
doc = get_whois(doc)
#only continue checking stuff if we can actually resolve the address
if doc['ip'] != '':
#get ssl information if available
print('[*] Get certificate informatio... | this function will just combine all of the logic to create our doc and post to elasticsearch |
def test_sample_is_attached_to_patient(self):
self.assertEqual(self.test_patient.sample_set.all()[0], self.test_sample) | test that the many_to_one relationship is in place |
def has_finished(): | Return True if this request is considered finished, which is, when |
def calculate_ddct(self, baseline_time=0):
if baseline_time == 0:
baseline = self.baseline_data['dct'][0]
elif baseline_time == 96:
baseline = self.baseline_data['dct'][96]
elif baseline_time == 'average':
baseline = (self.baseline_data['dct'][0] + self.bas... | For the time being this is TGF/baseline and control/baseline The choice of 0 or 96 will make a difference |
def set_params2D(ima, p, xform = "xform.align2d"):
t = Transform({"type":"2D","alpha":p[0],"tx":p[1],"ty":p[2],"mirror":p[3],"scale":p[4]})
ima.set_attr(xform, t) | set 2D alignment parameters in the header alpha tx ty mirror scale |
def test_get_sets_by_category():
group_categories = get_sets_by_category(mb, "Group")
assert len(group_categories) == 5 | Ensure this function returns the correct number of entities with the specified tag. |
def create_timestamp(self):
return self._create_ts | the integer timestamp when this task is created. |
def _ensure_es_index(self, index):
if not self.elasticsearch.indices.exists(index):
try:
self.elasticsearch.indices.create(index=index)
except TransportError as error_msg:
self.logger.error(str(error_msg.error))
return False
sel... | Used internally when writing to elasticsearch to ensure a given index exists. |
def test_fk_id_in_filter(query):
john_doe = Reporter.objects.create(
first_name="John", last_name="Doe", email="john@doe.com"
)
jean_bon = Reporter.objects.create(
first_name="Jean", last_name="Bon", email="jean@bon.com"
)
sara_croche = Reporter.objects.create(
first_name="Sa... | Test in filter on an foreign key relationship. |
def __init__(self, parent=None):
super(ProgressDlg, self).__init__(parent)
self.setupUi(self) | Constructor parent reference to the parent widget QWidget |
def test_grdfilter_file_in_file_out():
with GMTTempFile(suffix=".nc") as tmpfile:
result = grdfilter(
"@earth_relief_01d",
outgrid=tmpfile.name,
region=[0, 180, 0, 90],
filter="g600",
distance="4",
)
assert result is None # return ... | grdfilter an input grid file, and output to a grid file. |
def insert(self, key, data):
debug.printMsg('Insert for "' + key + '" With data: ' + str(data) )
# if there is no root node
if not self.root:
debug.printMsg("No root was found, create one")
self.root = Node(key, data)
else:
debug.printMsg("Root was fou... | This function will insert data into the BST using a log_2(n) algorithm |
def generate_test_settings(tmpdir, dataset):
# When `tmpdir` is a path convert it to a string
if isinstance(tmpdir, py._path.local.LocalPath):
tmpdir = str(tmpdir)
test_settings = {
'datasets': {
'mnist': {
'train': {
'images... | Temporarily overwrite the settings with test settings. This allows to use test datasets for testing. |
def __repr__(self):
return str(self.data) | Convert Node to string |
def test_badyvaluewithtuple(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, 2, (1, 2), 3)
self.assertEqual(str(e.exception), 'y must be an integer') | This function tests for bad y value with tuple |
def greedy_initial(self):
sol = [] # [[0;2;5;0;4;6;0],[],...]
sol_veh_type = [] # corresponding vehicle type for the solution
route_way_time = []
to_vist = [i+1 for i in range(store_num - 1)] # [1,5,8,...]
itr = 0
while len(to_vist) > 0 and itr < 500:
... | Generate an initial solution based on the Timeoriented Nearestneighbor heuristic proposed by Solomon. |
def __init__(
self,
feature_map: FeatureMap,
weight: Union[Parameter, Tensor],
bias_module: Optional[Module] = None,
input_transform: Optional[TInputTransform] = None,
output_transform: Optional[TOutputTransform] = None,
):
super().__init__()
self.feat... | r"""Initializes a GeneralizedLinearPath instance. |
def update(self, current, values=None):
values = values or []
for k, v in values:
if k not in self._values_order:
self._values_order.append(k)
if k not in self.stateful_metrics:
if k not in self._values:
self._values[k] = [
... | Updates the progress bar. |
def test_create_data_lookup_error(self):
with self.assertRaises(LookupError):
_ = create_data({"name": "fake_data"}) | Checks if create date raises lookup error when name is incorrect. |
def check_user_credentials(token, auth_url='https://accounts.okeanos.grnet.gr'
'/identity/v2.0'):
logging.info(' Test the credentials')
try:
auth = AstakosClient(auth_url, token)
auth.authenticate()
logging.info(' Authentication verified')
return AUTHENTICAT... | Identity,Account/Astakos. Test ~okeanos authentication credentials |
async def process_prune(
channel, amount, user_id: int, ctx=None, inter=None, allowed_mentions=None
):
user = await User.get(user_id)
if amount not in range(PRUNE_MIN, PRUNE_MAX):
return await send_message(
PRUNE_MIN,
PRUNE_MAX,
key="not_in_range",
use... | Process the prune/clear command. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.