code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_memory_scratch(): <NEW_LINE> <INDENT> return '/dev/shm'
Returns largest ramdisk available on this machine to this user.
625941de379a373c97cfae8b
def foo(bar): <NEW_LINE> <INDENT> bar = str(bar) <NEW_LINE> print('Function to do something with user input: "%s"' % bar) <NEW_LINE> return
foo dummy function, takes user input: bar
625941de507cdc57c6307026
def binary_op(self, op: str, p1: str, p2: str, single_prec=False) -> str: <NEW_LINE> <INDENT> if '0x' in p1 or '0x' in p2: <NEW_LINE> <INDENT> hex_form = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hex_form = False <NEW_LINE> <DEDENT> if '0x' in p1: <NEW_LINE> <INDENT> f1 = float.fromhex(p1) <NEW_LINE> <DEDENT> ...
Binary operation on p1 and p2 with the operation specified by op :param op: add, sub, mul, div :param p1: float number in hex :param p2: float number in hex :return:
625941de15fb5d323cde0e59
def fids_to_ids(self,data): <NEW_LINE> <INDENT> self.function('fids_to_ids') <NEW_LINE> return self.retrieve(data)
Find all aliases and/or synonyms for the specified FIG IDs. For each FIG ID, a hash will be returned that maps each ID type to a list of the IDs of that type.
625941de24f1403a92600ea8
def batch_set_data(self, indexes, data): <NEW_LINE> <INDENT> if not super().batch_set_data(indexes, data): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> rows = {ind.row() for ind in indexes} <NEW_LINE> db_map_data = self._make_db_map_data(rows) <NEW_LINE> self.add_items_to_db(db_map_data) <NEW_LINE> return True
Sets data for indexes in batch. If successful, add items to db.
625941def7d966606f6aa34d
def traverse(self, module, action): <NEW_LINE> <INDENT> if module.__name__ not in self.nodes: <NEW_LINE> <INDENT> logging.error("Module not registered.") <NEW_LINE> return <NEW_LINE> <DEDENT> sequence = [] <NEW_LINE> self.__trace(self.nodes[module.__name__], set(), sequence) <NEW_LINE> for node in reversed(sequence): <...
遍历访问模块的依赖,得到拓扑依赖序后,按顺序对每个依赖执行指定的action @param module: 模块 @param action: 对模块执行的行为
625941de1f037a2d8b946542
def __str__(self): <NEW_LINE> <INDENT> return "({},{},{})".format(self.tail, self.head, self.weight)
Returns the string representation of the edge. :return: the string representation of the edge.
625941de5fc7496912cc3cc3
def min_value(self): <NEW_LINE> <INDENT> return _vnl_vectorPython.vnl_vectorUI_min_value(self)
min_value(self) -> unsigned int
625941de6e29344779a62954
def setSelectedTab(self, index): <NEW_LINE> <INDENT> self._view.tabWidget.setCurrentIndex(index)
Set the tab to be selected.
625941defff4ab517eb2f783
def authorization_right_set(right, value): <NEW_LINE> <INDENT> auth_ref = c_void_p() <NEW_LINE> AuthorizationCreate(None, None, 0, byref(auth_ref)) <NEW_LINE> return AuthorizationRightSet( auth_ref, right.encode('ascii'), value.__c_void_p__(), None, None, None)
Set Authorization Right thanks to Tom Burgin https://gist.github.com/tburgin/77ebd114d59d368b0b4321ca7cf77767
625941ded10714528d60002b
def report_external_config_failure(self, host_uuid, error): <NEW_LINE> <INDENT> args = {'host': host_uuid, 'error': error} <NEW_LINE> LOG.error("External manifests failed on host: %(host)s. Error: %(error)s" % args) <NEW_LINE> conf = StorageBackendConfig.get_backend(self.dbapi, constants.SB_TYPE_EXTERNAL) <NEW_LINE> va...
Callback for Sysinv Agent
625941de2c8b7c6e89b35b04
def is_this_vendor(self, sys_info, host=None, credential=None, **kwargs): <NEW_LINE> <INDENT> result = sys_info <NEW_LINE> if host and credential: <NEW_LINE> <INDENT> if utils.is_valid_ssh_credential(credential): <NEW_LINE> <INDENT> user = credential['username'] <NEW_LINE> pwd = credential['password'] <NEW_LINE> <DEDEN...
Determine if the hostname is accociated witH this vendor. :param host: swtich's IP address :param credential: credential to access switch
625941debe8e80087fb20f83
def e_s(T): <NEW_LINE> <INDENT> a = 2.7798202e-6 <NEW_LINE> b = -2.6913393e-3 <NEW_LINE> c = 0.97920849 <NEW_LINE> d = -158.63779 <NEW_LINE> e = 9653.1925 <NEW_LINE> return a * T**4 + b * T**3 + c * T**2 + d * T + e
Parametrization of the saturation vapor pressure.
625941de50485f2cf553d0e0
def _areas_overlap_rect(self, rect1, rect2): <NEW_LINE> <INDENT> rect1lower, rect1upper = rect1 <NEW_LINE> rect2lower, rect2upper = rect2 <NEW_LINE> x1, z1 = rect1lower[0], rect1lower[2] <NEW_LINE> x2, z2 = rect1upper[0], rect1upper[2] <NEW_LINE> xx1, zz1 = rect2lower[0], rect2lower[2] <NEW_LINE> xx2, zz2 = rect2upper[...
Just a wrapper for _areas_overlap_cube that disregards the y axis. :param rect1 = object(cube): these are "cube" type. :param rect2 = object(cube): :return:
625941de99fddb7c1c9de6d5
def validate_password(password): <NEW_LINE> <INDENT> USER_PASS = re.compile(r"^.{3,20}$") <NEW_LINE> if USER_PASS.match(password): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> return "That wasn't a valid password."
Checks whether the given password is well-formed. Returns an error message or empty string if there is no error.
625941de5f7d997b87174de0
def __getitem__(self, key): <NEW_LINE> <INDENT> return self.__files[key]
Index into the files and retrieve the one specified by the key.
625941dea79ad161976cc48b
def pop(self): <NEW_LINE> <INDENT> if self.isEmpty(): <NEW_LINE> <INDENT> raise EmptyStackError("Stack is Empty: Trying to pop from an empty stack") <NEW_LINE> <DEDENT> self._top -= 1 <NEW_LINE> return self._list.pop()
Removes an item from the top of the stack modifying it. :return: item removed from the top of the stack. :raises: EmptyStackError if stack has no elements.
625941decad5886f8bd2731e
def getPlay(self): <NEW_LINE> <INDENT> return self.play
Return 1 if the game is still running else 0 if the game ended
625941de3617ad0b5ed6823b
def get_data(self, database, table, column): <NEW_LINE> <INDENT> sql_columns = '' <NEW_LINE> for i in range(len(column)): <NEW_LINE> <INDENT> sql_columns = sql_columns + column[i] <NEW_LINE> if i < len(column)-1: <NEW_LINE> <INDENT> sql_columns += ', ' <NEW_LINE> <DEDENT> <DEDENT> sql = F"select {sql_columns} from {dat...
返回所需要得数据 Args: database: str型的一个库名 table: str型的一个表名 column: str单元列表 Returns: 返回[ (str, str, ...), (str, str, ...)...] -1: error
625941de851cf427c661a851
def mask_shape_border (DS,shape_file_address): <NEW_LINE> <INDENT> def conv_lat(DS): <NEW_LINE> <INDENT> if 'lat' in DS: <NEW_LINE> <INDENT> DS.rio.set_spatial_dims(x_dim="lon", y_dim="lat", inplace=True) <NEW_LINE> <DEDENT> elif 'latitude' in DS: <NEW_LINE> <INDENT> DS.rio.set_spatial_dims(x_dim="longitude", y_dim="la...
This function takes a netcdf file and a shape and delivers the netcdf cropped according to the shape. Assumption of EPSG: 4326 required. Parameters: DS: Dataset with multiple climatic features (.nc); shape_file_address: a directory to the shapefile location or the shapefile itself. Returns: DS_clipped: The dats...
625941de07d97122c4178bd7
def test_keep_n_latest_modules(): <NEW_LINE> <INDENT> unit_1 = UbiUnit( ModulemdUnit( name="test", stream="10", version=100, context="abcd", arch="x86_64" ), None, ) <NEW_LINE> unit_2 = UbiUnit( ModulemdUnit( name="test", stream="10", version=101, context="abcd", arch="x86_64" ), None, ) <NEW_LINE> matcher = ModularMat...
Test keeping only the latest version of modulemd
625941de8da39b475bd652bc
def has_delete_permission(self, request, obj=None): <NEW_LINE> <INDENT> return self.check_perm(request, obj, 'delete')
Check user permission on Node delete :param request: the request object :param obj: the Node object :return: bool
625941de8a349b6b435e84b8
def alexnet(num_classes): <NEW_LINE> <INDENT> net = nn.HybridSequential() <NEW_LINE> with net.name_scope(): <NEW_LINE> <INDENT> net.add( nn.Conv2D(channels=96, kernel_size=11, strides=4, activation='relu'), nn.MaxPool2D(pool_size=3, strides=2), nn.Conv2D(channels=256, kernel_size=5, padding=2, activation='relu'), nn.Ma...
net 224*224images :param num_classes: :return:
625941de004d5f362079a677
def describe(self, metric): <NEW_LINE> <INDENT> return metric.name
Describe the metric. :param metric: Metric :return: Metric description
625941deac7a0e7691ed440c
def update_derived_signal(self, signal: DerivedSignal) -> DerivedSignal: <NEW_LINE> <INDENT> response = self.client.update_derived_signal( UpdateDerivedSignalRequest(signal=signal.to_proto()) ) <NEW_LINE> return DerivedSignal.from_proto(response)
Update a derived signal. Args: signal: The derived signal to update.
625941de090684286d50f02f
def receive_msg(self, first_frame=None, timeout=None): <NEW_LINE> <INDENT> self.status = 'Receiving' <NEW_LINE> frames = [first_frame] if first_frame else [] <NEW_LINE> while len(frames) == 0 or self._deform_frame(frames[-1])[0] not in [self.frame_types['END'], self.frame_types['RSM']]: <NEW_LINE> <INDENT> for n_try in...
Запрос сообщения из канала. В отличие от check_received мы точно знаем, что сообщение должно придти. // Раньше так было После считывания, сообщение оказывается в поле self.message :param first_frame: Первый кадр сообщения. Мог быть считан в других функциях :return: Полученное сообщение
625941de5510c4643540f722
def get_frame_counter(self): <NEW_LINE> <INDENT> return _moduleconnectorwrapper.RawNormalizedData_get_frame_counter(self)
get_frame_counter(RawNormalizedData self) -> uint32_t
625941de5fdd1c0f98dc057a
def deleteNode(self, node, server=None): <NEW_LINE> <INDENT> if server is None: <NEW_LINE> <INDENT> server = self._server <NEW_LINE> <DEDENT> iq = Iq( typ='set', queryNS=None, attrs={}, frm=self._client, to=server, ) <NEW_LINE> pubsub_node = Node(tag='pubsub', attrs={'xmlns':NS_PUBSUB_OWNER}) <NEW_LINE> pubsub_node.add...
Deletes the selected node. @type node: string @param node: id of the node to delete @type server: string @param server: PubSub server @rtype: (string , list[string]) @return: A tuple with the type of answer ('ok','error') and information about the answer. In case of 'error', a list with the errors. In case ...
625941de38b623060ff0b133
def replace_keyed_meta(self, axis: int, replaced_meta_name: str, values_dict: Dict(str, str), key_meta_name: str = None) -> Adat: <NEW_LINE> <INDENT> key_meta_name = key_meta_name or replaced_meta_name <NEW_LINE> values = [] <NEW_LINE> metadata = get_pd_axis(self, axis) <NEW_LINE> key_meta = metadata.get_level_values(k...
Updates metadata in an Adat given a dictionary of values keyed to existing metadata. If a key does not exist in values_dict, the function will fill in missing data with pre-existing values and create a warning to notify the user. Parameters ---------- axis : int The metadata/multiindex to operate on: 0 - row ...
625941de31939e2706e4d1ab
def get_led_rate(self): <NEW_LINE> <INDENT> return "OK " + str(self.__rate) + "\n"
Получить частоту мерцания светодиода (0 аргументов)
625941de3c8af77a43ae3ae9
def register_undo_command(self, temporary, command): <NEW_LINE> <INDENT> commands_fp = os.path.join(self._get_cp_dir(temporary), "COMMANDS") <NEW_LINE> command_file = None <NEW_LINE> try: <NEW_LINE> <INDENT> if os.path.isfile(commands_fp): <NEW_LINE> <INDENT> command_file = open(commands_fp, "a") <NEW_LINE> <DEDENT> el...
Register a command to be run to undo actions taken. .. warning:: This function does not enforce order of operations in terms of file modification vs. command registration. All undo commands are run first before all normal files are reverted to their previous state. If you need to maintain strict order, y...
625941de63f4b57ef0001456
@manager.command <NEW_LINE> def train_dialog(): <NEW_LINE> <INDENT> logger.info('Command: train_dialog') <NEW_LINE> trainer.train_dialog_model()
start train NN responsible for dialog actions prediction
625941dea219f33f34628cab
def yprint(data, stream=sys.stdout, compact=False): <NEW_LINE> <INDENT> if isinstance(data, (int, float)): <NEW_LINE> <INDENT> print(data, file=stream) <NEW_LINE> <DEDENT> elif isinstance(data, (str, bytes)): <NEW_LINE> <INDENT> print(repr(data), file=stream) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y = yaml.YAML(...
Write a YAML record. :param data: The data to write. :param stream: the file to write to, defaults to stdout. :param compact: Write single lines if possible, default False.
625941de4f88993c3716c3aa
def put(self, key, data): <NEW_LINE> <INDENT> if key in self.hash_table: <NEW_LINE> <INDENT> get_node = self.hash_table[key] <NEW_LINE> if self.head == get_node: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__remove(get_node) <NEW_LINE> self.__add(get_node) <NEW_LINE> <DEDENT> get_node.da...
Add the key and data to the cache. if key already exists , the data is updated and object is made the MRU element :param key: key of the data to be added to cache :param data: corresponding data object to be added to the cache :return: None
625941deeab8aa0e5d26de9f
def get_lca_embodied(self): <NEW_LINE> <INDENT> return os.path.join(self.get_lca_emissions_results_folder(), 'Total_LCA_embodied.csv')
scenario/outputs/data/emissions/Total_LCA_embodied.csv
625941deff9c53063f47c538
def test_created_within_bounds(self): <NEW_LINE> <INDENT> lower_bound = 20 <NEW_LINE> upper_bound = 30 <NEW_LINE> allowed_range = range(lower_bound, upper_bound) <NEW_LINE> test_dummy = dummy.DummyThermometer( lower_bound = lower_bound, upper_bound = upper_bound) <NEW_LINE> for i in range(0,1000): <NEW_LINE> <INDENT> s...
Dummy thermometer is created and returns values within bounds.
625941de5166f23b2e1a549f
def make_default_acl(self, acls): <NEW_LINE> <INDENT> if not DEFAULT_ACL: <NEW_LINE> <INDENT> return acls <NEW_LINE> <DEDENT> realacl = [ self.make_role_acl('readers', 'r'), self.make_role_acl('admin', 'rwcda'), self.make_self_acl('rwcda'), ] <NEW_LINE> if acls: <NEW_LINE> <INDENT> realacl.extend(acls) <NEW_LINE> <DEDE...
Constructs a default Treadmill acl.
625941de63d6d428bbe44836
def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None, weights=None, repeat_weights=0): <NEW_LINE> <INDENT> c = cov(x, y, rowvar, bias, ddof, weights, repeat_weights) <NEW_LINE> try: <NEW_LINE> <INDENT> d = diag(c) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return c / c <NEW_LINE> <DEDENT> return c / sqrt...
Return correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, `P`, and the covariance matrix, `C`, is .. math:: P_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } } The values of `P` are between -1 and 1, inclusive. Param...
625941dec432627299f04f8e
def test_apply(self): <NEW_LINE> <INDENT> for tdata in [ [1., 2., 3., 4.], [2., 4., 6., 8.], [0, 1., 2.], ]: <NEW_LINE> <INDENT> tdata = np.array(tdata) <NEW_LINE> G = self.make_G(tdata, keyfmt='{s1}{s2}', srcs='ab') <NEW_LINE> basis = EigenBasis( data=G, keyfmt='{s1}{s2}', srcs='ab', t=2, tdata=tdata, ) <NEW_LINE> np....
EigenBasis EigenBasis.apply EigenBasis.unapply
625941de50485f2cf553d0e1
def done(self, base_offset=None, exception=None): <NEW_LINE> <INDENT> for relative_offset, future in enumerate(self._msg_futures): <NEW_LINE> <INDENT> if future.done(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if exception is not None: <NEW_LINE> <INDENT> future.set_exception(exception) <NEW_LINE> <DEDENT> elif...
Resolve all pending futures
625941de97e22403b379d2e1
def searchitem(self, item, threshold=None): <NEW_LINE> <INDENT> return self.search(self.key(item), threshold)
Search the index for items whose key exceeds the threshold similarity to the key of the given item. :return: list of pairs of (item, similarity) by decreasing similarity. >>> from ngram import NGram >>> n = NGram([(0, "SPAM"), (1, "SPAN"), (2, "EG"), ... (3, "SPANN")], key=lambda x:x[1]) >>> n.searchitem((2, "SPA"), ...
625941de71ff763f4b5499d7
def _is_comment(self, line): <NEW_LINE> <INDENT> return line.startswith(self.comment_symbol)
Check if a given line is a comment.
625941de4e696a04525c9792
def __getitem__( self, key ): <NEW_LINE> <INDENT> return self.__dict__.__getitem__( key )
: Index into the data structure. = INPUT VARIABLES - key The dictionary key of the item to get.
625941de4428ac0f6e5bab3a
def __init__(self): <NEW_LINE> <INDENT> self.Business = None <NEW_LINE> self.IpList = None
:param Business: 大禹子产品代号(bgp表示独享包;bgp-multip表示共享包) :type Business: str :param IpList: IP列表 :type IpList: list of str
625941de55399d3f055889fc
def priority_ge_filter(tasks, value, *args, **kwargs): <NEW_LINE> <INDENT> value = int(value) <NEW_LINE> return filter_tasks(tasks, taskkey="priority", op_name="ge", value=value, *args, **kwargs)
Convenience filter action using taskkey="priority", op_name="ge".
625941de76d4e153a657ee78
def get_records(self, hql, schema='default', hive_conf=None): <NEW_LINE> <INDENT> return self.get_results(hql, schema=schema, hive_conf=hive_conf)['data']
Get a set of records from a Hive query. :param hql: hql to be executed. :type hql: str or list :param schema: target schema, default to 'default'. :type schema: str :param hive_conf: hive_conf to execute alone with the hql. :type hive_conf: dict :return: result of hive execution :rtype: list >>> hh = HiveServer2Hook(...
625941de0c0af96317bb852e
def set_matrix_forms(self, matrix_forms): <NEW_LINE> <INDENT> self.matrix_forms = matrix_forms
Set matrix_forms with a dict mapping matrix names to bilinear forms
625941de460517430c3944c4
def longestCommonPrefix(self, strs): <NEW_LINE> <INDENT> if not strs: return "" <NEW_LINE> shortestStr = min(strs, key = len) <NEW_LINE> currentShortest = shortestStr <NEW_LINE> for word in strs: <NEW_LINE> <INDENT> temp = "" <NEW_LINE> for i, c in enumerate(shortestStr): <NEW_LINE> <INDENT> if c != word[i]: break <NEW...
:type strs: List[str] :rtype: str
625941de7b180e01f3dc4b3d
def get_nodenum(self, nodestatus): <NEW_LINE> <INDENT> if not isinstance(nodestatus, int): <NEW_LINE> <INDENT> raise SDBTypeError("nodestatus be an instance of int") <NEW_LINE> <DEDENT> if nodestatus not in common.NODE_STATUS.available_options() : <NEW_LINE> <INDENT> raise SDBTypeError("nodestatus invalid") <NEW_LINE> ...
Get the count of node with given status in current replica group. Parameters: Name Type Info: nodestatus int The specified status, see Info as below. Return values: the count of node Exceptions: pysequoiadb.error.SDBTypeError pysequoiadb.error.SDBBaseError Info: flags : 0 or 1. ...
625941deb7558d58953c5255
def fieldcode_precess(s): <NEW_LINE> <INDENT> if '.' in s: <NEW_LINE> <INDENT> s = s.replace('.','') <NEW_LINE> <DEDENT> if s[-1] is '_': <NEW_LINE> <INDENT> s=s[:-1] <NEW_LINE> <DEDENT> if len(s) < 4: <NEW_LINE> <INDENT> return 'null' <NEW_LINE> <DEDENT> if len(s) == 4 or '_' in s: <NEW_LINE> <INDENT> return s <NEW_LI...
对专题子栏目代码做规范化,例如缺失下划线A00258(A002_58)或有.或长度小于4或下划线在最后 :param s: :type s:str :return: :rtype: str
625941de925a0f43d254a1c0
def get_R(self): <NEW_LINE> <INDENT> r = _qr_R(self.qr) <NEW_LINE> return r
Get the R matrix from the decomposition. Returns ------- r : np.ndarray The R portion of the decomposed matrix.
625941de1f037a2d8b946543
def queryset(self, request, queryset): <NEW_LINE> <INDENT> return queryset.filter(water_name=self.value())
Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`.
625941dea05bb46b383ecb66
def cifar_loader(num_classes, batch_size): <NEW_LINE> <INDENT> train_transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) <NEW_LINE> val_transform = transforms.Compose([ transforms.ToTensor(), transforms...
Cifar Data Loader
625941de5f7d997b87174de1
def test_empty_post_data(self, client): <NEW_LINE> <INDENT> response = client.post( "/api/v1/register", data=json.dumps(empty_data), content_type='application/json;charset=utf-8') <NEW_LINE> res_data = json.loads(response.get_data(as_text=True)) <NEW_LINE> assert 'Bad Request' in res_data['status'] <NEW_LINE> assert 'M...
This method tests for a valid registration
625941de91f36d47f21ac83c
def load_vocab(vocab_file): <NEW_LINE> <INDENT> vocab = collections.OrderedDict() <NEW_LINE> index = 0 <NEW_LINE> with open(vocab_file, "r") as f: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> token = f.readline() <NEW_LINE> if not token: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> token = token.strip() <NEW_LI...
Loads a vocabulary file into a dictionary.
625941dec4546d3d9de72d7d
def custom_extend(input_list, second_list): <NEW_LINE> <INDENT> list_length = custom_len(input_list) <NEW_LINE> input_list[list_length:list_length] = second_list
Append every item in second_list to input_list. Like input_list.extend(second_list), custom_extend(input_list, second_list) should append every item in the second list to the end of the first list and return nothing. For example: >>> months = ['Jan', 'Feb', 'Mar'] >>> custom_extend(months, ['Apr', 'May']) ...
625941de4f88993c3716c3ab
def page10(self): <NEW_LINE> <INDENT> result = request1001.GET('/images/G/01/x-locale/personalization/yourstore/bluebox/bluebox-sides._V192187807_.gif') <NEW_LINE> request1002.GET('/images/G/01/ui/loadIndicators/loadIndicator-large._V192195480_.gif') <NEW_LINE> return result
GET bluebox-sides._V192187807_.gif (requests 1001-1002).
625941de462c4b4f79d1da16
def _search(parts, index, direction): <NEW_LINE> <INDENT> assert direction in (1, -1), direction <NEW_LINE> def in_bounds(index): <NEW_LINE> <INDENT> return index >= 0 and index < len(parts) <NEW_LINE> <DEDENT> if direction == 1: <NEW_LINE> <INDENT> starts = brace_starts <NEW_LINE> ends = brace_ends <NEW_LINE> <DEDENT>...
Helper for searching forward / backward. Yields (index, token, brace_depth)
625941de30dc7b7665901ca9
def has_traits(cls, ignore=("config", "parent")): <NEW_LINE> <INDENT> return bool(set(cls.class_trait_names()) - set(ignore))
True if cls has any traits apart from the usual ones all our components have at least 'config' and 'parent' as traitlets this is inherited from `traitlets.config.Configurable` so we ignore them here.
625941deaad79263cf390d8c
@pytest.fixture(scope="module") <NEW_LINE> def bar_mask_nc(random_masked_field, tempsrcdir): <NEW_LINE> <INDENT> filename = os.path.join(tempsrcdir, "bar.nc") <NEW_LINE> dataset = netCDF4.Dataset(filename, "w", format="NETCDF3_CLASSIC") <NEW_LINE> shape = random_masked_field.shape <NEW_LINE> dataset.createDimension("di...
a simple netCDF file with a random field * 2
625941dead47b63b2c50a2c5
def delete_program_record(programid: str) -> bool: <NEW_LINE> <INDENT> if programid == 'TEST': <NEW_LINE> <INDENT> print('NOT deleting special program record for TEST.\nok') <NEW_LINE> return True <NEW_LINE> <DEDENT> print(f'Deleting program record for {programid}') <NEW_LINE> if not args.dry_run: <NEW_LINE> <INDENT> t...
Deletes from dynamodb a program record for programs that no longer exist in PostgreSQL :param programid: to be deleted :return: True if the delete succeeded, False if an exception occurred.
625941de9b70327d1c4e111c
def getObservationProb(self, noisyAction, oldGhostPos, newGhostPos, jailPosition): <NEW_LINE> <INDENT> return busters.getObservationProbability(noisyAction, oldGhostPos, newGhostPos)
Return the probability P(noisyAction | oldGhostPos, newGhostPos).
625941de50812a4eaa59c665
def to_dict(self) -> Dict: <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'account_id') and self.account_id is not None: <NEW_LINE> <INDENT> _dict['account_id'] = self.account_id <NEW_LINE> <DEDENT> if hasattr(self, 'included_scope') and self.included_scope is not None: <NEW_LINE> <INDENT> _dict['included_s...
Return a json dictionary representing this model.
625941de4a966d76dd551359
def mediator_partial_width_dm(self): <NEW_LINE> <INDENT> width = np.select([self.mmed < 2*self.mdm, self.mmed >= 2*self.mdm], [0, self.gdm**2 * self.mmed / (12 * PI) * alpha(self.mdm, self.mmed) * beta(self.mdm, self.mmed)], default=np.nan) <NEW_LINE> return width
On-shell width for mediator -> DM DM.
625941de4428ac0f6e5bab3b
def _parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('file', help='Path to the input file to be checked') <NEW_LINE> parser.add_argument('--soname', help='Shared object name of the input file') <NEW_LINE> parser.add_argument('--shared-lib', action='append', default=[]...
Parse command line options.
625941de7d847024c06be605
def __init_logger(): <NEW_LINE> <INDENT> global LOGGER <NEW_LINE> logging.config.fileConfig('logging.conf') <NEW_LINE> LOGGER = logging.getLogger('models')
Used to initialize the logger, when running from diwacs.py
625941debf627c535bc13516
@app.route('/singleUser') <NEW_LINE> def singleUser(): <NEW_LINE> <INDENT> id = request.args.get('id') <NEW_LINE> users_posts = Blog.query.filter_by(user_id=id).all() <NEW_LINE> user = User.query.filter_by(id=id).first() <NEW_LINE> return render_template('singleUser.html', users_posts=users_posts, user=user)
NEW for Blogz. Shows all posts from one user.
625941dee5267d203edcdfdf
def validate_schema(self) -> None: <NEW_LINE> <INDENT> def is_string_or_yaml_tag_type(_, instance): <NEW_LINE> <INDENT> return ( Draft3Validator.TYPE_CHECKER.is_type(instance, "string") or isinstance(instance, CmdTag) or isinstance(instance, FileTag) or isinstance(instance, OutputStackTag) ) <NEW_LINE> <DEDENT> try: <N...
validate JSON schema
625941de462c4b4f79d1da17
def on_transaction_aborted(self, event): <NEW_LINE> <INDENT> pass
Called when a local transaction is discharged unsuccessfully (aborted). :param event: The underlying event object. Use this to obtain further information on the event. :type event: :class:`proton.Event`
625941de76e4537e8c3519bb
def test_2_opticalFlowPyrLK(self): <NEW_LINE> <INDENT> points = goodFeaturesToTrack(self.prev,max_count=50) <NEW_LINE> self.assertEqual( len(points) , 50 )
optic_flow::opticalFlowPyrLK........ .............................
625941de3cc13d1c6d3c76c0
def stage2(a, H_lambda, s, epsilon, max_iterations): <NEW_LINE> <INDENT> t = t_prev = float('inf') <NEW_LINE> num_iterations = 0 <NEW_LINE> H_bar_lambda = H_lambda / H_lambda[0] <NEW_LINE> while True: <NEW_LINE> <INDENT> t_prev, t_prev_prev = t, t_prev <NEW_LINE> try: <NEW_LINE> <INDENT> H_bar_lambda, t = next_step(a, ...
Perform Stage 2, the fixed shift process of Jenkins-Traub. Returns the deflated polynomial, and the number of iterations the stage took.
625941de63b5f9789fde742d
def get_value(self, series, key): <NEW_LINE> <INDENT> if not np.isscalar(key): <NEW_LINE> <INDENT> raise InvalidIndexError <NEW_LINE> <DEDENT> from pandas.core.indexing import maybe_droplevels <NEW_LINE> from pandas.core.series import Series <NEW_LINE> k = _values_from_object(key) <NEW_LINE> loc = self.get_loc(k) <NEW_...
we always want to get an index value, never a value
625941de4e4d5625662d471a
def __init__(self, system): <NEW_LINE> <INDENT> super(RAT651, self).__init__('rat-6.5.1', system, 'root-5.34.36', '6.5.1')
Initiliase the rat 6.5.1 package.
625941de5e10d32532c5f26d
def _iterate(self): <NEW_LINE> <INDENT> return lambda s, x: x
default behavior. should be overwritten.
625941def548e778e58cd8c6
def get_x(self) -> float: <NEW_LINE> <INDENT> return self._x
Get the x coordinate value of the current drawing position (x,y). Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel()). :return: the x coordinate value of the current drawing position
625941dea4f1c619b28b0379
def syslog_local_console_disable(handle): <NEW_LINE> <INDENT> from ucsmsdk.mometa.comm.CommSyslogConsole import CommSyslogConsoleConsts <NEW_LINE> dn = "sys/svc-ext/syslog/console" <NEW_LINE> mo = handle.query_dn(dn) <NEW_LINE> if not mo: <NEW_LINE> <INDENT> raise ValueError("sys log console does not exist.") <NEW_LINE...
This method disables system logs on local console. Args: handle (UcsHandle) Returns: CommSyslogConsole: Managed Object Raises: ValueError: If CommSyslogConsole is not present Example: syslog_local_console_enable(handle)
625941de004d5f362079a678
def get_texts(language): <NEW_LINE> <INDENT> if language == None: <NEW_LINE> <INDENT> texts_file = "./config/texts.json" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> texts_file = "./config/texts_%s.json"%language <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> texts_json = open(texts_file, "r") <NEW_LINE> texts = json.lo...
Reads the file all texts.
625941debe383301e01b57c7
def get(self, request, name): <NEW_LINE> <INDENT> if self.request.version == 'v6': <NEW_LINE> <INDENT> return self.get_v6(request, name) <NEW_LINE> <DEDENT> elif self.request.version == 'v7': <NEW_LINE> <INDENT> return self.get_v6(request, name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Http404
Retrieves the details for a recipe type and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :param name: The name of the recipe type :type name: string :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the ...
625941de1d351010ab855e62
def exclude(name, values): <NEW_LINE> <INDENT> return markers.exclude_marker((name, values))
Excludes a specific parametrization of a test from running :param name: can receive either a name of a parameter for this test, or a name of a fixture parameter :param values: must be a list of values to exclude for the given parameter
625941dee5267d203edcdfe0
def test_solutions_have_correct_number_of_notes(self): <NEW_LINE> <INDENT> result = create_population(20, CANTUS_FIRMUS) <NEW_LINE> expected_length = (len(CANTUS_FIRMUS) * 4) - 3 <NEW_LINE> for genome in result: <NEW_LINE> <INDENT> self.assertEqual(expected_length, len(genome.chromosome))
Ensures that all solutions have the expected number of notes.
625941de5fc7496912cc3cc5
def persistNewsArticle(self, article): <NEW_LINE> <INDENT> self.persistDict('NewsArticles', [article.__dict__ ])
This function persists NewsArticles :param article: a single NewsArticles
625941dea17c0f6771cbe396
def __rmul__(self, other): <NEW_LINE> <INDENT> return (self * other) if isinstance(other, (Array, float, int)) else NotImplemented
Element-wise multiplies this Array with a number or array. If the method does not support the operation with the supplied arguments (specific data type or shape), it should return NotImplemented. Args: other (Array, float, int): The array or number to multiply element-wise to this array. Returns: Array: ...
625941de0a50d4780f6671dc
def __init__(self, scale=1, usebits=False): <NEW_LINE> <INDENT> super(CrossEntropyMulti, self).__init__() <NEW_LINE> self.usebits = usebits <NEW_LINE> self.scale = scale <NEW_LINE> self.logscale = np.float(1. / np.log(2.0) if usebits else 1.)
Args: scale (float, optional): scale factor for the backpropagated error (default: 1) usebits (boolean, optional): Display costs in bits (default: False)
625941debd1bec0571d90975
def calcTrueAnomaly(x1, x2, v1, v2, m1, m2, flag=True): <NEW_LINE> <INDENT> if flag: <NEW_LINE> <INDENT> x1 = x1.in_units('cm') <NEW_LINE> x2 = x2.in_units('cm') <NEW_LINE> v1 = v1.in_units('cm s**-1') <NEW_LINE> v2 = v2.in_units('cm s**-1') <NEW_LINE> m1 = m1.in_units('g') <NEW_LINE> m2 = m2.in_units('g') <NEW_LINE> <...
Given pynbody arrays for positions and velocity of primary and secondary bodies and masses, calculates the true anomaly in the reduced two body system. Usage note: Intended for binary system, but pass x2 = v2 = 0 to use with any location in the disk. Parameters ---------- Assumed as pynbody SimArrays [preferred units]...
625941deb57a9660fec33bcf
def get_units(self): <NEW_LINE> <INDENT> return self.get_course().get_units()
Gets all units in the course.
625941dec432627299f04f8f
def create_app(current_env='development'): <NEW_LINE> <INDENT> app = Flask(__name__) <NEW_LINE> if current_env == 'development': <NEW_LINE> <INDENT> import logging <NEW_LINE> logging.basicConfig() <NEW_LINE> logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) <NEW_LINE> <DEDENT> app.config.from_object(ENV_MAP...
Creates the flask application instance Args: current_env (string): The current environment Returns: (Object, socketIO): Flask instance
625941de30bbd722463cc10e
def most_popular(dic, d1, d2): <NEW_LINE> <INDENT> counts = 0 <NEW_LINE> cdic = {} <NEW_LINE> for candidate in dic: <NEW_LINE> <INDENT> for tweet in dic[candidate]: <NEW_LINE> <INDENT> if d1 <= tweet[2] <= d2: <NEW_LINE> <INDENT> counts += tweet[-1] + tweet[-2] <NEW_LINE> <DEDENT> <DEDENT> cdic[candidate] = counts <NEW...
((dict of {str: list of tweet tuples}, int, int) -> str Precondition: d1 <= d2 Return the most popular candidate on Twitter between d1 and d2. In the case of a tie, return the string "Tie".
625941de6e29344779a62957
def get_pl_thk(self): <NEW_LINE> <INDENT> return self.plate_th
Return the plate thickness :return:
625941ded6c5a10208144394
def calc_input_param_lin_reg(beta, sigma, Sigma_x=None): <NEW_LINE> <INDENT> beta = np.asarray(beta) <NEW_LINE> if Sigma_x is not None and ( beta.ndim == 0 or beta.shape[-1] <= 1 ): <NEW_LINE> <INDENT> raise ValueError("Input dimension has to be greater than 1 " "if Sigma is provided") <NEW_LINE> <DEDENT> if beta.ndim ...
Calculate suitable sigma_x for linear regression models. Parameters ---------- beta : float or ndarray The explanatory variable coefficient of size (J,D), (D,) or (), where J is the number of groups and D is the number of input dimensions. sigma : float The noise standard deviation. Sigma_x : ndarray ...
625941de07f4c71912b117cb
def calculator(counter_type): <NEW_LINE> <INDENT> def set_calculator(func): <NEW_LINE> <INDENT> _counter_type_calculators[counter_type] = func <NEW_LINE> return func <NEW_LINE> <DEDENT> return set_calculator
A decorator that assign a counter_type to its calculator.
625941de5fcc89381b1e1a08
def validateName(self, event): <NEW_LINE> <INDENT> name = validName(self.nameInput.text()) <NEW_LINE> if name in getDbList() and name != self.db.name: <NEW_LINE> <INDENT> self.nameError.show() <NEW_LINE> self.createButton.setEnabled(False) <NEW_LINE> self.createButton.setStyleSheet(APPLY_BUTTON_DISABLED) <NEW_LINE> sel...
This method validates whether name entered in the field and is it unique (but if the name didn't changed it's okay!).
625941de23849d37ff7b33d4
def ensure_virtualenv(): <NEW_LINE> <INDENT> if not hasattr(sys, 'real_prefix'): <NEW_LINE> <INDENT> raise Exception('Not inside a virtualenv') <NEW_LINE> <DEDENT> print('Running in a virtual environment')
A python2 instance will be installed to the current virtualenv, in order to run the Autobahn test client. So if there is none active, these tests should not proceed.
625941de7d43ff24873a2fe9
def get_members_dict( obj: object, pattern: OptStr = None, classinfo: ClassInfo = object, rules: OptDictOfKeyOps = None, **kwds: Any) -> dict: <NEW_LINE> <INDENT> predicate = lambda o: ( isinstance(o, classinfo) or inspect.isclass(o) and issubclass(o, classinfo)) <NEW_LINE> refs = {k: v for k, v in inspect.getmembers(o...
Get dictionary with an object's members dict attributes. Args: obj: Arbitrary object pattern: Only members which names satisfy the wildcard pattern given by 'pattern' are returned. The format of the wildcard pattern is described in the standard library module :py:mod:`fnmatch`. By defau...
625941de5f7d997b87174de2
def test_new_user_email_normalized(self): <NEW_LINE> <INDENT> email = 'test@ROTIMI.COM' <NEW_LINE> user = get_user_model().objects.create_user( email, 'test123' ) <NEW_LINE> self.assertEqual(user.email, email.lower())
Test the email for a new user is normalized
625941de97e22403b379d2e2
def test_cause_member(self): <NEW_LINE> <INDENT> contact = Contact.objects.get(pk=1) <NEW_LINE> au = User.objects.get(username='user') <NEW_LINE> with self.assertRaises(PermissionDenied): <NEW_LINE> <INDENT> self._create_cause(au, contact, au) <NEW_LINE> <DEDENT> self.assertEqual(len(self._list_causes(au)), 1) <NEW_LIN...
GIVEN a normal member user WHEN attempting to create and read a cause THEN creating should fail, while read should work out
625941dede87d2750b8600dc
def count_user_types(data): <NEW_LINE> <INDENT> customer = 0 <NEW_LINE> subscriber = 0 <NEW_LINE> for i in range (len(data)): <NEW_LINE> <INDENT> if data_list[i][-3] == 'Customer': <NEW_LINE> <INDENT> customer += 1 <NEW_LINE> <DEDENT> elif data_list[i][-3] == 'Subscriber': <NEW_LINE> <INDENT> subscriber += 1 <NEW_LINE>...
Função para contar as ocorrencias de tipos de usuários em uma lista. Argumentos: data: lista a ser lida. Retorna: Duas variáveis int com o numero da ocorrencia de cada tipo de usuario.
625941de56b00c62f0f149a2
def strip_punct(cur_string): <NEW_LINE> <INDENT> exclude = set(string.punctuation) <NEW_LINE> exclude.add(' ') <NEW_LINE> exclude.remove('_') <NEW_LINE> regex = '[' + re.escape(''.join(exclude)) + ']' <NEW_LINE> return re.sub(regex, '', cur_string)
Remove punctuation from a string
625941de3eb6a72ae02ec82c
def __iter__(self): <NEW_LINE> <INDENT> return iter(self.Missiles)
Return an iterator for the missiles.
625941de99fddb7c1c9de6d7
def execute(self, generator): <NEW_LINE> <INDENT> optimized = ROOT.RDF.Experimental.Distributed.optimized <NEW_LINE> if optimized: <NEW_LINE> <INDENT> computation_graph_callable = generator.get_callable_optimized() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> computation_graph_callable = generator.get_callable() <NEW_...
Executes an RDataFrame computation graph on a distributed backend. Args: generator (ComputationGraphGenerator): A factory object for a computation graph. Its ``get_callable`` method will return a function responsible for creating the computation graph of a given RDataFrame object and a rang...
625941dee8904600ed9f2278
def test_join_a_non_public_team(self): <NEW_LINE> <INDENT> self.team.public = False <NEW_LINE> self.team.save() <NEW_LINE> response = self.request_join_team() <NEW_LINE> self.assertEqual(response.status_code, 403)
Tests the attempt of joining a non-public team
625941dedd821e528d63b4ee