code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(HomeView, self).get_context_data(**kwargs) <NEW_LINE> context['notes'] = models.Note.objects.all() <NEW_LINE> return context
Add notes list to context
625941d7d58c6744b4257ec2
def copy(self): <NEW_LINE> <INDENT> return self.__class__.load(self.save())
Returns copy of this willy.
625941d732920d7e50b28435
def getPaused(self): <NEW_LINE> <INDENT> return self._paused
Returns: the _paused status of the game
625941d7462c4b4f79d1d933
def FCI(self): <NEW_LINE> <INDENT> nEle = self.mol.nelec <NEW_LINE> nOrb = self.mol.norb <NEW_LINE> det_list = [] <NEW_LINE> if comb(nOrb,nEle) > 5000: <NEW_LINE> <INDENT> print("Number determinants: ",comb(nOrb,nEle)) <NEW_LINE> sys.exit("FCI too expensive. Quitting.") <NEW_LINE> <DEDENT> for occlist in combinations(r...
Routine to compute FCI energy from RHF reference
625941d766656f66f7cbc410
def asserter(line1, line2, expectedVal): <NEW_LINE> <INDENT> self.assertEqual(self.checkImports.compareImportLines(line1, line2), expectedVal)
shortcut for shorter lines
625941d773bcbd0ca4b2c2d9
def _estimate_error_rate(self, x): <NEW_LINE> <INDENT> test_bits = [] <NEW_LINE> test_indices = [] <NEW_LINE> if self.role == LEADER_ROLE: <NEW_LINE> <INDENT> while len(test_indices) < ROUND_SIZE // 4 and len(x) > 0: <NEW_LINE> <INDENT> index = random.randint(0, len(x) - 1) <NEW_LINE> test_bits.append(x.pop(index)) <NE...
Estimates the error rate of the exchanged BB84 information :param x: list The measurement outcomes obtained :param num_test_bits: int The number of bits we should test :return: float The error rate of the communicated information
625941d7377c676e9127240c
def isPalindrome(self, head): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> temp = head <NEW_LINE> middle = head <NEW_LINE> while temp: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> if count % 2 == 0: <NEW_LINE> <INDENT> middle = middle.next <NEW_LINE> <DEDENT> temp = temp.next <NEW_LINE> <DEDENT> pre = middle <NEW_LINE> temp2 ...
:type head: ListNode :rtype: bool
625941d7d8ef3951e32437a1
def sample(self, size): <NEW_LINE> <INDENT> return random.sample(self.memory, size)
Samples slice of arrays with input size.
625941d707f4c71912b116e7
def parse_schema(self, name): <NEW_LINE> <INDENT> assert name, "how can we parse something we can't find?" <NEW_LINE> schema_xml = Doc.get_schema_xml(name, self.cursor) <NEW_LINE> root = etree.fromstring(schema_xml.encode("utf-8")) <NEW_LINE> if root.tag != Schema.SCHEMA: <NEW_LINE> <INDENT> raise Exception("Top-level ...
Pull out the schema information we need for generating the DTD
625941d70a366e3fb873ea7f
@app.route('/pdf/<path:fname>') <NEW_LINE> def get_pdf(fname): <NEW_LINE> <INDENT> return send_from_directory('/tmp', fname, as_attachment=True)
Get PDF resource.
625941d707d97122c4178af3
def linear_activation_forward(A_prev, W, b, activation): <NEW_LINE> <INDENT> Z, linear_cache = linear_forward(A_prev, W, b) <NEW_LINE> if activation == "sigmoid": <NEW_LINE> <INDENT> A, activation_cache = sigmoid(Z) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> A, activation_cache = relu(Z) <NEW_LINE> <DEDENT> assert (...
Implement the forward propagation for the LINEAR->ACTIVATION layer Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of...
625941d79c8ee82313fbb9d9
def ingest_walk(self, root): <NEW_LINE> <INDENT> from ctools import s3 <NEW_LINE> (bucket,key) = s3.get_bucket_key(root) <NEW_LINE> for obj in s3.list_objects(bucket,key): <NEW_LINE> <INDENT> self.insert_file( path=obj['Key'], mtime=obj['LastModified'], file_size=obj['Size'], hexdigest=obj['ETag'] ) <NEW_LINE> self.fil...
Walk S3 bucket. Do not go inside ZIP files
625941d766673b3332b922f5
def _compare_dicts(dict1, dict2): <NEW_LINE> <INDENT> if set(dict1.keys()) != set(dict2.keys()): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> for i in dict1: <NEW_LINE> <INDENT> if isinstance(dict1[i], dict) and isinstance(dict2[i], dict): <NEW_LINE> <INDENT> return _compare_dicts(dict1[i], dict2[i]) <NEW_LINE> <DE...
Compares two dictionaries to see if all keys of all dictionaries (nested or not) match. Recursive fxn. Returns: returncode -- 0 (success) or 1 (failure)
625941d730dc7b7665901bc8
def test_channels(self): <NEW_LINE> <INDENT> song = Song(testfile) <NEW_LINE> self.assertEqual(song.channels, 2) <NEW_LINE> self.assertIs(song.channels, song.channels)
Test the amount of channels of the audio stream is retrieved correctly.
625941d7435de62698dfdeb1
def can_query(self): <NEW_LINE> <INDENT> return self.property_type.indexed
Returns True if this property can be used as a query filter, False otherwise.
625941d756ac1b37e6264430
def _normalise_by_monitor(self): <NEW_LINE> <INDENT> indices_in_range = np.where((self.mon_pt_times >= self._mon_norm_start) & (self.mon_pt_times < self._mon_norm_end)) <NEW_LINE> wsindex = self._ws_index <NEW_LINE> def monitor_normalization(foil_ws, mon_ws): <NEW_LINE> <INDENT> mon_values = mon_ws.readY(wsindex) <NEW_...
Normalises by the monitor counts between mon_norm_start & mon_norm_end instrument parameters for the current workspace index
625941d7f9cc0f698b14085d
def vector_sum(vectors): <NEW_LINE> <INDENT> return reduce(vector_add,vectors)
Суммирует все соответствующие элементы
625941d7656771135c3ebad4
def download_action(path_to_file, date_arg, data_type, filter_europe): <NEW_LINE> <INDENT> file_name = path_to_file.split("/")[-1] <NEW_LINE> try: <NEW_LINE> <INDENT> r = retrieve.Retrieve() <NEW_LINE> result = r.retrieve_file(path_to_file, date=date_arg, data_type=data_type, filter_europe=filter_europe) <NEW_LINE> fil...
action to be called within another thread :param path_to_file: path to the downloaded file :param date_arg: date of retrieval :param data_type: where is the data stored :param filter_europe: do we want only european files? :return: Filename if successful, None if an error occurs.
625941d70383005118ecf845
def apply(self, fun=None, axis=0): <NEW_LINE> <INDENT> from .astfun import _bytecode_decompile_lambda <NEW_LINE> if axis not in [0,1]: <NEW_LINE> <INDENT> raise ValueError("margin must be either 0 (cols) or 1 (rows).") <NEW_LINE> <DEDENT> if fun is None: <NEW_LINE> <INDENT> raise ValueError("No function to apply.") <NE...
Apply a lambda expression to an H2OFrame. Parameters ---------- fun: lambda A lambda expression to be applied per row or per column axis: int 0: apply to each column; 1: apply to each row Returns ------- H2OFrame
625941d7cc0a2c11143dd0f4
@node.commandWrap <NEW_LINE> def HypershadeSortByName(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.HypershadeSortByName(*args, **kwargs)
:rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941d7656771135c3ebad5
@app.route('/podcast/update/<podcast_id>', methods=['GET', 'POST']) <NEW_LINE> def podcast_update(podcast_id): <NEW_LINE> <INDENT> if 'username' not in session: <NEW_LINE> <INDENT> flash(f'Oops... you need to be logged in to see this page.', 'danger') <NEW_LINE> return redirect(url_for('login')) <NEW_LINE> <DEDENT> els...
Function that checks whether user is logged in. For logged in user it opens page with a form that allows user to edit existing content to the database. It searches collection podcasts in the detabase and displays pre-filled in form with the content of a podcast found using value "ObjectId(podcast_id)" of a key "_id". ...
625941d760cbc95b062c67a7
def __init__(self, make, model, year): <NEW_LINE> <INDENT> super().__init__(make, model, year) <NEW_LINE> self.battery = Battery()
Initialize atributes of the parent class. Then initialize attributes specific to an electric car.
625941d7bd1bec0571d90893
@dispatch.polymorphic <NEW_LINE> def state_eq(x, y): <NEW_LINE> <INDENT> raise NotImplementedError()
Are the states of x and y exactly the same?
625941d7ac7a0e7691ed432c
def is_compatible_with(self, spec_or_tensor): <NEW_LINE> <INDENT> return super(TensorSpec, self).is_compatible_with(spec_or_tensor)
Returns True if spec_or_tensor is compatible with this TensorSpec. Two tensors are considered compatible if they have the same dtype and their shapes are compatible (see `tf.TensorShape.is_compatible_with`). Args: spec_or_tensor: A tf.TensorSpec or a tf.Tensor Returns: True if spec_or_tensor is compatible with s...
625941d78e05c05ec3eea5da
def get_ugid_from_processid(pid): <NEW_LINE> <INDENT> grep_ugid_cmd = "cat /proc/%s/status | grep -iE '^(U|G)id'" <NEW_LINE> o = process.system_output(grep_ugid_cmd % pid.strip(), shell=True) <NEW_LINE> ugid = re.findall(r"(\d+)", o) <NEW_LINE> if ugid: <NEW_LINE> <INDENT> return ugid <NEW_LINE> <DEDENT> else: <NEW_LIN...
return a list[uid,euid,suid,fsuid,gid,egid,sgid,fsgid] of pid
625941d7e5267d203edcdefe
def _data_and_metadata(self): <NEW_LINE> <INDENT> md = {} <NEW_LINE> if self.metadata: <NEW_LINE> <INDENT> md.update(self.metadata) <NEW_LINE> <DEDENT> if self.width: <NEW_LINE> <INDENT> md['width'] = self.width <NEW_LINE> <DEDENT> if self.height: <NEW_LINE> <INDENT> md['height'] = self.height <NEW_LINE> <DEDENT> if se...
shortcut for returning metadata with shape information, if defined
625941d7379a373c97cfadaa
def test_45_basic_limits_combined(self): <NEW_LINE> <INDENT> parents = [MagicMock(device=self._mock_device(), min_size=Size("1 MiB"), max_size=Size("1 GiB"), reserved_size=Size(0)), MagicMock(device=self._mock_device(), min_size=Size("1 MiB"), max_size=Size("1 GiB"), reserved_size=Size(0))] <NEW_LINE> size_area = SizeA...
Test SizeArea limits functionality without ParentArea
625941d7adb09d7d5db6c9f2
def test_grid_file_path(self): <NEW_LINE> <INDENT> expected_path = os.path.join( shakemap_extract_dir(), SHAKE_ID, 'grid.xml') <NEW_LINE> working_dir = shakemap_extract_dir() <NEW_LINE> shake_event = ShakeEvent( working_dir=working_dir, event_id=SHAKE_ID, data_is_local_flag=True) <NEW_LINE> grid_path = shake_event.grid...
Test grid_file_path works using cached data.
625941d70383005118ecf846
def updateMessages(self): <NEW_LINE> <INDENT> if self.params[0].value: <NEW_LINE> <INDENT> input_files = self.params[0].valueAsText.split(';') <NEW_LINE> for i in input_files: <NEW_LINE> <INDENT> i_desc = arcpy.Describe(i) <NEW_LINE> if i_desc.dataType == 'Folder': <NEW_LINE> <INDENT> if self.params[1].valueAsText == '...
Modify the messages created by internal validation for each tool parameter. This method is called after internal validation.
625941d7167d2b6e31218df9
def test_change_user_company(self): <NEW_LINE> <INDENT> User = self.env['res.users'] <NEW_LINE> Company = self.env['res.company'] <NEW_LINE> test_user = User.create({'name': 'John Smith', 'login': 'jsmith'}) <NEW_LINE> company_1 = Company.create({'name': 'company_1'}) <NEW_LINE> company_2 = Company.create({'name': 'com...
Check the partner company update when the user company is changed
625941d74c3428357757c58b
@disallow("M8") <NEW_LINE> @bottleneck_switch(ddof=1) <NEW_LINE> def nanvar(values, axis=None, skipna=True, ddof=1, mask=None): <NEW_LINE> <INDENT> values = lib.values_from_object(values) <NEW_LINE> dtype = values.dtype <NEW_LINE> mask = _maybe_get_mask(values, skipna, mask) <NEW_LINE> if is_any_int_dtype(values): <NEW...
Compute the variance along given axis while ignoring NaNs Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. mask : ndarray[bool], optiona...
625941d7283ffb24f3c55b63
def __init__(self, file_or_io: Union[str, TextIO, BinaryIO], mode: ReadMode = ReadMode.OBJECT, encoding: str = 'utf-8', types: Union[List[Type], Dict[str, Type]] = None): <NEW_LINE> <INDENT> if mode not in [ReadMode.OBJECT, ReadMode.DICT, ReadMode.LIST]: <NEW_LINE> <INDENT> raise ValueError(f'The read mode only can be ...
Constructor of this CSV reader. :param file_or_io: The file path or an opened stream to use. If it is a file path and it ends in .gz, then the compressed file is read using gzip. :param encoding: The encoding (it is only used if the parameter file_or_io is a file path). :param mode: The default mode to read the rows. ...
625941d73617ad0b5ed6815a
def test_make_sim_metaclass(): <NEW_LINE> <INDENT> class SimTest1(Simulation): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> sim_file = 'Tuscon.json' <NEW_LINE> sim_path = os.path.join(PROJ_PATH, 'simulations', 'Standalone') <NEW_LINE> <DEDENT> <DEDENT> sim_test1 = SimTest1() <NEW_LINE> return sim_test1
Test setting the simulation parameter file as class attributes versus specifying the simulation parameter file in the model parameter file. :return: simulation
625941d7498bea3a759b9d13
def test_sparse_dense(): <NEW_LINE> <INDENT> for s in scenarios(): <NEW_LINE> <INDENT> validate_sparse_dense(**s)
Test sparse / dense consistency
625941d7be7bc26dc91cd860
def CreateChannelCode(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("CreateChannelCode", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.CreateChannelCodeResponse...
新增渠道活码接口 :param request: Request instance for CreateChannelCode. :type request: :class:`tencentcloud.wav.v20210129.models.CreateChannelCodeRequest` :rtype: :class:`tencentcloud.wav.v20210129.models.CreateChannelCodeResponse`
625941d7287bf620b61d3cc6
def __init__(self, call: 'TypeGroupCall', participants: List['TypeGroupCallParticipant'], participants_next_offset: str, users: List['TypeUser']): <NEW_LINE> <INDENT> self.call = call <NEW_LINE> self.participants = participants <NEW_LINE> self.participants_next_offset = participants_next_offset <NEW_LINE> self.users = ...
Constructor for phone.GroupCall: Instance of GroupCall.
625941d750812a4eaa59c584
def with_id(self, object_id): <NEW_LINE> <INDENT> if not self._query_obj.empty: <NEW_LINE> <INDENT> raise InvalidQueryError( "Cannot use a filter whilst using `with_id`") <NEW_LINE> <DEDENT> return self.filter(pk=object_id).first()
Retrieve the object matching the id provided. Uses `object_id` only and raises InvalidQueryError if a filter has been applied. :param object_id: the value for the id of the document to look up .. versionchanged:: 0.6 Raises InvalidQueryError if filter has been set
625941d70c0af96317bb844c
def GetValue(self): <NEW_LINE> <INDENT> return self._trackposition
Returns the value of L{KnobCtrl}.
625941d7a17c0f6771cbe2b4
def current_statistics(): <NEW_LINE> <INDENT> locals()[LOCALS_KEY_KI_PROTECTION_ENABLED] = True <NEW_LINE> try: <NEW_LINE> <INDENT> return GLOBAL_RUN_CONTEXT.runner.current_statistics() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise RuntimeError("must be called from async context")
Returns an object containing run-loop-level debugging information. Currently the following fields are defined: * ``tasks_living`` (int): The number of tasks that have been spawned and not yet exited. * ``tasks_runnable`` (int): The number of tasks that are currently queued on the run queue (as opposed to blocked ...
625941d731939e2706e4d0cb
def save(self): <NEW_LINE> <INDENT> if not self.is_unique(): <NEW_LINE> <INDENT> print( "{} tried to save a job hat is not unique!".format(self.organization)) <NEW_LINE> return <NEW_LINE> <DEDENT> self.cleanup() <NEW_LINE> try: <NEW_LINE> <INDENT> self.validate() <NEW_LINE> <DEDENT> except KeyError as err: <NEW_LINE> <...
Save job to DB, after final checks.
625941d7004d5f362079a596
def _retrieve_interesting_stops(list_ad): <NEW_LINE> <INDENT> res = [] <NEW_LINE> picked_one = False <NEW_LINE> sorted_list_stops = sorted(list_ad, key=itemgetter("rang")) <NEW_LINE> for idx, stop in enumerate(sorted_list_stops): <NEW_LINE> <INDENT> has_departure = _has_departure(stop) <NEW_LINE> has_arrival = _has_arr...
Filter and sort "Arrets Desserte" (corresponding to stop_times in Navitia) to get only the relevant ones from a Navitia's perspective (stations, where travelers can hop on or hop off) :param list_ad: an array of "Arrets Desserte" (typically the one from the feed) :return: Filtered array Notes: - written in a yield-fas...
625941d74e696a04525c96b0
def to_str(s, encoding=None): <NEW_LINE> <INDENT> if isinstance(s, str): <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> if six.PY3: <NEW_LINE> <INDENT> if isinstance(s, (bytes, bytearray)): <NEW_LINE> <INDENT> return s.decode(encoding or __salt_system_encoding__, "replace") <NEW_LINE> <DEDENT> raise TypeError('expect...
Given str, bytes, bytearray, or unicode (py2), return str
625941d78e7ae83300e4b231
def load(self): <NEW_LINE> <INDENT> if not self.use_matrix: <NEW_LINE> <INDENT> log.info("[initializing `{}` from saved]".format(self.__class__.__name__)) <NEW_LINE> if self.int2emb_load_path.is_file(): <NEW_LINE> <INDENT> self.emb_matrix = np.load(self.int2emb_load_path)
Initialize embeddings from the file.
625941d7287bf620b61d3cc7
def add_subtitle_encoding_menu(self, category_label, *encodings): <NEW_LINE> <INDENT> self.subtitle_encoding_updater.add_menu(category_label, encodings)
Set up a subtitles encoding menu. This method should be called for each category of subtitle encodings (East Asian, Western European, Unicode, etc). Pass it the list of encodings for that category. :param category_label: human-readable name for the category :param encodings: list of (label, encoding) tuples. label ...
625941d7cc40096d61595bb4
def get_sprite_url(url, sprite='front_default'): <NEW_LINE> <INDENT> return url['name'], get(url['url']).json()['sprites'][sprite]
Pega a url do sprite.
625941d7627d3e7fe0d690b5
def LENB(*args) -> Function: <NEW_LINE> <INDENT> return Function("LENB", args)
Returns the length of a string in bytes." Learn more: https//support.google.com/docs/answer/9367584.
625941d78c0ade5d55d3ec20
def _find_max_per_frame(nccf, sample_rate, freq_high): <NEW_LINE> <INDENT> lag_min = int(math.ceil(sample_rate / freq_high)) <NEW_LINE> best = torch.max(nccf[..., lag_min:], -1) <NEW_LINE> half_size = nccf.shape[-1] // 2 <NEW_LINE> half = torch.max(nccf[..., lag_min:half_size], -1) <NEW_LINE> best = _combine_max(half, ...
For each frame, take the highest value of NCCF, apply centered median smoothing, and convert to frequency. Note: If the max among all the lags is very close to the first half of lags, then the latter is taken.
625941d79f2886367277aaf0
def save_system_output(db, folds, param, log, output_file, mode='dcase'): <NEW_LINE> <INDENT> all_res = dcase_util.containers.MetaDataContainer( filename=output_file ) <NEW_LINE> for fold in folds: <NEW_LINE> <INDENT> fold_results_filename = os.path.join( param.get_path('path.application.recognizer'), 'res_fold_{fold}....
Save system output Parameters ---------- db : dcase_util.dataset.Dataset Dataset folds : list List of active folds param : dcase_util.containers.DCASEAppParameterContainer Application parameters log : dcase_util.ui.FancyLogger Logging interface output_file : str mode : str Output mode, possibl...
625941d7cad5886f8bd2723d
def test_permission_create_user_unauthenticated(self): <NEW_LINE> <INDENT> data = { 'email': 'user1@example.org', 'password': 'testpassword', 'first_name': 'user1', 'last_name': 'example', 'admin': False, } <NEW_LINE> resp = self.client.post(reverse('user-list'), data=data) <NEW_LINE> self.assertEqual(resp.status_code,...
Unauthenticated users should not be able to create users.
625941d7d4950a0f3b08c5b1
def cone(*args, **kwargs): <NEW_LINE> <INDENT> pass
The cone command creates a new cone and/or a dependency node that creates one, and returns their names. Flags: - axis : ax (float, float, float) [create,query,edit] The primitive's axis - caching : cch (bool) [create,query,edit] Modifies the node caching ...
625941d7d7e4931a7ee9e182
def describe(self, name): <NEW_LINE> <INDENT> d_string = DRMAA_LIB.drmaa2_describe_attribute( cast(self.parent._wrapped, c_void_p), name.encode()) <NEW_LINE> return return_str(d_string)
Get the text description of an implementation-specific attribute. :param name str: From the list of implementation-specific names. :return str: A description.
625941d73d592f4c4ed1d2ce
def test_to_json_string(self): <NEW_LINE> <INDENT> l_none, l0 = None, [] <NEW_LINE> l1 = [{'1': 'one', '2': 'two'}] <NEW_LINE> l2 = [{'1': 'one'}, {'2': [2]}] <NEW_LINE> newObj = Base.from_json_string(Base.to_json_string(l_none)) <NEW_LINE> self.assertEqual([], newObj) <NEW_LINE> newObj = Base.from_json_string(Base.to_...
test to_json_string This test convert object to string and convert back to object to see if an object is correctly converted to json string
625941d77c178a314d6ef6c7
def __init__(self, parent, scanner, rule, args=()): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.scanner = scanner <NEW_LINE> self.rule = rule <NEW_LINE> self.args = args <NEW_LINE> while scanner.stack: scanner = scanner.stack <NEW_LINE> self.token = scanner.last_read_token
Create a new context. Args: parent: Context object or None scanner: Scanner object rule: string (name of the rule) args: tuple listing parameters to the rule
625941d715baa723493c41dc
def test_success_leave_topic_as_author_no_participants(self): <NEW_LINE> <INDENT> self.private_topic.participants.clear() <NEW_LINE> self.private_topic.save() <NEW_LINE> response = self.client.delete(reverse('api:mp:detail', args=[self.private_topic.id])) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_20...
Leaves a private topic when we are the last participant.
625941d7e64d504609d74aa4
def _cells(nb): <NEW_LINE> <INDENT> if nb.nbformat < 4: <NEW_LINE> <INDENT> for ws in nb.worksheets: <NEW_LINE> <INDENT> for cell in ws.cells: <NEW_LINE> <INDENT> yield cell <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for cell in nb.cells: <NEW_LINE> <INDENT> yield cell
Returns a generator with reference to cells in the passed notebook. :param nb: Jupyter Notebook Object :return: generator with cell references
625941d726068e7796caef47
def read_dataset(filename, fill_na=False) -> pd.DataFrame: <NEW_LINE> <INDENT> dataset = pd.read_csv(filename, na_filter=True) <NEW_LINE> if fill_na: <NEW_LINE> <INDENT> dataset = dataset.fillna(0) <NEW_LINE> <DEDENT> logger.info(f'read {len(dataset)} flows from {filename}') <NEW_LINE> return dataset
a simple wrapper for pandas
625941d792d797404e3043ef
def process(text, tokenizer=TweetTokenizer(), stopwords=[]): <NEW_LINE> <INDENT> text = text.lower() <NEW_LINE> tokens = tokenizer.tokenize(text) <NEW_LINE> return [tok for tok in tokens if tok not in stopwords and not tok.isdigit()]
Process the text of a tweet: - Lowercase - Tokenize - Stopword removal - Digits removal Return: list of strings
625941d7bde94217f3683053
def get_available_pkg_updates(self, nodes, salt): <NEW_LINE> <INDENT> updates = {} <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> updates[node] = salt.local( node, "pkg.list_upgrades")['return'][0][node] <NEW_LINE> <DEDENT> return updates
Collect available package updates for given nodes :param nodes: list, nodes to collect available updates for :param salt: SaltManager, tcp-qa Salt manager instance :return: dict, update candidates for nodes
625941d730c21e258bdfa703
def detect_faces(detection_model, gray_image_array): <NEW_LINE> <INDENT> return detection_model.detectMultiScale(gray_image_array, 1.3, 5)
function to detect faces
625941d71f5feb6acb0c4db2
def __init__(self, name, prereqs=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> if prereqs is None: <NEW_LINE> <INDENT> self.prereqs = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.prereqs = prereqs <NEW_LINE> <DEDENT> self.taken = False
(Course, str, list of Courses) -> NoneType Create a new course with given name and prerequisites. By default, the course has no prerequisites (represent this with an empty list, NOT None). The newly created course is not taken.
625941d7e64d504609d74aa5
def _set_models(self, results): <NEW_LINE> <INDENT> self._log_header1(gammalib.NORMAL, 'Set models') <NEW_LINE> models = gammalib.GModels() <NEW_LINE> has_stacked_model = False <NEW_LINE> for model in self._models: <NEW_LINE> <INDENT> use_model = False <NEW_LINE> if 'GCTA' in model.classname(): <NEW_LINE> <INDENT> if n...
Set models for On/Off fitting The method does the following - append "OnOff" to the instrument name of all background models - fix all spatial and temporal parameters Parameters ---------- results : list of dict Result dictionaries Returns ------- models : `~gammalib.GModels()` Model container
625941d76fb2d068a760f305
def __call__(self): <NEW_LINE> <INDENT> return {'reye' : (self.re_y, self.re_x), 'leye' : (self.le_y, self.le_x) }
Returns the annotations of this database in a dictionary: {'reye' : (re_y, re_x), 'leye' : (le_y, le_x)}.
625941d70a50d4780f6670f8
def test_MINU(self): <NEW_LINE> <INDENT> assert(True) <NEW_LINE> check_instruction("MINU $1, $2", "f1210006")
Test the MINU instruction
625941d7e1aae11d1e749f1e
def wrap_exceptions(fun): <NEW_LINE> <INDENT> @functools.wraps(fun) <NEW_LINE> def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return fun(self, *args, **kwargs) <NEW_LINE> <DEDENT> except OSError as err: <NEW_LINE> <INDENT> if err.errno == errno.ESRCH: <NEW_LINE> <INDENT> if not pid_exi...
Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied.
625941d723849d37ff7b32f2
def save_file(self): <NEW_LINE> <INDENT> pass
Called when the UI wants to save the file
625941d744b2445a339322f9
def __init__(self): <NEW_LINE> <INDENT> self.container = [] <NEW_LINE> self.i_map = collections.defaultdict(set)
Initialize your data structure here.
625941d7460517430c3943e5
def test_retrieve_ingredients_assigned_unique(self): <NEW_LINE> <INDENT> ingredient = Ingredient.objects.create(user=self.user, name='Eggs') <NEW_LINE> Ingredient.objects.create(user=self.user, name='Cheese') <NEW_LINE> recipe1 = Recipe.objects.create( title='Eggs benedict', time_minutes=30, price=12.00, user=self.user...
Test filtering ingredients by assigned returns unique items.
625941d730dc7b7665901bc9
def __init__(self, feat_sym, roidb, batch_size=1, shuffle=False, ctx=None, work_load_list=None, feat_stride=16, anchor_scales=(8, 16, 32), anchor_ratios=(0.5, 1, 2), allowed_border=0): <NEW_LINE> <INDENT> super(AnchorLoader, self).__init__() <NEW_LINE> self.feat_sym = feat_sym <NEW_LINE> self.roidb = roidb <NEW_LINE> s...
This Iter will provide roi data to Fast R-CNN network :param feat_sym: to infer shape of assign_output :param roidb: must be preprocessed :param batch_size: must divide BATCH_SIZE(128) :param shuffle: bool :param ctx: list of contexts :param work_load_list: list of work load :param aspect_grouping: group images with si...
625941d77d847024c06be523
def locate(self, pattern, big_endian=False): <NEW_LINE> <INDENT> space, self.space = tee(self.space) <NEW_LINE> if pattern.startswith('0x'): <NEW_LINE> <INDENT> target = unhexlify( pattern[2:].encode('utf-8')).decode('utf-8') <NEW_LINE> if not big_endian: <NEW_LINE> <INDENT> target = target[::-1] <NEW_LINE> <DEDENT> <D...
Locate the pattern.
625941d760cbc95b062c67a8
def agree_strings_to_ints(self, agree): <NEW_LINE> <INDENT> mfeat = self.get_feat_int(agree[1]) <NEW_LINE> labeldfeat = self.get_labeldfeat_int(agree[0], agree[2]) <NEW_LINE> return mfeat, labeldfeat
Convert an agree triple of strings to a pair of ints.
625941d79b70327d1c4e103a
def get_oauth_token(key, secret): <NEW_LINE> <INDENT> oauth_url = "https://api.idealista.com/oauth/token" <NEW_LINE> payload = {"grant_type": "client_credentials"} <NEW_LINE> r = requests.post(oauth_url, auth=HTTPBasicAuth(key, secret), data=payload) <NEW_LINE> return r.text
Gets oauth2 token from the API Key and Secret provided by idealista
625941d7925a0f43d254a0dd
def relative_rate(self): <NEW_LINE> <INDENT> return _blocks_swig2.add_ss_sptr_relative_rate(self)
relative_rate(add_ss_sptr self) -> double
625941d73317a56b86939eb9
def test_number_to_words(self): <NEW_LINE> <INDENT> test_cases = (('six', 6), ('fifteen', 15), ('forty-six', 46), ('one hundred and sixty-seven', 167), ('two hundred', 200), ('one thousand', 1000)) <NEW_LINE> for test_case in test_cases: <NEW_LINE> <INDENT> self.assertEqual(e0017.number_to_words(test_case[1]), test_cas...
test number to words on some examples
625941d7d486a94d0b98e3ab
def dns_mgr(): <NEW_LINE> <INDENT> return DnsManager
return the global user manager instance
625941d710dbd63aa1bd2e07
def hasPathSum(self, root, sum): <NEW_LINE> <INDENT> if root == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if sum == root.val and root.left == None and root.right == None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right,...
:type root: TreeNode :type sum: int :rtype: bool
625941d78e7ae83300e4b232
def show_anaglyph(self): <NEW_LINE> <INDENT> self.parent.launch_context_item(anaglyph.PlotAnaglyph)
Show anaglyph of raster data.
625941d75166f23b2e1a53be
@_wrapin <NEW_LINE> def crossings(y, value, x=None): <NEW_LINE> <INDENT> if x is None: <NEW_LINE> <INDENT> return _dsutils.crossings(y, value) <NEW_LINE> <DEDENT> return _dsutils.crossings(x, y, value)
Finds the crossing points where a (poly-)line defined by a 1D y array has the given values and return the (linearly) interpolated index or x value if an x array is given
625941d74a966d76dd551276
def certutil(vol_utils): <NEW_LINE> <INDENT> certutil_cmd = r"certutil -addstore -f TrustedPublisher %s\redhat.cer" % vol_utils <NEW_LINE> if not os.path.exists(r"C:\certutil.exe"): <NEW_LINE> <INDENT> shutil.copy(r"%s\certutil.exe" % vol_utils, r"C:\certutil.exe") <NEW_LINE> <DEDENT> if not os.path.exists(r"C:\certadm...
Install certificate. :param vol_utils: Volume of Win_utils.
625941d7009cb60464c63615
def list_of_scalars_summary(self, tag_value_pairs, step): <NEW_LINE> <INDENT> with self.writer.as_default(): <NEW_LINE> <INDENT> for tag, value in tag_value_pairs: <NEW_LINE> <INDENT> tf.summary.scalar(tag,value,step=step) <NEW_LINE> self.writer.flush()
Log scalar variables.
625941d723849d37ff7b32f3
@eel.expose <NEW_LINE> def convert(command, output, recursion_limit): <NEW_LINE> <INDENT> eel.addOutput("Building in the current instances temporary directory at {}\n".format(temporary_directory)) <NEW_LINE> eel.addOutput("To get a new temporary directory, restart this application\n") <NEW_LINE> dist_path = os.path.joi...
Package the executable passing the arguments the user requested
625941d707d97122c4178af4
def separa_sentencas(texto): <NEW_LINE> <INDENT> sentencas = re.split(r'[.!?]+', texto) <NEW_LINE> if sentencas[-1] == '': <NEW_LINE> <INDENT> del sentencas[-1] <NEW_LINE> <DEDENT> return sentencas
A funcao recebe um texto e devolve uma lista das sentencas dentro do texto.
625941d78da39b475bd651db
def test_with_routine_and_params(self): <NEW_LINE> <INDENT> self.registry.register(open) <NEW_LINE> params = {'a': 1} <NEW_LINE> conf = self.registry.conf(open, [], params) <NEW_LINE> self.assertEqual(conf[TASK_NAME], getpath(open)) <NEW_LINE> self.assertEqual(conf[TASK_KWARGS], params)
Test to generate a new conf related to a task routine and params.
625941d79b70327d1c4e103b
def comp_feat(self, sig, rate): <NEW_LINE> <INDENT> feat, energy = base.mfcc(sig, rate, self.conf) <NEW_LINE> if self.conf['include_energy'] == 'True': <NEW_LINE> <INDENT> feat = np.append(feat, energy[:, np.newaxis], 1) <NEW_LINE> <DEDENT> if self.conf['dynamic'] == 'delta': <NEW_LINE> <INDENT> feat = base.delta(feat)...
compute the features Args: sig: the audio signal as a 1-D numpy array rate: the sampling rate Returns: the features as a [seq_length x feature_dim] numpy array
625941d7cad5886f8bd2723e
def setUp(self): <NEW_LINE> <INDENT> super(test_sseLunch, self).setUp() <NEW_LINE> self.demo_user = self.env['res.users'].search([('name', '=', 'Administrator')]) <NEW_LINE> self.new_id_order = self.env['lunch.order'].create({ 'user_id': self.demo_user.id, 'order_line_ids': '[]', })
*****setUp*****
625941d738b623060ff0b053
def test_returns_401_for_wrongly_signed_post_requests(self, client, data): <NEW_LINE> <INDENT> url = reverse('orders:order_creation') <NEW_LINE> data_string = json.dumps(data) <NEW_LINE> key = 'Wrong key'.encode() <NEW_LINE> hm = hmac.new(key, data_string.encode(), hashlib.sha256) <NEW_LINE> bad_hmac = base64.b64encode...
The handler must return a 401 response for wrongly signed POST requests.
625941d74e696a04525c96b1
def cavityfreq(p, natom, Lair): <NEW_LINE> <INDENT> N = p[0] <NEW_LINE> nair = p[1] <NEW_LINE> Lcell = p[2] <NEW_LINE> return N/(2*(nair * Lair + natom * Lcell))
Parameters: constans params: p = [Mode_number, n_air, cell_length] natom = atomic index of refraction Lair = beam path in air
625941d78c3a873295158621
def test_repr(self): <NEW_LINE> <INDENT> payload = payloads.GetAttributesResponsePayload( self.unique_identifier, self.attributes ) <NEW_LINE> unique_identifier = "unique_identifier={0}".format( payload.unique_identifier ) <NEW_LINE> payload_attributes = "attributes={0}".format( payload.attributes ) <NEW_LINE> expected...
Test that repr can be applied to a GetAttributes response payload.
625941d7f7d966606f6aa26c
def e_artigo_def(cc): <NEW_LINE> <INDENT> if not isinstance(cc, str): <NEW_LINE> <INDENT> raise ValueError("e_artigo_def:argumento invalido") <NEW_LINE> <DEDENT> return cc in ('A', 'O')
Utilizacao: e_artigo_def(<cadeia de caracteres>) Verifica se o input e um artigo_def valido e_artigo_def: cad. caracteres -> booleano Gramatica: <artigo_def>::=A|O
625941d7925a0f43d254a0de
@click.command("diseases", short_help="Update disease terms") <NEW_LINE> @click.option( "-f", "--downloads-folder", type=click.Path(exists=True, dir_okay=True, readable=True), help="specify path to folder where files necessary to update diseases are pre-downloaded", ) <NEW_LINE> @click.option( "--api-key", help="Downlo...
Update disease terms in mongo database. Use pre-downloaded resource files (phenotype_to_genes and genemap2) or download them from OMIM. Both options require using a valid omim api key.
625941d744b2445a339322fa
def score_energy(self, visible, hidden): <NEW_LINE> <INDENT> lag = max(self.n_lag_hidden, self.m_lag_visible) <NEW_LINE> assert(visible.shape == (lag, self.size_visible))
@param visible: visible input (includes time-lagged values) @param hidden: hidden input (NO time-lagged values)
625941d7435de62698dfdeb2
def testTeamScheduleResource(self): <NEW_LINE> <INDENT> model = victorops_client.models.team_schedule_resource.TeamScheduleResource()
Test TeamScheduleResource
625941d7097d151d1a2230be
def __init__(self, bar_type = 1, bar_char = "=", bar_term = ">", bar_len = 80 ): <NEW_LINE> <INDENT> self.bar_type = bar_type <NEW_LINE> self.bar_char = bar_char <NEW_LINE> self.bar_term = bar_term <NEW_LINE> self.bar_len = bar_len <NEW_LINE> self.prog = 0 <NEW_LINE> self.value = 0
standard initializer.
625941d726238365f5f0f0d6
def ExpectedConnections(self, run_params): <NEW_LINE> <INDENT> return {}
Returns the expected edges or an empty dict to skip the check.
625941d773bcbd0ca4b2c2dc
@pytest.mark.check_for_usbdevice <NEW_LINE> def test_extract_device_name(): <NEW_LINE> <INDENT> assert grml2usb.extract_device_name("/dev/sda") == "sda" <NEW_LINE> assert grml2usb.extract_device_name("/dev/sdb") == "sdb" <NEW_LINE> assert grml2usb.extract_device_name("/dev/sdb4") == "sdb"
Assert, that 'extract_device_name' returns a device name for a given path
625941d7ad47b63b2c50a1e5
def _create_csm_scores(self, csm_value): <NEW_LINE> <INDENT> if csm_value.exists: <NEW_LINE> <INDENT> stub_csm_record = namedtuple('stub_csm_record', 'correct, total, created') <NEW_LINE> return { self.location: stub_csm_record( correct=csm_value.raw_earned, total=csm_value.raw_possible, created=csm_value.created ) } <...
Creates a stub result from courseware student module for the given values.
625941d7cdde0d52a9e5329a
def __le__(self, other): <NEW_LINE> <INDENT> if isinstance(other, MemoryValue): <NEW_LINE> <INDENT> return self.get_value_signed() <= other.get_value_signed() <NEW_LINE> <DEDENT> elif isinstance(other, int): <NEW_LINE> <INDENT> return self.get_value_signed() <= other <NEW_LINE> <DEDENT> return NotImplemented
Less than or equals :param other: :return:
625941d7e8904600ed9f2195
def _return_data(self, system: str, action: str, success: bool, **kwargs) -> str: <NEW_LINE> <INDENT> base = { "user": cherrypy.request.params["user"], "class": self.__class__.__name__, "system": system, "action": action, "success": success, } <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> base[key] =...
creates the json for returning requiring some data but allowing more
625941d7507cdc57c6306f45
def is_role_registered(name: str) -> bool: <NEW_LINE> <INDENT> return name in roles._roles
Check the *name* role is already registered.
625941d745492302aab5e52b
@cross_origin() <NEW_LINE> @api.route('/actors/<name>/movies', methods=['GET']) <NEW_LINE> def get_actor_movies(name): <NEW_LINE> <INDENT> actor = Actor.query.filter(Actor.name == unquote(name)).first() <NEW_LINE> if not actor: <NEW_LINE> <INDENT> return abort(404) <NEW_LINE> <DEDENT> movies = [] <NEW_LINE> for movie i...
Return the list all actor's movies :param name of the actor (URL encoded) :return: JSON with movies information
625941d760cbc95b062c67a9
@app.route('/gps_coords/<jpid>/<srcStop>/<destStop>', methods=['GET']) <NEW_LINE> def retrieve_gps(jpid, srcStop, destStop): <NEW_LINE> <INDENT> return Db().get_gps(jpid, srcStop, destStop)
Retrieves gps coordinates of a given journey pattern id
625941d7cb5e8a47e48b7d0d