code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _set_csrf_token(self, session): <NEW_LINE> <INDENT> response = session.get(self._host_uri) <NEW_LINE> soup = bs4.BeautifulSoup(response.text, features='html.parser') <NEW_LINE> tag = soup.find(id='csrf_token') <NEW_LINE> csrf_token = None <NEW_LINE> if tag: <NEW_LINE> <INDENT> csrf_token = tag.get('value') <NEW_LIN...
Retrieve CSRF token from the server and append to HTTP headers. Args: session: Instance of requests.Session.
625941e0a934411ee3751a19
def setSynonimsOfTerm(self, term, tag): <NEW_LINE> <INDENT> synonyms = self.synonymExtractor.findSynonyms(term, tag) <NEW_LINE> for synonym in synonyms: <NEW_LINE> <INDENT> if synonym not in self.synonyms.values(): <NEW_LINE> <INDENT> self.synonyms[synonym.replace("_", " ")] = term
Set synonyms of main terms helps match with synonyms :param term: Main word :param synonyms: List of synonyms of term
625941e0596a897236089e41
def with_waffle(flagname, flagvalue=True): <NEW_LINE> <INDENT> def with_waffle_cls_or_fun(cls_or_func): <NEW_LINE> <INDENT> def give_me_waffles(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def _give_me_waffles(*args, **kwargs): <NEW_LINE> <INDENT> origvalue = None <NEW_LINE> from waffle.models import Flag <NEW_LI...
Decorator that enables a given flag You can wrap a test class with this decorator and all the tests in the class will run with the waffle flag enabled/disabled. You can wrap a single test function with this decorator and that test will run with the waffle flag enabled/disabled. Usage:: @with_waffle('some_flag',...
625941e03539df3088e2e6cf
def match_prefix(self, string): <NEW_LINE> <INDENT> for patterns in [self._re_prefix, self._re_prefix_with_trailing_input]: <NEW_LINE> <INDENT> matches = [(r, r.match(string)) for r in patterns] <NEW_LINE> matches = [(r, m) for r, m in matches if m] <NEW_LINE> if matches != []: <NEW_LINE> <INDENT> return Match(string, ...
Do a partial match of the string with the grammar. The returned :class:`Match` instance can contain multiple representations of the match. This will never return `None`. If it doesn't match at all, the "trailing input" part will capture all of the input. :param string: The input string.
625941e0283ffb24f3c55c82
def index_nearest(value, array): <NEW_LINE> <INDENT> a = (array-value)**2 <NEW_LINE> return index(a.min(), a)
expects a _n.array returns the global minimum of (value-array)^2
625941e050485f2cf553d120
def __sizeof__(self): <NEW_LINE> <INDENT> return self._size if self._size is not None else 0
Record.__sizeof__() -> Physical size in bytes of the Record in file.
625941e0287bf620b61d3de6
def all_data_gen(): <NEW_LINE> <INDENT> for record in data_reader_generator(): <NEW_LINE> <INDENT> yield record
Generator over all data sources
625941e07cff6e4e81117d0a
def random_point_on_sphere(dimensions=3): <NEW_LINE> <INDENT> if dimensions==3: <NEW_LINE> <INDENT> u0,u1 = point_inside_unit_circle() <NEW_LINE> useful = math.sqrt(1.0 - u0*u0 - u1*u1) <NEW_LINE> x = 2.0*u0*useful <NEW_LINE> y = 2.0*u1*useful <NEW_LINE> z = 1.0 - 2.0*(u0*u0 + u1*u1) <NEW_LINE> return (x,y,z) <NEW_LINE...
Return random point on sphere of unit radius in given number of dimensions.
625941e0435de62698dfdfd2
def test_list_outputs(self): <NEW_LINE> <INDENT> comp1 = om.IndepVarComp() <NEW_LINE> comp1.add_output('comp1_a', 1.0) <NEW_LINE> comp1.add_output('comp1_b', 2.0) <NEW_LINE> comp1.add_output('comp1_c', 3.0) <NEW_LINE> prob = om.Problem(model=comp1) <NEW_LINE> prob.setup() <NEW_LINE> prob.run_model() <NEW_LINE> stream =...
Test list_outputs when the root model is a Component.
625941e0a17c0f6771cbe3d4
def iter_nodes(self): <NEW_LINE> <INDENT> return xrange(len(self.nodes))
Iterates the indexes (the unique identifiers) of the Expression nodes.
625941e0d8ef3951e32438c2
def testLoadDataFrameStructureView(self): <NEW_LINE> <INDENT> struct = create_random_structure(parametrized=True).view[:10,:] <NEW_LINE> charges = [a.charge for a in struct.atoms] <NEW_LINE> self.assertTrue(not all(x == 0 for x in charges)) <NEW_LINE> df = struct.to_dataframe() <NEW_LINE> struct.load_dataframe(dict(cha...
Tests the load_dataframe method on StructureView
625941e0b830903b967e9c8c
def CalBayComm(u): <NEW_LINE> <INDENT> conn = FLEXLABInterface() <NEW_LINE> conn.open("128.3.20.130",3500,"Login","Password") <NEW_LINE> conn.cmd('SETDAQ:WattStopper.HS1--4126F--Dimmer Level-2:' + str(u) + ':Login:Password') <NEW_LINE> time.sleep(30) <NEW_LINE> retStr = conn.cmd('GetDAQ:WattStopper.HS1--4126F--Light Le...
Send the signal u to the CalBay adapter, and return a list that contains `u` and `y`, where `y` is the measured illuminance level. :param u: input signal for the light control In this example, u represents a setpoint for the dimming control on the lights in the office 4126F. The output from this function is the curr...
625941e031939e2706e4d1ea
def index(self, pattern): <NEW_LINE> <INDENT> pattern = self._check_string_param('pattern', pattern) <NEW_LINE> matches = [] <NEW_LINE> for index in range(len(self)): <NEW_LINE> <INDENT> if (self[index] == pattern): <NEW_LINE> <INDENT> matches += [index] <NEW_LINE> <DEDENT> <DEDENT> return matches
Return indices of strings that exactly match (pattern) Args: pattern (string): search text Raises: StringsParameterError
625941e08a43f66fc4b543e6
def login(self, email: str, password: str): <NEW_LINE> <INDENT> data = json.dumps({ "email": email, "v": 2, "secret": f"0 {password}", "deviceID": self.device_id, "clientType": 100, "action": "normal", "timestamp": int(timestamp() * 1000) }) <NEW_LINE> response = requests.post(f"{self.api}/g/s/auth/login", headers=self...
Login into an account. **Parameters** - **email** : Email of the account. - **password** : Password of the account. **Returns** - **Success** : 200 (int) - **Fail** : :meth:`Exceptions <amino_.lib.util.exceptions>`
625941e0d268445f265b51f3
def calculate_fitness(self, required_data): <NEW_LINE> <INDENT> if len(self.mating_pool) > 0 : <NEW_LINE> <INDENT> print('inside mating pool') <NEW_LINE> for count in range(len(self.mating_pool)): <NEW_LINE> <INDENT> flag = self.mating_pool[count].calculate_fitness(required_data) <NEW_LINE> if flag: <NEW_LINE> <INDENT>...
we calculate the fitness of each dna sample. essentially we look thru all dna samples to check to see how many characters are matching with the goal word more characters matching are given more fitness score the aim is:: in the next selection of dna, we will have higher probability of selecting the ones with the highe...
625941e0f9cc0f698b14097d
def polyfit2d_general(x, y, z, deg, w=None, function='polynomial', minx=None, maxx=None, miny=None, maxy=None): <NEW_LINE> <INDENT> x = np.asarray(x) <NEW_LINE> y = np.asarray(y) <NEW_LINE> z = np.asarray(z) <NEW_LINE> deg = np.asarray(deg) <NEW_LINE> if function == 'polynomial': <NEW_LINE> <INDENT> vander = np.polynom...
2D Polynomimal fit Args: x (`numpy.ndarray`_): y (`numpy.ndarray`_): z (`numpy.ndarray`_): value of data at each (x,y) coordinate deg (tuple): degree of polynomial fit in the form [nx,ny] w (`numpy.ndarray`_, optional): weights. Often invvar function (str, optional): minx: maxx...
625941e0b7558d58953c5292
def find_kth(A, base_a, B, base_b, k): <NEW_LINE> <INDENT> if len(A) - base_a > len(B) - base_b: <NEW_LINE> <INDENT> return find_kth(B, base_b, A, base_a, k) <NEW_LINE> <DEDENT> if base_a == len(A): <NEW_LINE> <INDENT> return float(B[base_b + k - 1]) <NEW_LINE> <DEDENT> if k == 1: <NEW_LINE> <INDENT> return float(min(A...
base_a, base_b: where to start checking (initially as 0) k: how many elements to select It is necessary and cannot be simply (len(A)+len(B))/2, because it's true the first time but not really the case in later iterations.
625941e0b5575c28eb68e388
def isPageWatched(user, trunk): <NEW_LINE> <INDENT> result = (models.Subscription.all(). filter('user =', user). filter('trunk =', trunk). filter('method !=', models.Subscription.METH_MEH)) <NEW_LINE> return result.count(1) != 0
Is the page being watched by the user?
625941e066673b3332b92416
def testMultiClass_NpMatrixData(self): <NEW_LINE> <INDENT> iris = base.load_iris() <NEW_LINE> train_x = iris.data <NEW_LINE> train_y = iris.target <NEW_LINE> classifier = debug.DebugClassifier(n_classes=3) <NEW_LINE> classifier.fit(x=train_x, y=train_y, steps=200) <NEW_LINE> scores = classifier.evaluate(x=train_x, y=tr...
Tests multi-class classification using numpy matrix data as input.
625941e021a7993f00bc807b
def Load_mayaDir ( self ): <NEW_LINE> <INDENT> xml_path = os.path.join(ENV_PATH.WORKINGSAPCE_PATH,ENV_PATH.XML_FILE_NAME) <NEW_LINE> root = ET.parse(xml_path) <NEW_LINE> MAYA_myProject={} <NEW_LINE> for project in root.iter('project') : <NEW_LINE> <INDENT> name = project.get('name') <NEW_LINE> pjID = project.find('id')...
Load only maya folder in requied directory.
625941e0fff4ab517eb2f7c3
def p_expression_func_call(p): <NEW_LINE> <INDENT> p[0] = tq_ast.FunctionCall(p[1].lower(), p[3])
expression : ID LPAREN arg_list RPAREN
625941e0099cdd3c635f0fde
def _set_mutation_rate(self, mut_rate): <NEW_LINE> <INDENT> if mut_rate < 0: <NEW_LINE> <INDENT> self._mutation_rate = 0 <NEW_LINE> <DEDENT> elif mut_rate > 1: <NEW_LINE> <INDENT> self._mutation_rate = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._mutation_rate = mut_rate
Sets the mutation rate of this method.
625941e03617ad0b5ed6827b
def smooth_savgol_filter_f(x, window_length, polyorder, deriv=0, delta=1.0, axis=-1, mode='interp', cval=0.0, flag_fig = False, id_x=0): <NEW_LINE> <INDENT> from scipy import signal <NEW_LINE> x_sm = signal.savgol_filter(x, window_length, polyorder, deriv, delta, axis, mode, cval) <NEW_LINE> if flag_fig: <NEW_LINE> <IN...
Smooth curves using savgol filter. Call scipy.signal.savgol_filter. :param x: Can be 1D or 2D ndarray :param window_length: :param polyorder: :param deriv: :param delta: :param axis: :param mode: :param cval: :param flag_fig: :param id_x: :return: Author: Huajian Liu Email: huajian.liu@adelaide.edu.au Version: v0 (2...
625941e063d6d428bbe44875
def get_prefixes(): <NEW_LINE> <INDENT> return [str(i) for i in range(10, 100)]
Those are the characters the number starts with.
625941e021bff66bcd684cd4
@app.route("/users/new") <NEW_LINE> def show_user_new(): <NEW_LINE> <INDENT> return render_template("user_new.html")
Show the new user form
625941e082261d6c526ab82a
def _update_look(self): <NEW_LINE> <INDENT> data = PLANT_SPECIES[self.name] <NEW_LINE> if self.status == YIELD: <NEW_LINE> <INDENT> self.look = 'Game completed! Final yield: %s' % self.flowers <NEW_LINE> return <NEW_LINE> <DEDENT> if self.status == DEAD: <NEW_LINE> <INDENT> self.look = 'The plant is dead... Be more car...
Builds a text, for the user to read, that explains the current plant status.
625941e0460517430c394501
def __init__(self, root, train=True, transform=None): <NEW_LINE> <INDENT> super(KOMATSUNA, self).__init__() <NEW_LINE> self.root = os.path.expanduser(root) <NEW_LINE> self.transform = transform <NEW_LINE> self.train = train <NEW_LINE> if not self._check_exists(): <NEW_LINE> <INDENT> raise RuntimeError("Dataset not foun...
Init KOMATSUNA dataset.
625941e03539df3088e2e6d0
def test_info_get(self): <NEW_LINE> <INDENT> response = self.client.open( '/info', method='GET') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8'))
Test case for info_get
625941e02ae34c7f2600d4b6
def link_archive_provider(node, user): <NEW_LINE> <INDENT> addon = node.get_or_add_addon(settings.ARCHIVE_PROVIDER, auth=Auth(user), log=False) <NEW_LINE> if hasattr(addon, 'on_add'): <NEW_LINE> <INDENT> addon.on_add() <NEW_LINE> <DEDENT> node.save()
A generic function for linking some node, user pair with the configured archive provider :param node: target node :param user: target user (currently unused, but left in for future-proofing the code for use with archive providers other than OSF Storage)
625941e04e4d5625662d4758
def get_queryset(self, *args, **kwargs): <NEW_LINE> <INDENT> queryset = super().get_queryset(*args, **kwargs) <NEW_LINE> return queryset.select_related(*self._select_related)
Override parent method to apply the select_related() based on self._select_related.
625941e0796e427e537b094d
def addIntegerField(self, value, row, column, columnspan = 1, rowspan = 1, width = 10, sticky = N+E, state = NORMAL): <NEW_LINE> <INDENT> field = IntegerField(self, value, width, state) <NEW_LINE> self.rowconfigure(row, weight = 1) <NEW_LINE> self.columnconfigure(column, weight = 1) <NEW_LINE> field.grid(row = row, col...
Creates and inserts an integer field at the row and column, and returns the integer field.
625941e07b180e01f3dc4b7c
def get_matches_by_round(match_round): <NEW_LINE> <INDENT> if match_round > 3: <NEW_LINE> <INDENT> return {'error': 'round cannot be greater than 3'} <NEW_LINE> <DEDENT> matches = db.games.find_one({"round": match_round}) <NEW_LINE> if not matches: <NEW_LINE> <INDENT> return {'error': 'Round not yet started by the refr...
Get matches and their winners
625941e0cb5e8a47e48b7e2a
def cleanup(self, connection): <NEW_LINE> <INDENT> if self.internal_pipeline: <NEW_LINE> <INDENT> self.internal_pipeline.cleanup(connection)
cleanup will *only* be called after run() if run() raises an exception. Use cleanup with any resources that may be left open by an interrupt or failed operation such as, but not limited to: - open file descriptors - mount points - error codes Use contextmanagers or signal handlers to clean up any resource...
625941e063f4b57ef0001494
def validAddRole(self): <NEW_LINE> <INDENT> name = API().getTextByResourceId(self.testcase, self.driver, self.logger, XJJSPC.resource_id_name, XJJSPC.verify_timeout) <NEW_LINE> API().assertEqual(self.testcase, self.logger, name, XJJSPC.account_name)
usage: 验证新建角色是否正确
625941e03317a56b86939fd5
def test_sum_of_three_values_naive(self): <NEW_LINE> <INDENT> self.assertTrue(lists.sum_of_three_values.sum_of_three_values_naive(self.list, self.sum)) <NEW_LINE> self.assertFalse(lists.sum_of_three_values.sum_of_three_values_naive(self.list, self.false_sum))
Test the naive implementation of sum of three values
625941e057b8e32f52483823
def handleTrade(self, t): <NEW_LINE> <INDENT> self._csvlog({'trade_price':t.price}) <NEW_LINE> if self._position: <NEW_LINE> <INDENT> if t.price <= self._position.cost_stop: <NEW_LINE> <INDENT> self._closePosition(t, "failed") <NEW_LINE> self.stats['position_fail'] += 1 <NEW_LINE> <DEDENT> elif t.price >= self._positio...
A trade came in. We won't trigger trade opens from this but it might cause us to close one.
625941e030bbd722463cc14d
def _queen(row, solve): <NEW_LINE> <INDENT> if row > n - 1: <NEW_LINE> <INDENT> solves.append(solve) <NEW_LINE> return <NEW_LINE> <DEDENT> for col in range(n): <NEW_LINE> <INDENT> idx1 = _cell_to_diag(row, col) <NEW_LINE> idx2 = _cell_to_anti_diag(row, col) <NEW_LINE> if not cols[col] and not diags[idx1] and not anti_d...
Test every col of current row. Add valid to current solve then find cols in the next row.
625941e0dc8b845886cb58bc
def generate_command(self, string): <NEW_LINE> <INDENT> cmd, rest = self._split_command(string) <NEW_LINE> if not cmd: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if cmd in self.canonical_mi_commands: <NEW_LINE> <INDENT> opts, args = self.option_parsers[cmd].parse_args(rest) <NEW_LINE> command = Command(cmd, op...
Generate a command object based upon a string. This works as follows: First, the command name is determined: - Words are gobbled up from the start of the string (a word is text separated by spaces). - The first command that matches, based upon the complete() command, is chosen. If the command is not found, return None...
625941e00383005118ecf967
@login_required <NEW_LINE> def reopenfound(request,found_id): <NEW_LINE> <INDENT> if request.method=='GET': <NEW_LINE> <INDENT> item = get_object_or_404(FoundItem, pk = found_id) <NEW_LINE> if not item.user == request.user: <NEW_LINE> <INDENT> messages.warning(request, "It seems that it isn't your item.") <NEW_LINE> re...
Allows a user to repoen their items that they had reported found before
625941e02eb69b55b151cc39
def gauss_den(x, mu, va, log = False, axis = -1): <NEW_LINE> <INDENT> if x.ndim == 1: <NEW_LINE> <INDENT> d = 1 <NEW_LINE> n = x.size <NEW_LINE> if not N.size(mu) == 1: <NEW_LINE> <INDENT> raise DenError("for 1 dimension problem, mean must have only one element") <NEW_LINE> <DEDENT> if not N.size(va) == 1: <NEW_LIN...
Compute multivariate Gaussian density at points x for mean mu and variance va along specified axis: requirements: * mean must be rank 0 (1d) or rank 1 (multi variate gaussian) * va must be rank 0 (1d), rank 1(multi variate, diag covariance) or rank 2 (multivariate, full covariance). * in 1 dimens...
625941e01f5feb6acb0c4ed0
def test_03_user_enable(self): <NEW_LINE> <INDENT> self.check_enable(argv=['--user'], dirs=self.jupyter_dirs['env_vars'])
Check that enable works correctly using --user flag.
625941e0ac7a0e7691ed444c
def filter_dataset(input_dataset, other_arguments, predicate, output_types, output_shapes, name=None): <NEW_LINE> <INDENT> _ctx = _context.context() <NEW_LINE> if not _ctx.executing_eagerly(): <NEW_LINE> <INDENT> if not isinstance(output_types, (list, tuple)): <NEW_LINE> <INDENT> raise TypeError( "Expected list for 'ou...
Creates a dataset containing elements of `input_dataset` matching `predicate`. The `predicate` function must return a scalar boolean and accept the following arguments: * One tensor for each component of an element of `input_dataset`. * One tensor for each value in `other_arguments`. Args: input_dataset: A `Te...
625941e0d99f1b3c44c6790f
def test_sync_record_for_forum_with_deleted_threads(self): <NEW_LINE> <INDENT> self.post_thread(self.user.reads_cutoff + timedelta(days=1)) <NEW_LINE> self.post_thread(self.user.reads_cutoff + timedelta(days=1)) <NEW_LINE> self.post_thread(self.user.reads_cutoff + timedelta(days=1)) <NEW_LINE> add_acl(self.user, self.f...
unread forum reverts to read after its emptied
625941e0925a0f43d254a200
def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self.axes[0], name)
pass on calls to the axis, e.g. making a plot
625941e0fbf16365ca6f6550
def get_finished_matches(self, live): <NEW_LINE> <INDENT> finished_matches = [match for match in self.get_all_matches() if match[STATUS] == FINISHED] <NEW_LINE> for i in xrange(len(finished_matches)): <NEW_LINE> <INDENT> finished_matches[i] = User.choose_information(finished_matches[i]) <NEW_LINE> <DEDENT> finished_mat...
Get only the finished matches. Receives: live - A string that contains the live matches. Returns: A list that contains the user teams' finished matches.
625941e0711fe17d825426e9
def createConstantColorData(self, c, n_faces): <NEW_LINE> <INDENT> mesh_colors = np.tile(c, 3 * n_faces) <NEW_LINE> data_mesh_colors = mesh_colors.flatten() <NEW_LINE> return data_mesh_colors
Creates a flattened array holding the rgba color of each vertex :param c: color which is assigned to each vertex :param n_faces: amount of faces :return:
625941e029b78933be1e5a2d
def _removeUnneededKeysInGroup(self, groupToProcess): <NEW_LINE> <INDENT> return {key:value for key, value in groupToProcess.items() if key in self._keysInGroup}
Return new dict with only keys in self._keysInGroup
625941e00a366e3fb873eba3
@app.task <NEW_LINE> def dbpedia_spotlight(doc, lang='en', conf=0.5, supp=0, api_url=None): <NEW_LINE> <INDENT> if api_url is None: <NEW_LINE> <INDENT> server = "http://spotlight.sztaki.hu" <NEW_LINE> ports_by_language = { 'en': 2222, 'fr': 2225, 'de': 2226, 'ru': 2227, 'pt': 2228, 'hu': 2229, 'it': 2230, 'es': 2231, '...
Run text through a DBpedia Spotlight instance. Calls the DBpedia Spotlight instance to perform entity linking and returns the names/links it has found. See http://spotlight.dbpedia.org/ for details. This task uses a Python client for DBp Spotlight: https://github.com/aolieman/pyspotlight
625941e0be7bc26dc91cd97f
@api_view(['POST']) <NEW_LINE> @permission_classes((IsAuthorizedUser, )) <NEW_LINE> @renderer_classes((JSONRenderer, )) <NEW_LINE> def send_justificatif(request, id): <NEW_LINE> <INDENT> perm = perm_models.Perm.objects.get(pk=id) <NEW_LINE> info = perm.get_justificatif_information() <NEW_LINE> justificatif_template = g...
Endpoint qui permet d'envoyer le justificatif de paiement par mail pour une perm d'id {id}.
625941e023849d37ff7b3413
def import_labview(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Import Labview to NWB.') <NEW_LINE> parser.add_argument('nwb_path', help='path to the NWB file to write') <NEW_LINE> parser.add_argument('labview_path', help='path to the Labview folder to import') <NEW_LINE> parser.add_argument('--...
Command line script to import a Labview folder to NWB format.
625941e0293b9510aa2c3618
def find_data_by_region(self, region_list, pos, affix=None): <NEW_LINE> <INDENT> if not affix and self.image_format: <NEW_LINE> <INDENT> affix = self.image_format <NEW_LINE> <DEDENT> file_loc = [] <NEW_LINE> if pos: <NEW_LINE> <INDENT> folder = os.path.join(self.root, "All_"+self.pos_label) <NEW_LINE> <DEDENT> else: <N...
Given a combination of eight years, dig out each region's data file and save the filepath to a list :param region_list: the specific region to search :param pos: pos/neg class :param affix: copy image -> jpg or copy text file -> txt :return: generated file list
625941e063b5f9789fde746c
def __init__(self, json_ttm_str): <NEW_LINE> <INDENT> self.testingtool_msg_dict = json.loads(json_ttm_str)
Parses a json string to create a message, defines a dictionary with the fields of the message as an attribute. (str) -> (TestingToolMessage) :param json_ttm_str: string-json formatted.
625941e0cad5886f8bd2735f
def _logConnectionLostMsg(self): <NEW_LINE> <INDENT> log.msg(f"({self._type} Port {self._realPortNumber} Closed)")
Log message for closing port
625941e015fb5d323cde0e9a
def get_flatness(L, slope, t, p): <NEW_LINE> <INDENT> F = "tmp_F{L}".format(L=L+1) + ''.join([random.choice(string.ascii_letters + string.digits) for n in range(4)]) <NEW_LINE> TMP_RAST[L].append(F) <NEW_LINE> grass.mapcalc("$g = 1.0 / (1.0 + pow(($x / $t), $p))", g=F, x=slope, t=t, p=p) <NEW_LINE> return F
Calculates the flatness index Flatness F1 = 1 / (1 + pow ((slope / t), p) Equation 2 (Gallant and Dowling, 2003)
625941e091f36d47f21ac87c
def clone(self, acl_id): <NEW_LINE> <INDENT> response = self._adapter.put(self._build_uri(['clone', acl_id])) <NEW_LINE> if response.status_code == 404: <NEW_LINE> <INDENT> raise exceptions.NotFound(response.body) <NEW_LINE> <DEDENT> return response.body.get('ID')
Clone an existing ACL returning the new ACL ID :param str acl_id: The ACL id :rtype: bool :raises: consulate.exceptions.Forbidden :raises: consulate.exceptions.NotFound
625941e0cdde0d52a9e533bb
def _notify(self, title, body, hosts=None, username=None, password=None, **kwargs): <NEW_LINE> <INDENT> self.username, self.password = username, password <NEW_LINE> title = title or 'SickGear' <NEW_LINE> hosts = self._choose(hosts, sickbeard.KODI_HOST) <NEW_LINE> success = True <NEW_LINE> message = [] <NEW_LINE> for ho...
Internal wrapper for the notify_snatch and notify_download functions Call either the JSON-RPC over HTTP or the legacy HTTP API methods depending on the Kodi API version. Args: title: Title of the notice to send body: Message body of the notice to send Return: A list of results in the format of host:ip:re...
625941e050485f2cf553d121
def load_pattern(self): <NEW_LINE> <INDENT> pth = join(self.folder, self.filenames["orders"]) <NEW_LINE> self.pattern = np.loadtxt(pth, dtype="int")
Read file with coordinats for each difraction order of the Echelle spectrometer
625941e021a7993f00bc807c
def __parse_submission(self, line, state): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> line = self.__get_next_line() <NEW_LINE> msg = "" <NEW_LINE> if self.__level_is_finished(line, state.level+1): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elif line.token == TOKEN_SUBM: <NEW_LINE> <INDENT> msg = _("Submissi...
@param line: The current line in GedLine format @type line: GedLine @param state: The current state @type state: CurrentState Handling of lines subordinate to the level 0 SUMN (Submission) GEDCOM tag n @<XREF:SUBN>@ SUBN {1:1] +1 SUBM @<XREF:SUBM>@ {0:1} +1 FAMF <NAME_OF_FAMILY_FILE> {0:1} +1 TEMP <...
625941e0090684286d50f071
def get_imgs_Y_fn(file_name, path): <NEW_LINE> <INDENT> return scipy.misc.imread(path + file_name, mode='YCbCr')[:,:,:1]
Input an image path and name, return an image array
625941e0de87d2750b86011c
def write_sudoku_base(self): <NEW_LINE> <INDENT> for row in xrange(9): <NEW_LINE> <INDENT> for column in xrange(9): <NEW_LINE> <INDENT> self.grid[row][column] = (row * 3 + row / 3 + column) % 9 + 1
This method fill in global grid variable the base of sudoku game, this base is a sudoku solved in order.
625941e00a50d4780f66721b
def encode(self, data, *args, **kwargs): <NEW_LINE> <INDENT> import bz2 <NEW_LINE> format = 'bz2' <NEW_LINE> if len(data[0]): <NEW_LINE> <INDENT> format += '_%s' % data[0] <NEW_LINE> <DEDENT> return format, bz2.compress(data[1])
encodes the given data to bz2 bytes. The given data **must** be bytes :param data: (sequence[str, obj]) a sequence of two elements where the first item is the encoding format of the second item object :return: (sequence[str, obj]) a sequence of two elements where the first item is the encoding format of the second it...
625941e0d18da76e23532861
def __init__(self, name, mode=None, description='', default=None): <NEW_LINE> <INDENT> if mode is None: <NEW_LINE> <INDENT> mode = self.__class__.OPTIONAL <NEW_LINE> <DEDENT> elif not isinstance(mode, int) or mode > 7 or mode < 1: <NEW_LINE> <INDENT> raise Exception('Argument mode "%s" is not valid.' % mode) <NEW_LINE>...
Constructor @param name: The argument name @type name: str @param mode: The argument mode: REQUIRED or OPTIONAL @type mode: int or None @param description: A description text @type description: str @param default: The default value (for OPTIONAL mode only) @type default: mixed
625941e0236d856c2ad44b65
def write_diag_2bit_spoke(self, bunch, theta_frac=1): <NEW_LINE> <INDENT> self.write_NOTA("****Begin diag 2bit spoke", self.data.do_notas) <NEW_LINE> for combi in bunch: <NEW_LINE> <INDENT> trols = Controls.new_knob(self.data.num_orbitals+1, combi[1], True) <NEW_LINE> theta = self.data.diag_2bits_to_theta[combi] <NEW_L...
This function writes a spoke consisting of a bunch of interlaced 2 qubit gates. This spoke is a diagonal matrix. Parameters ---------- bunch : tuple[tuple[int]] theta_frac : float theta fraction, multiply all thetas by this fraction Returns ------- None
625941e05fdd1c0f98dc05bb
def _validate_metadata(self, metadata): <NEW_LINE> <INDENT> metadata = metadata or {} <NEW_LINE> valid_prefixes = ["x-object-meta-", "x-remove-object-meta-"] <NEW_LINE> for key in metadata or {}: <NEW_LINE> <INDENT> key = key.lower() <NEW_LINE> for prefix in valid_prefixes: <NEW_LINE> <INDENT> if key.startswith(prefix)...
Validate dict of metadata headers Args: metadata: dict of metadata headers Returns: validated metadata dict Raises: ValueError
625941e015baa723493c42fe
def get_attributes(self): <NEW_LINE> <INDENT> return [{"Feature Groups":self.active_groups}]
returns a list of tuples of (attribute,value) for all learned attributes Returns ------- list of tuples of (attribute,value)
625941e0046cf37aa974d0cb
def test_django_update_fields_edge_cases(self): <NEW_LINE> <INDENT> obj = self.obj <NEW_LINE> obj.boolean = True <NEW_LINE> obj.save(update_fields=[]) <NEW_LINE> self.assertEqual( obj.history.filter(action=LogEntry.Action.UPDATE).count(), 0, msg="There is no log entries created", ) <NEW_LINE> obj.refresh_from_db() <NEW...
The test ensures that if Django's `update_fields` behavior ever changes for special values `(None, [])`, the package should too. https://docs.djangoproject.com/en/3.2/ref/models/instances/#specifying-which-fields-to-save
625941e0a934411ee3751a1b
def projection(N, n, m): <NEW_LINE> <INDENT> ket1 = basis(N, n) <NEW_LINE> ket2 = basis(N, m) <NEW_LINE> return ket1 * ket2.dag()
The projection operator that projects state |m> on state |n>. i.e., |n><m|. Returns ------- oper : qobj Requested projection operator.
625941e071ff763f4b549a18
def sample_from_vMF(mu, kappa, num_samples): <NEW_LINE> <INDENT> np.random.seed(32) <NEW_LINE> thetas = np.random.uniform(low = -np.pi, high = np.pi, size=num_samples) <NEW_LINE> v = np.transpose(np.vstack((np.cos(thetas), np.sin(thetas)))) <NEW_LINE> xi = np.random.uniform(size=num_samples) <NEW_LINE> w = 1.0/kappa * ...
Uses method from Jakob (2012) and Jung (2009) and others to sample from a vMF distribution on the 2-sphere. Parameters: mu - direction vector (3 x 1) kappa - concentration parameter (constant) N - number of samples Returns: omega - the sampled points
625941e00383005118ecf968
def __call__(self): <NEW_LINE> <INDENT> coeff = [self.D() for _ in range(self.n)] <NEW_LINE> f = self.P(coeff) <NEW_LINE> return f
Return a new sample. EXAMPLE:: sage: from sage.crypto.lwe import UniformPolynomialSampler sage: sampler = UniformPolynomialSampler(ZZ['x'], 8, -12, 12) sage: sampler() -10*x^7 + 5*x^6 - 8*x^5 + x^4 - 4*x^3 - 11*x^2 - 10
625941e050485f2cf553d122
def onSelectEpub(self, event): <NEW_LINE> <INDENT> wildcard = 'ePub File (*.epub)|*.epub' <NEW_LINE> dlg = wx.FileDialog(self, 'Choose a file', '', '', wildcard, wx.FD_OPEN) <NEW_LINE> if dlg.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> self.OnReset() <NEW_LINE> self.epubFile = os.path.join( dlg.GetDirectory(), dlg.Get...
Open FileDialog to select epub file.
625941e0287bf620b61d3de8
def asset_subclass_by_interval(series, interval, asset_class): <NEW_LINE> <INDENT> ac_dict = asset_class_dict(asset_class) <NEW_LINE> benchmark = web.DataReader(ac_dict.values(), 'yahoo', start = '01/01/2000')['Adj Close'] <NEW_LINE> ind = clean_dates(series, benchmark) <NEW_LINE> dt_dict = {'quarterly': lambda x: x.qu...
Return asset sub class weightings that explain the asset returns over interval periods of "interval." :ARGS: asset_prices: :class:`pandas.Series` of the asset for which attribution will be done asset_class_prices: :class:`pandas.DataFrame` of asset class prices interval :class:string of the frequenc...
625941e0091ae356686672df
def hook_makeOutline(VO, blines): <NEW_LINE> <INDENT> Z = len(blines) <NEW_LINE> tlines, bnodes, levels = [], [], [] <NEW_LINE> tlines_add, bnodes_add, levels_add = tlines.append, bnodes.append, levels.append <NEW_LINE> for i in xrange(Z): <NEW_LINE> <INDENT> bline = blines[i] <NEW_LINE> if not bline or bline[0] in whi...
Return (tlines, bnodes, levels) for Body lines blines. blines is either Vim buffer object (Body) or list of buffer lines.
625941e09f2886367277ac12
def launch_qqmusic_app(self, driver=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> wait(5) <NEW_LINE> self.__initialize_variable_of_qqmusic_app() <NEW_LINE> if driver: <NEW_LINE> <INDENT> self.driver = driver <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.driver = self.mobile_driver_factory_object.get_driver(g...
Launch willow application :param:None :return:None :raises:None
625941e08a349b6b435e84f9
def pack(self, data): <NEW_LINE> <INDENT> if not self.gzip_enabled or len(data) < self.gzip_threshold: <NEW_LINE> <INDENT> return data + self.zero_flag_bytes <NEW_LINE> <DEDENT> sio = StringIO() <NEW_LINE> gz = gzip.GzipFile(fileobj=sio, mode='w') <NEW_LINE> gz.write(data) <NEW_LINE> gz.close() <NEW_LINE> gzip_data = s...
Pack the (byte) data, optionally compressing it.
625941e07cff6e4e81117d0c
def check_genome_mapping(ind): <NEW_LINE> <INDENT> new_ind = individual.Individual(ind.genome, None) <NEW_LINE> attributes_0 = vars(ind) <NEW_LINE> attributes_1 = vars(new_ind) <NEW_LINE> if params['GENOME_OPERATIONS']: <NEW_LINE> <INDENT> attributes_0['tree'] = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if att...
Re-maps individual to ensure genome is correct, i.e. that it maps to the correct phenotype and individual. :param ind: An instance of the representation.individual.Individual class. :return: Nothing.
625941e04a966d76dd551399
def getEdge(graph, vertexa, vertexb): <NEW_LINE> <INDENT> if (graph['type'] == "ADJ_LIST"): <NEW_LINE> <INDENT> return alt.getEdge(graph, vertexa, vertexb)
Retorna el arco asociado a los vertices vertexa ---- vertexb Args: graph: El grafo sobre el que se ejecuta la operacion vertexa: Vertice de inicio vertexb: Vertice destino Returns: El grado el arco Raises: Exception
625941e0d6c5a102081443d4
def open_file(): <NEW_LINE> <INDENT> with open("words.txt", "r") as f: <NEW_LINE> <INDENT> words = list(map(lambda x: x.strip(), f.readlines()))[0:1100] <NEW_LINE> <DEDENT> return words
Function to open and pars txt file, which returns first 1100 words from given words library.
625941e057b8e32f52483824
def __init__(self) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._label = QtWidgets.QLabel(self) <NEW_LINE> self._cb = QtWidgets.QCheckBox(self) <NEW_LINE> spacer = QtWidgets.QSpacerItem( 1, 1, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum ) <NEW_LINE> _lay = QtWidgets.Q...
Inicialize.
625941e0f9cc0f698b14097f
def check_body_line_length(commit_lines): <NEW_LINE> <INDENT> for line in commit_lines: <NEW_LINE> <INDENT> if len(line) > MAX_LINE_LENGTH: <NEW_LINE> <INDENT> return 'Wrap body lines at {0} characters'.format(MAX_LINE_LENGTH)
Check line length. >>> check_body_line_length(["", "", 'this is short enough']) >>> check_body_line_length(["", "", 'TOO_LONG' * 10]) 'Wrap body lines at 72 characters'
625941e0004d5f362079a6b8
def _writeVTK(self, f, solution, solutionType, cycle, step): <NEW_LINE> <INDENT> f.write('# vtk DataFile Version 2.0\n') <NEW_LINE> f.write(self.title + '\n') <NEW_LINE> f.write('ASCII\n') <NEW_LINE> f.write('DATASET POLYDATA\n') <NEW_LINE> f.write('POINTS '+str(self.numberPoints)+' double\n') <NEW_LINE> y = 0.0 <NEW_L...
Writes solution to VTK file as a set of points.
625941e04527f215b584c7da
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, IpamsvcUpdateFixedAddressResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941e0097d151d1a2231de
def map(self, func, *args, **kwargs): <NEW_LINE> <INDENT> kw_color = kwargs.pop("color", None) <NEW_LINE> for (row_i, col_j, hue_k), data_ijk in self.facet_data(): <NEW_LINE> <INDENT> if not data_ijk.values.tolist(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ax = self.facet_axis(row_i, col_j) <NEW_LINE> kwargs["...
Apply a plotting function to each facet's subset of the data. Parameters ---------- func : callable A plotting function that takes data and keyword arguments. It must plot to the currently active matplotlib Axes and take a `color` keyword argument. If faceting on the `hue` dimension, it must also take ...
625941e0f7d966606f6aa390
def create_frame_coords_list(coords_path): <NEW_LINE> <INDENT> id_number = coords_path[0] <NEW_LINE> fr_coordinates = [None]*int((len(coords_path) - 1) / 3) <NEW_LINE> index = 0 <NEW_LINE> for i in range(1, len(coords_path), 3): <NEW_LINE> <INDENT> x = coords_path[i] <NEW_LINE> y = coords_path[i + 1] <NEW_LINE> frame_n...
:param coords_path: [int] :type coords_path: list :return: int, [int] :rtype: tuple
625941e066673b3332b92418
def __getstate__(self): <NEW_LINE> <INDENT> raise TypeError(name + ' cannot be pickled')
Prevent pickling without explicit conversion.
625941e03346ee7daa2b30f5
def getNMessages(self): <NEW_LINE> <INDENT> return len(self._messages)
Get the number of messages
625941e0be8e80087fb20fc5
def poly_learning_rate(optimizer, base_lr, curr_iter, max_iter, power=0.9, index_split=4, scale_lr=10.0): <NEW_LINE> <INDENT> lr = base_lr * (1 - float(curr_iter) / max_iter) ** power <NEW_LINE> for index, param_group in enumerate(optimizer.param_groups): <NEW_LINE> <INDENT> if index <= index_split: <NEW_LINE> <INDENT>...
poly learning rate policy
625941e0ad47b63b2c50a305
def assertSent(self, ctx, path_files): <NEW_LINE> <INDENT> expected = { path.name: set((file, self.files.joinpath(file).read_bytes()) for file in (set(ctx.path_files.get(path, ())) | set(path_files.get(path, ())))) for path in ctx.subpaths } <NEW_LINE> actual = { path.name: set((file.name, file.read_bytes()) for file i...
Assert that specified test files were sent The contents of the temporary directory will be compared against the expected contents.
625941e0fff4ab517eb2f7c5
def note_callback(data): <NEW_LINE> <INDENT> print("Note: {}".format(data))
Prints the retrieved note each time a note event is sent. The callback arg must be named 'data' or you can grab the data from the kwargs.
625941e04f88993c3716c3eb
def rep(x,n): <NEW_LINE> <INDENT> z = numpy.zeros(len(x)*n) <NEW_LINE> for i in range(len(x)): <NEW_LINE> <INDENT> for j in range(n): <NEW_LINE> <INDENT> z[i*n+j]=x[i] <NEW_LINE> <DEDENT> <DEDENT> return(z)
interpolate
625941e05166f23b2e1a54e0
def iter_extract(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Extract files from the archive with an iterator. You may simply iterate over a :class:`Extractor` object, which is same as calling to this method. Yields: (str, file-like): Tuples of ``(name, file-like object)``, the filename and corresponding file-like object for each file in the archive. The re...
625941e06fece00bbac2dac9
def _assert_obj_type(pub, name="pub", obj_type=DBPublication): <NEW_LINE> <INDENT> if not isinstance(pub, obj_type): <NEW_LINE> <INDENT> raise InvalidType( "`%s` have to be instance of %s, not %s!" % ( name, obj_type.__name__, pub.__class__.__name__ ) )
Make sure, that `pub` is instance of the `obj_type`. Args: pub (obj): Instance which will be checked. name (str): Name of the instance. Used in exception. Default `pub`. obj_type (class): Class of which the `pub` should be instance. Default :class:`.DBPublication`. Raises: InvalidType: Wh...
625941e0a4f1c619b28b03b8
def compute_imf_ensemble(self, s): <NEW_LINE> <INDENT> noise_std = self.ensemble_noise_gain*s.std() <NEW_LINE> imf_mean = None <NEW_LINE> imf_std = None <NEW_LINE> for k in range(self.ensemble_num_samples): <NEW_LINE> <INDENT> noise = np.random.randn(len(s))*noise_std <NEW_LINE> imf = self.compute_imf(s+noise) <NEW_LIN...
Computes the ensemble-empirical model decomposition (EEMD, Huang et. al 2008).
625941e0cc0a2c11143dd219
def iso639_3_to_iso639_1(specific_code): <NEW_LINE> <INDENT> for key, value in MAIN_LANGUAGES.items(): <NEW_LINE> <INDENT> module_iso3 = value['language_code_3'] <NEW_LINE> if specific_code == module_iso3: <NEW_LINE> <INDENT> return key <NEW_LINE> <DEDENT> <DEDENT> return None
Function to get the equivalent ISO 639-1 code from an ISO 639-3 code if it exists. :param specific_code: An ISO 639-3 code. :return:
625941e0d6c5a102081443d5
def get_declared_actors(self) -> Set[str]: <NEW_LINE> <INDENT> return set(self.actors.keys())
Get all declared actors. Returns: set[str]: The names of all the actors declared so far on this Broker.
625941e04e4d5625662d475a
def test_create_user(): <NEW_LINE> <INDENT> created_user = {"name": "Jacob Wright", "age": 25} <NEW_LINE> with flask_app.test_client() as test_client: <NEW_LINE> <INDENT> response = test_client.post('/api/users/', json={ "name": created_user["name"] }) <NEW_LINE> assert response.status_code == 201 <NEW_LINE> assert res...
POST /users/ Requirements: F-1
625941e09b70327d1c4e115d
def repeatedNTimes(self, A: List[int]) -> int: <NEW_LINE> <INDENT> n = len(A) // 2 <NEW_LINE> cnt = Counter(A) <NEW_LINE> for i in cnt: <NEW_LINE> <INDENT> if cnt[i] > 1: <NEW_LINE> <INDENT> return i
k = set() for i in A: if i in k: return i else: k.add(i)
625941e0cb5e8a47e48b7e2c
def test_innerwt_empty(self): <NEW_LINE> <INDENT> a = np.array([], dtype='f8') <NEW_LINE> b = np.array([], dtype='f8') <NEW_LINE> w = np.array([], dtype='f8') <NEW_LINE> assert_array_equal(umt.innerwt(a,b,w), np.sum(a*b*w,axis=-1))
Test generalized ufunc with zero-sized operands
625941e0460517430c394504
def t150280_x23(val2=10, val3=12): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> call = t150280_x16(val2=val2, val3=val3) <NEW_LINE> if f122() == 1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elif not f122(): <NEW_LINE> <INDENT> call = t150280_x26(val2=val2, val3=val3) <NEW_LINE> assert not IsPlayerDead() <NEW...
State 0
625941e0ff9c53063f47c579
def get_options(self): <NEW_LINE> <INDENT> options = {} <NEW_LINE> if self.config.options: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fields = self.config.options.strip().split(",") <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> log.warning("Failed parsing the options: %s", e) <NEW_LINE> <DEDENT> els...
Get analysis options. @return: options dict.
625941e00fa83653e4657340
def _setParameterValue(self, name, value, typeString = ''): <NEW_LINE> <INDENT> method = getattr(self.__class__, "_setParameterValue" + typeToName(value.__class__)) <NEW_LINE> return method(self, name, value, typeString)
Set the value of a parameter by its name, creating a child element to hold the parameter if needed.
625941e0baa26c4b54cb14a3