code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def visible_for_user(self, user): <NEW_LINE> <INDENT> if not user.is_authenticated: <NEW_LINE> <INDENT> return self.filter(visibility=Visibility.PUBLIC) <NEW_LINE> <DEDENT> return self.filter( Q(author=user.profile) | Q(visibility__in=[Visibility.SITE, Visibility.PUBLIC]) | ( Q(visibility=Visibility.LIMITED) & Q(limite...
Filter by visibility to given user.
625941f55fdd1c0f98dc0860
def is_user(channel_url): <NEW_LINE> <INDENT> if 'youtube.com/user/' in channel_url: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif 'youtube.com/channel/' in channel_url: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Didn't recognize url {}".format(channel_url...
Checks if url is channel or user
625941f5046cf37aa974d36b
def process_data (self, data, client=None): <NEW_LINE> <INDENT> imaging = PXEImagingApi(self.config) <NEW_LINE> imaging.set_api(self.api) <NEW_LINE> fnc, args = imaging.get_method(data) <NEW_LINE> d = self.method_exec(imaging, fnc, args) <NEW_LINE> d.addCallback(self.send_response, fnc, client) <NEW_LINE> d.addErrback(...
Called when a packet received. @param data: packet @type data: str @param client: client (host, port) tuple @type client: tuple
625941f50fa83653e46575e1
@auth_bp.route('/forgotpassword', methods=['GET', 'POST']) <NEW_LINE> def forgotpassword(): <NEW_LINE> <INDENT> pass_reset_form = ResetForm() <NEW_LINE> if request.method == 'POST' and pass_reset_form.validate_on_submit(): <NEW_LINE> <INDENT> user = validate_email(pass_reset_form.email.data) <NEW_LINE> if user: <NEW_LI...
User reset password. GET: Serve password reset page where user submits their email. POST: If form is valid and email checks, send user a password reset url.
625941f560cbc95b062c6b6e
def get_state(self): <NEW_LINE> <INDENT> if hasattr(self, "state"): <NEW_LINE> <INDENT> return self.state <NEW_LINE> <DEDENT> return None
Get the state for the current flow. Returns: str: If you started a flow it will return the state, otherwise it will return None.
625941f5bf627c535bc137fa
def read_dictionaries(self, filename, path): <NEW_LINE> <INDENT> full_name = os.path.join(path, filename) <NEW_LINE> try: <NEW_LINE> <INDENT> for fname in self.read_one_file(full_name): <NEW_LINE> <INDENT> self.read_dictionaries(fname, path) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> raise IOError...
read values from dictionary files
625941f56fece00bbac2dd70
def ParseMessage(descriptor, byte_str): <NEW_LINE> <INDENT> result_class = MakeClass(descriptor) <NEW_LINE> new_msg = result_class() <NEW_LINE> new_msg.ParseFromString(byte_str) <NEW_LINE> return new_msg
Generate a new Message instance from this Descriptor and a byte string. DEPRECATED: ParseMessage is deprecated because it is using MakeClass(). Please use MessageFactory.GetPrototype() instead. Args: descriptor: Protobuf Descriptor object byte_str: Serialized protocol buffer byte string Returns: Newly created ...
625941f5ec188e330fd5adbb
def _start_tournament(tournament): <NEW_LINE> <INDENT> logger.info('Let the tournament begin!') <NEW_LINE> tournament.start()
Quick helper to pass in as thread callback
625941f54c3428357757c94e
def fetch_etopo1(version, *, load=True, **kwargs): <NEW_LINE> <INDENT> version = version.lower() <NEW_LINE> available = { "ice": "ETOPO1_Ice_g_gmt4.grd.gz", "bedrock": "ETOPO1_Bed_g_gmt4.grd.gz", } <NEW_LINE> if version not in available: <NEW_LINE> <INDENT> raise ValueError("Invalid ETOPO1 version '{}'.".format(version...
Fetch the ETOPO1 global relief model. ETOPO1 is a 1 arc-minute global relief model of Earth's surface that integrates land topography and ocean bathymetry [AmanteEakins2009]_. It's available in two versions: "Ice Surface" (top of Antarctic and Greenland ice sheets) and "Bedrock" (base of the ice sheets). Each grid is ...
625941f5b57a9660fec33eb7
def TossCoins(): <NEW_LINE> <INDENT> coin1 = random.choice(TOSS_TYPES) <NEW_LINE> coin2 = random.choice(TOSS_TYPES) <NEW_LINE> return CheckIfSame(coin1, coin2)
Uses random to emulate the toss of the coins.
625941f59c8ee82313fbbda2
def diffFilter(self): <NEW_LINE> <INDENT> yshape = self.yshape <NEW_LINE> axis = self.axis <NEW_LINE> ndim = len(yshape) <NEW_LINE> axis,Lambda = self.sort_axis(axis,ndim,yshape) <NEW_LINE> for c,i in enumerate(axis): <NEW_LINE> <INDENT> siz0 = np.ones((1,ndim)).astype(int)[0] <NEW_LINE> siz0[i] = yshape[i] <NEW_LINE> ...
DCT-II filter for DT D
625941f5fb3f5b602dac3cc5
def _add_constant_input(self, node_entry, idx): <NEW_LINE> <INDENT> node = node_entry["relay_node"] <NEW_LINE> param_name = node_entry["name"] <NEW_LINE> self._params[param_name] = node.data <NEW_LINE> self._add_params(node_entry, idx)
Create named input for constant and add it to container inputs. If input is a parameter then add to param
625941f521a7993f00bc8326
def getdirections(self, route): <NEW_LINE> <INDENT> resp = self.__callrest("getdirections", rt=route) <NEW_LINE> return [d["dir"] for d in resp["directions"]]
List the directions for a route. In Pittsburgh, this is always ["OUTBOUND","INBOUND"]
625941f5a79ad161976cc770
def encoder(dtype): <NEW_LINE> <INDENT> def encoder_wrapper(inner): <NEW_LINE> <INDENT> name = inner.__name__ <NEW_LINE> parts = name.split('_') <NEW_LINE> typecode = parts[1] <NEW_LINE> version = parts[2] <NEW_LINE> @wraps(inner) <NEW_LINE> def fun(v): <NEW_LINE> <INDENT> data = inner(v) <NEW_LINE> typecode_b = bytes(...
Wrapper for encoder functions.
625941f544b2445a339326bc
def SetCommands(self, functions): <NEW_LINE> <INDENT> self.functions_dict = {} <NEW_LINE> functions_dict = {'args': {}, 'forbidden_args': {}, 'independent_args': [], 'dependent_args': []} <NEW_LINE> for function in functions: <NEW_LINE> <INDENT> self.functions_dict[function] = deepcopy(functions_dict)
Sets self.functions_dict according to functions list Inputs: functions: list of strings of functions Sets the self.functions_dict ex: {'list': {'args': {}, 'forbidden_args':{}, 'independent_args': [], 'dependent_args': []}, {'remove': {'args': {}, 'forbidden_args':{}, 'independent_args': [...
625941f5c4546d3d9de73065
def _infer_types_for_row(self, row): <NEW_LINE> <INDENT> inferred_types = [] <NEW_LINE> for item in row: <NEW_LINE> <INDENT> if item is None: <NEW_LINE> <INDENT> inferred_types.append(int) <NEW_LINE> <DEDENT> elif not isinstance(item, list): <NEW_LINE> <INDENT> inferred_types.append(type(item)) <NEW_LINE> <DEDENT> else...
Returns a list of data types for the data in the specified row :param row: List or Row of data :return: List of data types
625941f58a349b6b435e879d
def __init__(self, metadata, sources, cachepath, basepath, debug=False): <NEW_LINE> <INDENT> Debuggable.__init__(self) <NEW_LINE> list.__init__(self, sources) <NEW_LINE> self.debug_flag = self.debug_flag or debug <NEW_LINE> self.metadata = metadata <NEW_LINE> self.basepath = basepath <NEW_LINE> self.cachepath = cachepa...
:param metadata: The client metadata for this collection :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata :param sources: A list of all sources known to the server that will be used to generate the list of sources that apply to this client :type sources: list of ...
625941f57b180e01f3dc4e1a
def user_public_profile(self, user_id): <NEW_LINE> <INDENT> return self._get(url='/users/{user_id}'.format(user_id=user_id))
Get public profile information about a Spotify user. https://developer.spotify.com/documentation/web-api/reference/users-profile/get-users-profile/ Args: user_id: The user’s `Spotify user ID <https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids>`__.
625941f5236d856c2ad44e0e
def testStrLenCommand(env): <NEW_LINE> <INDENT> r = env <NEW_LINE> r.assertOk(r.execute_command('JSON.SET', 'doc1', '$', '{"a":"foo", "nested1": {"a": "hello"}, "nested2": {"a": 31}}')) <NEW_LINE> res1 = r.execute_command('JSON.STRLEN', 'doc1', '$..a') <NEW_LINE> r.assertEqual(res1, [3, 5, None]) <NEW_LINE> res2 = r.ex...
Test REJSON.STRLEN command
625941f57cff6e4e81117fb0
def test_subset_samples(self): <NEW_LINE> <INDENT> obs = self.cmd(table_str=self.biom_str1, axis='samples', ids=['f4', 'f2']) <NEW_LINE> self.assertEqual(obs.keys(), ['subset_generator']) <NEW_LINE> obs = parse_biom_table(list(obs['subset_generator'])) <NEW_LINE> self.assertEqual(len(obs.SampleIds), 2) <NEW_LINE> self....
Correctly subsets samples in a table.
625941f5091ae3566866757e
def rel_at (self, from_rowcol, rel_rowcol): <NEW_LINE> <INDENT> row, column = from_rowcol <NEW_LINE> rr, rc = rel_rowcol <NEW_LINE> return self.at((row + rr, column + rc))
retrieves object at relative location, if exists;
625941f57b25080760e39a7f
def call_git(self, args, files=None, expect_stderr=False, expect_fail=False): <NEW_LINE> <INDENT> out, _ = self._call_git(args, files, expect_stderr=expect_stderr, expect_fail=expect_fail) <NEW_LINE> return out
Call git and return standard output. Parameters ---------- args : list of str Arguments to pass to `git`. files : list of str, optional File arguments to pass to `git`. The advantage of passing these here rather than as part of `args` is that the call will be split into multiple calls to avoid exceeding the ma...
625941f5004d5f362079a959
def _create_ovn_fair_meter(self, ovn_txn): <NEW_LINE> <INDENT> meter = self.ovn_nb.db_find_rows( "Meter", ("name", "=", self.meter_name)).execute(check_error=True) <NEW_LINE> if meter: <NEW_LINE> <INDENT> meter = meter[0] <NEW_LINE> try: <NEW_LINE> <INDENT> meter_band = self.ovn_nb.lookup("Meter_Band", meter.bands[0].u...
Create row in Meter table with fair attribute set to True. Create a row in OVN's NB Meter table based on well-known name. This method uses the network_log configuration to specify the attributes of the meter. Current implementation needs only one 'fair' meter row which is then referred by multiple ACL rows. :param ov...
625941f576d4e153a657f15d
def rm_domain(wkf): <NEW_LINE> <INDENT> echo('Removing domain.') <NEW_LINE> domain_name = prompt('Domain name: ') <NEW_LINE> return wkf.rm_domain(domain_name)
remove a domain and all of its keys from the protected
625941f5d10714528d600316
def all_identical(li): <NEW_LINE> <INDENT> return li[1:] == li[:-1]
Given a list `li`, check if all its elements are identical
625941f507d97122c4178ec5
def shutdown(self): <NEW_LINE> <INDENT> super(AirCatBridge, self).shutdown() <NEW_LINE> if self._phicomm is not None: <NEW_LINE> <INDENT> self._phicomm.close() <NEW_LINE> self._phicomm = None
Shutdown.
625941f571ff763f4b549cc2
def solution(n, costs): <NEW_LINE> <INDENT> answer = 0 <NEW_LINE> costs = sorted(costs, key=lambda x:x[2]) <NEW_LINE> costs = list(map(lambda x: [x[1], x[0], x[2]] if x[1] < x[0] else x, costs)) <NEW_LINE> cycle_table = dict(map(lambda x:[x, x], range(n))) <NEW_LINE> for connect in costs: <NEW_LINE> <INDENT> if cycle_t...
크루스칼 알고리즘 적용
625941f5656771135c3ebea1
def _get_function_params(func): <NEW_LINE> <INDENT> fspec = getargspec(func) <NEW_LINE> func_params = [] <NEW_LINE> nd = len(fspec.args) if not fspec.defaults else -len(fspec.defaults) <NEW_LINE> for param in fspec.args[1:nd]: <NEW_LINE> <INDENT> func_params.append({'name': param, 'required': True}) <NEW_LINE> <DEDENT>...
Retrieves the list of parameters declared in function. Each parameter is represented as dict with keys: * name (str): the name of the parameter * required (bool): whether the parameter is required or not * default (obj): the parameter's default value
625941f58e7ae83300e4b5fa
def pdf(x, mean=0, std_dev=1): <NEW_LINE> <INDENT> PI = 3.141592653589793 <NEW_LINE> E = 2.718281828459045 <NEW_LINE> term1 = 1.0 / ((2 * PI)**0.5) <NEW_LINE> term2 = E**(-1.0 * (x - mean)**2.0 / 2.0 * (std_dev**2.0)) <NEW_LINE> return term1 * term2
Calculates the normal distribution's probability density function. :param x: An integer. :param mean: An integer. :param std_dev: An integer. :rtype: The normal distribution
625941f5dd821e528d63b7ce
def refresh(self, force=True): <NEW_LINE> <INDENT> if self._parameters.auto_refresh or force: <NEW_LINE> <INDENT> self._figure.canvas.draw()
Refresh the display. Parameters ---------- force : str, optional If set to False, refresh() will only have an effect if auto refresh is on. If set to True, the display will be refreshed whatever the auto refresh setting is set to. The default is True.
625941f58c0ade5d55d3efeb
def test_loadFromString_non_pem(get_X509Certificate_class): <NEW_LINE> <INDENT> x509Cert = get_X509Certificate_class() <NEW_LINE> res = x509Cert.loadFromString('THIS IS NOT PEM DATA') <NEW_LINE> assert not res['OK'] <NEW_LINE> from DIRAC.Core.Utilities.DErrno import ECERTREAD <NEW_LINE> assert res['Errno'] == ECERTREAD
" Just load a non pem formated string
625941f563f4b57ef0001731
def __init__(self, name, fields, constraints={}): <NEW_LINE> <INDENT> defined_fields = [f.define() for f in fields.values()] <NEW_LINE> self.__table = sa.Table(name, meta, *defined_fields) <NEW_LINE> for c in constraints.get('unique', ()): <NEW_LINE> <INDENT> self.__table.append_constraint(sa.UniqueConstraint(*c)) <NEW...
Setup storage with name, fields and possible constratints.
625941f566656f66f7cbc7d8
def run(self) -> bool: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> operation_type, argument = self._parse(self._program_state.current_instruction) <NEW_LINE> operation_handler = self._OPERATIONS_TO_HANDLERS[operation_type] <NEW_LINE> operation_runner = operation_handler(self._program_state, argument) <NEW_LINE>...
Run the program. :return: whether the program terminated successfully (reached the last instruction)
625941f5d6c5a1020814467b
def get_formatted_name(first_name, last_name): <NEW_LINE> <INDENT> full_name = first_name + " " + last_name <NEW_LINE> return full_name.title()
返回整洁的名称
625941f566673b3332b926bc
def delete( self, resource_group_name, network_security_group_name, security_rule_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/security...
The delete network security rule operation deletes the specified network security rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_security_group_name: The name of the network security group. :type network_security_group_name: str :param security_rule_nam...
625941f5b7558d58953c5531
def next(self, price): <NEW_LINE> <INDENT> if price > self.pre: <NEW_LINE> <INDENT> self.prelength += 1 <NEW_LINE> self.ans.append(max(self.prelength, self.findSmallerOne(price))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.prelength = 1 <NEW_LINE> self.ans.append(self.findSmallerOne(price)) <NEW_LINE> <DEDENT> ...
:type price: int :rtype: int
625941f53539df3088e2e976
def flatten(LOL): <NEW_LINE> <INDENT> return reduce(lambda x,y: x+y, LOL, [])
Will lake LOL (a List Of Lists) = [[x_1, x_2, ... , x_k], [y_1, y_2, ..., y_r], ... ] and return [x_1,x_2, ... , x_k, y_1, y_2, ... , y_r, ...]
625941f5aad79263cf391075
def test_file_upload(self): <NEW_LINE> <INDENT> pass
Test Client.file_upload().
625941f5dc8b845886cb5b62
def glotaran_value_as_markdown( self, value: Any, all_parameters: ParameterGroup | None = None, initial_parameters: ParameterGroup | None = None, ) -> MarkdownStr: <NEW_LINE> <INDENT> md = "" <NEW_LINE> if self.glotaran_is_scalar_property: <NEW_LINE> <INDENT> md = self.glotaran_format_value(value, all_parameters, initi...
Get a markdown representation of the property. Parameters ---------- value : Any The property value. all_parameters : ParameterGroup | None A parameter group containing the whole parameter set (used for expression lookup). initial_parameters : ParameterGroup | None The initial parameter. Returns ------- M...
625941f5d53ae8145f87a88d
def fit_data(self,X_train,y_train): <NEW_LINE> <INDENT> generations = self._generations <NEW_LINE> offsprings = self._offsprings <NEW_LINE> Population = self.initPopulation() <NEW_LINE> bestGeno = Population[0] <NEW_LINE> for iteration in range(generations): <NEW_LINE> <INDENT> parentGeno = deepcopy(bestGeno) <NEW_LINE...
Parameters ---------- X_train : array array of input train data y_train : array array of output train data
625941f526238365f5f0f4a1
def delete_command(self, line): <NEW_LINE> <INDENT> param, line = line.partition(' ')[0::2] <NEW_LINE> if param == 'thread': <NEW_LINE> <INDENT> if len(line) == 0: <NEW_LINE> <INDENT> line = self.current_thread.thread_name <NEW_LINE> <DEDENT> if input('Are you sure you want to delete "{0}" thread? (Y/n): '.format(line)...
Delete command. syntax: delete thread|memory param name: the thread name or key name
625941f5aad79263cf391076
def __init__(self, odim, attention_dim=256, attention_heads=4, linear_units=2048, num_blocks=6, dropout_rate=0.1, death_rate=0.0, positional_dropout_rate=0.1, self_attention_dropout_rate=0.0, src_attention_dropout_rate=0.0, input_layer="embed", use_output_layer=True, pos_enc_class=PositionalEncoding, normalize_before=T...
Construct an Decoder object.
625941f55510c4643540f9ff
def rank(self, method="average", ascending=True) -> "Series": <NEW_LINE> <INDENT> return self._rank(method, ascending).spark.analyzed
Compute numerical data ranks (1 through n) along axis. Equal values are assigned a rank that is the average of the ranks of those values. .. note:: the current implementation of rank uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single mach...
625941f59f2886367277aeb3
def load_side_by_side_dll(dllpath, manifestpath, logger=None): <NEW_LINE> <INDENT> if not logger: <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> <DEDENT> ensure_file_exists(dllpath) <NEW_LINE> ensure_file_exists(manifestpath) <NEW_LINE> logger.debug('Loading library "{}"'.format(dllpath)) <NEW_LINE...
Loads COM DLL as inproc server, using side-by-side manifest, returns a generated comtypes module for the DLL or raises Runtime error if fails to activate DLL context properly
625941f5f8510a7c17cf9d2c
def serialize(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, Point): <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("cannot serialize %r of type %r" % (obj, type(obj)))
Converts the a user-type object into a SQL datum.
625941f5d164cc617578337a
def delete(self, node: '_Node') -> None: <NEW_LINE> <INDENT> assert self.min is not None <NEW_LINE> self.decrease_key(node, self.min.key - 1) <NEW_LINE> self.delete_min()
Delete of the given node Amortized time complexity: O(log n) :return: heap node
625941f5be8e80087fb21262
def create_lead_image(size=(800, 450), color="blue"): <NEW_LINE> <INDENT> im = Image.new("RGB", size, color=color) <NEW_LINE> draw = ImageDraw.Draw(im) <NEW_LINE> color = ImageColor.getrgb(color) <NEW_LINE> for i in range(9): <NEW_LINE> <INDENT> factor = choice(range(8, 18, 1)) / 10.0 <NEW_LINE> stroke_color = ( int(mi...
Creates an memory object containing an image. Expects a size tuple and PIL color. :param size: tuple of ints (width, height) default (800, 450) :param color: String or PIL color (r,g,b) tuple. :return: NamedBlobImage
625941f530c21e258bdfaad0
def simulate(client): <NEW_LINE> <INDENT> print("[i] Started Automatic Simulation...") <NEW_LINE> while True: <NEW_LINE> <INDENT> sleep(randint(1, 3)) <NEW_LINE> (car_enter if randint(0, 100) < 70 else car_leave)(client)
Every [1-5s] have a car [enter or leave].
625941f53617ad0b5ed68521
@pytest.mark.remote_data <NEW_LINE> def test_against_pyephem(): <NEW_LINE> <INDENT> obstime = Time('2011-09-18 08:50:00') <NEW_LINE> location = EarthLocation(lon=Angle('-109d24m53.1s'), lat=Angle('33d41m46.0s'), height=30000. * u.m) <NEW_LINE> altaz_frame = AltAz(obstime=obstime, location=location, temperature=15 * u.d...
Check that Astropy gives consistent results with one PyEphem example. PyEphem: http://rhodesmill.org/pyephem/ See example input and output here: https://gist.github.com/zonca/1672906 https://github.com/phn/pytpm/issues/2#issuecomment-3698679
625941f54428ac0f6e5bae23
def test_add_coordinates_empty_structure(self): <NEW_LINE> <INDENT> ff = IMP.atom.CHARMMParameters(IMP.atom.get_data_path("top.lib"), IMP.atom.get_data_path("par.lib")) <NEW_LINE> topology = IMP.atom.CHARMMTopology(ff) <NEW_LINE> topology.add_sequence('ACY') <NEW_LINE> m = IMP.kernel.Model() <NEW_LINE> topology.apply_d...
Test adding coordinates to a completely empty structure
625941f5adb09d7d5db6cdb7
def split(self): <NEW_LINE> <INDENT> lst1 = self.data[0: len(self)/2] <NEW_LINE> lst2 = self.data[len(self)/2: len(self)] <NEW_LINE> return make_vector(lst1, self.zero), make_vector(lst2, self.zero)
Split the vector into two halves - left and right Return two vectors separately
625941f557b8e32f52483aca
def testBasinSaddleFinderDiamondWithStub(self): <NEW_LINE> <INDENT> summit1 = Summit(1, 1, 10000) <NEW_LINE> summit2 = Summit(2, 2, 20000) <NEW_LINE> saddle1000 = Saddle(1000, 1000, 1000) <NEW_LINE> saddle100 = Saddle(100, 100, 100) <NEW_LINE> saddle1 = Saddle(1, 1, 1) <NEW_LINE> linkerSS1a = Linker(summit1, saddle100)...
Ensure lowest 2 Saddles and linkers in a diamond configuration are disqualified /--(H1)------Saddle 1000 --(H2)-----\ /----(SS1a - x)-\ Summit1- Summit2 Saddle 100 (x) \--(L1 - x)-Saddle 1 (x) -(L2 - x)--/ \----(SS1b -x)-/
625941f57047854f462a1a2d
def cli_get_networks(self, parsed_args): <NEW_LINE> <INDENT> context = {} <NEW_LINE> args = jsonutils.dumps(parsed_args) <NEW_LINE> msg = self.app.clnt.make_msg('cli_get_networks', context, msg=args) <NEW_LINE> try: <NEW_LINE> <INDENT> resp = self.app.clnt.call(msg) <NEW_LINE> return resp <NEW_LINE> <DEDENT> except (rp...
Get all networks for a tenant from the Fabric Enabler.
625941f5be7bc26dc91cdc1f
def run(self, args, usr, console=None): <NEW_LINE> <INDENT> raise NotImplementedError("run method not implemented by command.")
:type args: list This function is called when the Command has been recognized by the Console user prompt. The args argument is the list of arguments given to the Command according to the pattern defined in the initialization. If the console allows it, the console object itself may be passed through the argument 'consol...
625941f5a219f33f34628f8b
def RandomWord(length): <NEW_LINE> <INDENT> return ''.join(random.choice(string.lowercase) for i in range(length))
Generate a random string of lowercase letters.
625941f53cc13d1c6d3c79a2
def superPow(self, a, b): <NEW_LINE> <INDENT> res = 1 <NEW_LINE> mod = 1337 <NEW_LINE> if a%mod == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if a > mod: <NEW_LINE> <INDENT> a = a%mod <NEW_LINE> <DEDENT> def work(b,rlen): <NEW_LINE> <INDENT> pos = 0 <NEW_LINE> for i in range(len(b)): <NEW_LINE> <INDENT> pos = ...
:type a: int :type b: List[int] :rtype: int
625941f5ac7a0e7691ed46eb
def loadFile(self, filename=None, inFormat=None, storePath=True): <NEW_LINE> <INDENT> filename = filename if filename else self._getFilename() <NEW_LINE> if not filename: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if storePath: <NEW_LINE> <INDENT> self._settings.setValue("dataPath", os.path.dirname(filename)) <NEW_...
Use Open Babel to load a molecule from a file.
625941f538b623060ff0b418
def cdw_feature_distance(self, old_model, old_classifier, new_model): <NEW_LINE> <INDENT> old_model=old_model.to(self.device) <NEW_LINE> old_classifier=old_classifier.to(self.device) <NEW_LINE> for data in self.train_loader: <NEW_LINE> <INDENT> inputs, _ = data <NEW_LINE> inputs=inputs.to(self.device) <NEW_LINE> with t...
cosine distance weight (cdw): calculate feature distance of the features of a batch of data by cosine distance.
625941f582261d6c526abad4
def testCommitCount1(t, env): <NEW_LINE> <INDENT> _commit(t, env.c1, 1, 1)
COMMIT FLAGS: commit all DEPEND: MKFILE CODE: CMT1e
625941f5187af65679ca574c
def det_lognl(self, det): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._det_lognls[det] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> kmin = self._kmin[det] <NEW_LINE> kmax = self._kmax[det] <NEW_LINE> d = self._whitened_data[det] <NEW_LINE> lognorm = self.det_lognorm(det) <NEW_LINE> lognl = logn...
Returns the log likelihood of the noise in the given detector: .. math:: \log p(d_i|n_i) = \log \alpha_i - \frac{1}{2} \left<d_i | d_i\right>. Parameters ---------- det : str The name of the detector. Returns ------- float : The log likelihood of the noise in the requested detector.
625941f5a934411ee3751cc1
def test_saveas(): <NEW_LINE> <INDENT> file_text = "Material,TestMaterial, !- Name" <NEW_LINE> idf = IDF(StringIO(file_text)) <NEW_LINE> idf.idfname = 'test.idf' <NEW_LINE> try: <NEW_LINE> <INDENT> idf.saveas() <NEW_LINE> assert False <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> f...
Test the IDF.saveas() function.
625941f5009cb60464c639d8
def test_article_view_with_two_articles(self): <NEW_LINE> <INDENT> article = create_article() <NEW_LINE> article2 = create_article(title = "Say Cheese World", author = "Max Mustermann", author_country = "Switzerland", published_on = demo_article_published_on, introduction = "That's all, folks", text = demo_article_text...
If there are two articles they should be shown and the error message should not
625941f52ae34c7f2600d75c
def error(message): <NEW_LINE> <INDENT> log.error(message) <NEW_LINE> sys.exit(1)
Give error message and exit
625941f55166f23b2e1a5785
def __init__(self, mdp, discount=0.9, iterations=100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> states = mdp.getStates() <NEW_LINE> vector_utilidad_iter = {} <NEW_...
Your value iteration agent should take an mdp on construction, run the indicated number of iterations and then act according to the resulting policy. Some useful mdp methods you will use: mdp.getStates() mdp.getPossibleActions(state) mdp.getTransitionStatesAndProbs(state, action) mdp.getReward(state, a...
625941f531939e2706e4d48c
def realistic_physics_step_func(cur_building, time_inc, abbr_step_option=False): <NEW_LINE> <INDENT> new_time_inc = time_inc <NEW_LINE> if abbr_step_option: <NEW_LINE> <INDENT> for e in cur_building.elevators: <NEW_LINE> <INDENT> boarding_time_remaining = e.avg_boarding_time - e.time_since_beg_of_action <NEW_LINE> if e...
Step function which uses realistic physics calculations/movements abbr_step_option -- If abbr_step_option is set to True, the elevators will only continue to the point where an elevator is done loading/unloading. This is a custom option used by some RL step functions.
625941f591f36d47f21acb25
def create_bakeSet(): <NEW_LINE> <INDENT> bakeSet = 'bake_SET' <NEW_LINE> tab = cmds.optionVar(q='op_currOpenTab') <NEW_LINE> name = '' <NEW_LINE> if tab == 3: <NEW_LINE> <INDENT> result = cmds.promptDialog(title='Name bakeSet', message='Enter name for bakeSet:', button=['OK', 'Cancel'], defaultButton='OK', cancelButto...
Creates a new bakeSet. If in a shot, prompts the user for a name.
625941f5bde94217f3683416
@for_events(ERROR, TRANSACTION) <NEW_LINE> def sanitize_http_response_cookies(client, event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cookie_string = event["context"]["response"]["headers"]["set-cookie"] <NEW_LINE> event["context"]["response"]["headers"]["set-cookie"] = _sanitize_string(cookie_string, ";", "=") <N...
Sanitizes the set-cookie header of the response :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
625941f555399d3f05588ce4
def main(): <NEW_LINE> <INDENT> repo_full_name = os.environ['REPO_FULL_NAME'] <NEW_LINE> required_repo_full_name = 'ansible-collections/community.docker' <NEW_LINE> if repo_full_name != required_repo_full_name: <NEW_LINE> <INDENT> sys.stderr.write('Skipping matrix check on repo "%s" which is not "%s".\n' % (repo_full_n...
Main entry point.
625941f507f4c71912b11ab1
def run(test, params, env): <NEW_LINE> <INDENT> vm_name = params.get("main_vm") <NEW_LINE> vm = env.get_vm(vm_name) <NEW_LINE> cgconfig = params.get("cgconfig", "on") <NEW_LINE> cpulist = params.get("emulatorpin_cpulist") <NEW_LINE> status_error = params.get("status_error", "no") <NEW_LINE> change_parameters = params.g...
Test emulatorpin tuning 1) Positive testing 1.1) get the current emulatorpin parameters for a running/shutoff guest 1.2) set the current emulatorpin parameters for a running/shutoff guest 2) Negative testing 2.1) get emulatorpin parameters for a running/shutoff guest 2.2) set emulatorpin parameters running...
625941f530dc7b7665901f8a
def test_initialize_with_custom_config(): <NEW_LINE> <INDENT> client = HTTPClientFactory(api_version=APIVersion.beta, timeout=(5, 5)) <NEW_LINE> assert client.api_version == APIVersion.beta <NEW_LINE> assert client.endpoint == NationalClouds.Global <NEW_LINE> assert client.timeout == (5, 5) <NEW_LINE> assert isinstance...
Test creation of HTTP Client will use custom configuration if they are passed
625941f571ff763f4b549cc3
def extract_caller_info(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> raise ZeroDivisionError <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> info = "" <NEW_LINE> frame = sys.exc_info()[2].tb_frame.f_back.f_back <NEW_LINE> f_code = frame.f_code <NEW_LINE> co_name = f_code.co_name <NEW_LINE> c...
Returns a string describing the caller of the caller of this function. It currently checks if the caller got arguments that have an attribute with the same name as the caller (so it's probably the class of a method) or returns the module name for everything else.
625941f5d486a94d0b98e772
def get_headers(headers: dict) -> dict: <NEW_LINE> <INDENT> required_headers = {} <NEW_LINE> for key, val in headers.items(): <NEW_LINE> <INDENT> if key in HEADERS_FOR_SIGN: <NEW_LINE> <INDENT> if val: <NEW_LINE> <INDENT> required_headers[key] = val <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if 'Content-Length' in required_...
Returns required headers for sign :param headers: dict :return: dict
625941f5be383301e01b5aa5
def title_when_record_requires(acknowledgement): <NEW_LINE> <INDENT> if acknowledgement.original_transaction_type in ('NWR', 'REV') and len(acknowledgement.creation_title) == 0: <NEW_LINE> <INDENT> message = 'When the Transaction Type is %s the Creation Title must be set' % acknowledgement.original_transaction_type <NE...
Ensures that the Creation Title is set if the Original Transaction Type requires it. The validation fails if: - The Original Transaction Type requires the Creation Title to be set but it is empty :param acknowledgement: the agreement to validate
625941f5097d151d1a223482
def CI(x, p=.95): <NEW_LINE> <INDENT> M = np.mean(x) <NEW_LINE> c = CIhw(x, p) <NEW_LINE> return [M-c, M+c]
:returns: list with the endpoints of the confidence interval based on the inverse t-test (`<http://en.wikipedia.org/wiki/Confidence_interval#Statistical_hypothesis_testing>`_). :arg array x: data :arg float p: p value for confidence interval
625941f5a8ecb033257d36f6
def sift_down(self, idx): <NEW_LINE> <INDENT> larger_child = self.get_larger_child(idx) <NEW_LINE> if (larger_child is None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if(self.heap[idx] < self.heap[larger_child]): <NEW_LINE> <INDENT> self.swap(idx, larger_child) <NEW_LINE> return self.sift_down(larger_child)
Recursively sift down the value at idx. Compare the value with its larger child: If the child is larger, swap them and continue sifting down with the new child.
625941f5f9cc0f698b140c21
def bump_by_label(pr_event, old_version): <NEW_LINE> <INDENT> for label in pr_event["labels"]: <NEW_LINE> <INDENT> label_name = label["name"] <NEW_LINE> try: <NEW_LINE> <INDENT> level = BumpLevel(label_name) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Calculate the new version based on the pull request event.
625941f521bff66bcd684f78
def setToZero(matrix): <NEW_LINE> <INDENT> xSet = set() <NEW_LINE> ySet = set() <NEW_LINE> for y in range(0,len(matrix)): <NEW_LINE> <INDENT> if y in ySet: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> currRow = matrix[y] <NEW_LINE> for x in range(0,len(currRow)): <NEW_LINE> <INDENT> if x in xSet: <NEW_LINE> <INDENT...
Write an algorithm such that if an element in an MxN matrix is 0, its enture row and column are set to 0
625941f54f6381625f115066
def __le__(self, other): <NEW_LINE> <INDENT> return _ldns.ldns_rr_list_compare(self, other) != 1
Compares two rr lists. :param other: The second one. :type other: :class:`ldns_rr_list` :throws TypeError: when `other` of non-:class:`ldns_rr_list` type. :return: (bool) True when `self` is less than or equal to 'other'.
625941f54f6381625f115067
def get_degrees_from_hours_and_invert(ra_in_hrs): <NEW_LINE> <INDENT> return 360 - float(ra_in_hrs) * 360 / 24
Return a degree equivalent of input RA in hours and invert. Inversion (subtraction from 360) is necessary to simulate looking at the *inside* of the celestial sphere in d3, instead of the outside (input in string or Decimal format)
625941f5379a373c97cfb173
def testColorObjSetRGB(self): <NEW_LINE> <INDENT> c = mapscript.colorObj() <NEW_LINE> c.setRGB(255, 255, 255) <NEW_LINE> assert (c.red, c.green, c.blue, c.pen) == (255, 255, 255, -4)
a color can be set using setRGB method
625941f5925a0f43d254a4a9
def plot(self, nmin=-3.5, nmax=1.5): <NEW_LINE> <INDENT> x, y = meshgrid( linspace(XMIN/ZOOM+XOFFSET, XMAX/ZOOM+XOFFSET, 200), linspace(YMIN/ZOOM, YMAX/ZOOM, 200)) <NEW_LINE> z = zeros_like(x) <NEW_LINE> for i in range(x.shape[0]): <NEW_LINE> <INDENT> for j in range(x.shape[1]): <NEW_LINE> <INDENT> z[i, j] = log10(self...
Plots the field magnitude.
625941f58da39b475bd655a8
def validate_config(self, config, required_values): <NEW_LINE> <INDENT> for req_key, req_type in required_values.items(): <NEW_LINE> <INDENT> if req_key not in config: <NEW_LINE> <INDENT> raise ValueError("Missing key %s in config file" % req_key) <NEW_LINE> <DEDENT> if (type(req_type) == dict) and (type(config[req_key...
Make sure every required option is set.
625941f5ab23a570cc2507b4
def ykps_auth(username: str, password: str): <NEW_LINE> <INDENT> url = 'https://powerschool.ykpaoschool.cn/guardian/home.html' <NEW_LINE> form_data = { 'account': username, 'ldappassword': password, 'pw': 'shooter' } <NEW_LINE> try: <NEW_LINE> <INDENT> req = requests.post(url, data=form_data, timeout=5) <NEW_LINE> soup...
Authenticates the given credentials through Powerschool. Return: (ret: int, name: str) ret: info/exit code 0: successful 1: invalid credentials 2: request error (possibly network (timeout) error) name: name of the user (if ret != 0, will be the error)
625941f5090684286d50f31d
def wavelet_transform(signal_in, sampl_freq, scales, wave_type): <NEW_LINE> <INDENT> signal_length = np.size(signal_in) <NEW_LINE> signal_fft = np.fft.fftshift(np.fft.fft(signal_in)) <NEW_LINE> f = np.arange(-sampl_freq/2, sampl_freq/2, sampl_freq/signal_length) <NEW_LINE> f.shape = (1, len(f)) <NEW_LINE> scales.shape ...
calculate the wavelet transform of signal_in Args: signal_in (array_like): signal from that the cwt should be calculated sampl_freq (float): sampling frequency of signal_in scales (array_like): values by which the mother wavelet should be scaled wave_type(function): wavelet in frequency domain in form ...
625941f55e10d32532c5f551
def validate_capacity(self, servers): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.manager.validate_capacity(servers) <NEW_LINE> <DEDENT> except packet.baseapi.Error as msg: <NEW_LINE> <INDENT> raise PacketManagerException(msg)
Validates if a deploy can be fulfilled.
625941f530bbd722463cc3f6
@upgrade <NEW_LINE> @tier3 <NEW_LINE> def test_positive_add_host(session): <NEW_LINE> <INDENT> hc_name = gen_string('alpha') <NEW_LINE> org = entities.Organization().create() <NEW_LINE> loc = entities.Location().create() <NEW_LINE> cv = entities.ContentView(organization=org).create() <NEW_LINE> lce = entities.Lifecycle...
Check if host can be added to Host Collection :id: 80824c9f-15a1-4f76-b7ac-7d9ca9f6ed9e :expectedresults: Host is added to Host Collection successfully :CaseLevel: System
625941f54d74a7450ccd47f2
def send_new_config_raw(self, new_config): <NEW_LINE> <INDENT> if type(new_config) is not list: <NEW_LINE> <INDENT> print("Command has to be a list") <NEW_LINE> return <NEW_LINE> <DEDENT> if len(new_config) is not 20: <NEW_LINE> <INDENT> print("command has to 20 items long ") <NEW_LINE> <DEDENT> self._get_current_confi...
Accepts a list of 20 values corresponding to each of the settings of the nanosyncs
625941f54c3428357757c950
def test_config_EmptySubsep_ReturnDict(self, config_file): <NEW_LINE> <INDENT> expected_status, expected_ret = True, {"APP_ATTRIBUTES": ["cluster_role:control", "zone:3", "provider:aws"]} <NEW_LINE> status, ret = hubblestack.fdg.readfile.config( config_file, ignore_pattern=".*(worker|master).*", dictsep="=", valsep=';'...
Test that given valid arguments and an empty ``subsep``, the function returns a dict with a list as value
625941f5711fe17d82542989
def __decode(self, buf): <NEW_LINE> <INDENT> if buf.count('\xff') > 1: <NEW_LINE> <INDENT> if self.base64encode: <NEW_LINE> <INDENT> return [b64decode(d[1:]) for d in buf.split('\xff')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [d[1:].replace("\xc4\x80", "\x00").decode('utf-8').encode('latin-1') for d in buf...
decode given buffer from base 64 @type buf string @param buf the buffer to dencode
625941f523e79379d52eeb87
def nullMenuIcon(): <NEW_LINE> <INDENT> global __nullMenuIcon <NEW_LINE> if __nullMenuIcon is None: <NEW_LINE> <INDENT> __nullMenuIcon = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) <NEW_LINE> __nullMenuIcon.fill(0x00000000) <NEW_LINE> <DEDENT> return __nullMenuIcon
Transparent icon
625941f5baa26c4b54cb1744
def subreddit(self, nsfw: bool = False, full_url: bool = False) -> str: <NEW_LINE> <INDENT> url = 'http://www.reddit.com' <NEW_LINE> if not nsfw: <NEW_LINE> <INDENT> if not full_url: <NEW_LINE> <INDENT> return self.random.choice(SUBREDDITS) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return url + self.random.choice(S...
Get a random subreddit from the list. :param nsfw: NSFW subreddit. :param full_url: Full URL address. :return: Subreddit or URL to subreddit. :Example: https://www.reddit.com/r/flask/
625941f544b2445a339326bd
def cache_load(url): <NEW_LINE> <INDENT> filename = '.'.join([md5(url.encode()).hexdigest(), os.path.basename(url)]) <NEW_LINE> cache_dir = os.path.join(tempfile.gettempdir(), CACHE_DIR) <NEW_LINE> if not os.path.exists(cache_dir): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(cache_dir) <NEW_LINE> <DEDENT> ...
Load the url and store the file in a temporary cache directory. Subsequent requests for this url will use the cached version until the file is older than the CACHE_AGE. Exceptions are caught and not re-raised to enable loading of nested odML files without breaking if one of the child files is unavailable. :param url:...
625941f5e8904600ed9f2564
def _clear_callback(self, values, clearing_time): <NEW_LINE> <INDENT> raise NotImplementedError( "Callback not set. Consider installing virtual mux into a virtual address map" )
Callback function for setting the state the mux has during the clearing of relays Overridden by the the virtual address map. :return:
625941f56fece00bbac2dd73
def get_service(hass, config, discovery_info=None): <NEW_LINE> <INDENT> return SmsruNotificationService(config)
Get the SMS.RU notification service.
625941f5e5267d203edce2c1
def check_json_metadata(uuid, dataset_folder, excluded_extensions=[]): <NEW_LINE> <INDENT> assert uuid, 'UUID not set' <NEW_LINE> metadata_dict = read_json_metadata(dataset_folder) <NEW_LINE> report_list = [] <NEW_LINE> if metadata_dict['uuid'] != uuid: <NEW_LINE> <INDENT> report_list.append('UUID Changed from %s to %s...
Function to check UUID, file_paths MD5 checksums from .metadata.json
625941f5004d5f362079a95a
def numersum(test_median, data_point): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return 1 / vincenty(test_median, data_point).kilometers <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return 1 / great_circle(test_median, data_poin...
Provides the denominator of the weiszfeld algorithm depending on whether you are adjusting the candidate x or y.
625941f592d797404e3047b9
def shiftingLetters(self, S, shifts): <NEW_LINE> <INDENT> S_list = [c for c in S] <NEW_LINE> for index, shift in enumerate(shifts, start=1): <NEW_LINE> <INDENT> for i in range(0, index): <NEW_LINE> <INDENT> S_list[i] = self._shift(S_list[i], shift % 26) <NEW_LINE> <DEDENT> <DEDENT> return ''.join(S_list)
:type S: str :type shifts: List[int] :rtype: str
625941f58e7ae83300e4b5fb
def write_vtk(self, datadir='data', file_name='nulls.vtk', binary=False): <NEW_LINE> <INDENT> import os as os <NEW_LINE> try: <NEW_LINE> <INDENT> import vtk as vtk <NEW_LINE> from vtk.util import numpy_support as VN <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Warning: no vtk library found.") <NEW_LINE> <DEDE...
Write the null point into a vtk file. call signature: write_vtk(datadir='data', file_name='nulls.vtk', binary=False) Arguments: *datadir*: Target data directory. *file_name*: Target file name. *binary*: Write file in binary or ASCII format.
625941f58a349b6b435e879f
def _make_trace(neuron, plane): <NEW_LINE> <INDENT> for neurite in iter_neurites(neuron): <NEW_LINE> <INDENT> segments = list(iter_segments(neurite)) <NEW_LINE> segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ]) for s in segments] <NEW_LINE> coords = dict(x=list(chain.from_iterable((p1[0], p2[0], None) for p1, p2 in segs)), y=li...
Create the trace to be plotted
625941f5236d856c2ad44e10
def __del__(self): <NEW_LINE> <INDENT> if self.tensor: <NEW_LINE> <INDENT> _LIB.release_graph_tensor(ctypes.c_void_p(self.tensor)) <NEW_LINE> <DEDENT> self.tensor = None
release the tensor object :return: None
625941f53346ee7daa2b339e