code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@patch('pyeloqua.forms.requests.get') <NEW_LINE> def test_f_get_data_parse(mock_get): <NEW_LINE> <INDENT> fpath = '/tmp/pyeloqua_test_f_init_path.json' <NEW_LINE> dump(FORM_SAMPLE, open(fpath, 'w')) <NEW_LINE> form = Form(test=True, form_path=fpath) <NEW_LINE> mock_get.return_value = Mock(ok=True, status_code=200) <NEW... | get_data returns complete parsed data | 625941da07f4c71912b11748 |
def commit(self, synchronous=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request = {} <NEW_LINE> with self.mutex: <NEW_LINE> <INDENT> if len(self.batch) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.index.batch({'requests': self.batch}) <NEW_LINE> res = self.index.setSettings({'userData': {'lastObj... | Send the current batch of updates
| 625941dabe383301e01b5745 |
def analysis_job_data(job_url): <NEW_LINE> <INDENT> if job_url is None: <NEW_LINE> <INDENT> print(u'工作详情地址为空,略过') <NEW_LINE> return <NEW_LINE> <DEDENT> print('job_url=%s' % job_url) <NEW_LINE> try: <NEW_LINE> <INDENT> html = rq.get(job_url) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LI... | 解析job详情页面里的pagenum数据 | 625941da5f7d997b87174d5e |
def build_multiple(stack, start_state, final_states): <NEW_LINE> <INDENT> a_start, a_finals = stack.pop() <NEW_LINE> for state in a_finals: <NEW_LINE> <INDENT> state.isFinalState = False <NEW_LINE> state.charTransitions = start_state.charTransitions <NEW_LINE> state.epsilonTransitions = start_state.epsilonTransitions <... | Построение оператора a*b
:param stack: стек автоматов
:param start_state: начальное состояние автомата b
:param final_states: конечные состояния автомата b | 625941daf548e778e58cd843 |
def main(): <NEW_LINE> <INDENT> for i in test_yield(5): <NEW_LINE> <INDENT> print(i) <NEW_LINE> <DEDENT> test = test_yield(5) <NEW_LINE> print(test.__class__) <NEW_LINE> print(test.next()) <NEW_LINE> print(test.next()) <NEW_LINE> print(test.next()) <NEW_LINE> print(test.next()) <NEW_LINE> print(test.next()) | docstring for main | 625941da796e427e537b088c |
def build_skip_conn_attn(cnn_channels, h_cnn_time, x_time, timespan): <NEW_LINE> <INDENT> skip = [None] <NEW_LINE> skip_ch = [0] <NEW_LINE> nlayers = len(h_cnn_time[0]) <NEW_LINE> timespan = len(h_cnn_time) <NEW_LINE> for jj in range(nlayers): <NEW_LINE> <INDENT> lidx = nlayers - jj - 2 <NEW_LINE> if lidx >= 0: <NEW_LI... | Build skip connection for attention based model. | 625941da851cf427c661a7d1 |
def setUp(self): <NEW_LINE> <INDENT> self.pool = models.IpPool.objects.create( family='ipv4', network='10.10.0.0', prefix_length=16, ) <NEW_LINE> self.small_pool = models.IpPool.objects.create( family='ipv4', network='192.168.1.0', prefix_length=26, ) <NEW_LINE> self._hold_down_period = models.IpPool.HOLD_DOWN_PERIOD <... | Prepare the IP pool test environment by creating some dummy IP
pools. | 625941dadd821e528d63b46c |
def update_jsondata(self, **kw): <NEW_LINE> <INDENT> d = (self.jsondata or {}).copy() <NEW_LINE> d.update(kw) <NEW_LINE> self.jsondata = d | Convenience function.
Since we use the simple
`JSON encoded dict recipe <http://docs.sqlalchemy.org/en/rel_0_9/core/types.html #marshal-json-strings>`_
without mutation tracking, we provide a convenience method to update | 625941da94891a1f4081bd6f |
def bt_next_question(self): <NEW_LINE> <INDENT> self.next_answer_true = True <NEW_LINE> if self.skin_button_activ is not False: <NEW_LINE> <INDENT> self.button_ok_procces.setStyleSheet("background-color:#52cc00;\n""") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.button_ok_procces.setStyleSheet("background-color:#... | Переход к следующему вопросу в валидации | 625941dadc8b845886cb57fa |
def remove(self, path, dir_fd=None): <NEW_LINE> <INDENT> path = self._path_with_dir_fd(path, self.remove, dir_fd) <NEW_LINE> self.filesystem.remove(path) | Remove the FakeFile object at the specified file path.
Args:
path: Path to file to be removed.
dir_fd: If not `None`, the file descriptor of a directory,
with `path` being relative to this directory.
New in Python 3.3.
Raises:
OSError: if path points to a directory.
OSError: if path do... | 625941da5fc7496912cc3c42 |
def plot_dust_cell_distributions(self): <NEW_LINE> <INDENT> log.info("Plotting dust cell distributions ...") <NEW_LINE> plotter = CellDistributionsPlotter() <NEW_LINE> plotter.config.path = self.config.path <NEW_LINE> plotter.run() | This function ...
:return: | 625941da5510c4643540f6a2 |
def addLeftChild(self, data): <NEW_LINE> <INDENT> n = self.__class__(data, self) <NEW_LINE> self.left = n <NEW_LINE> return n | This method adds a left child | 625941dab545ff76a89140d9 |
def accept_vpc_peering_connection( conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): <NEW_LINE> <INDENT> if not _exactly_one((conn_id, name)): <NEW_LINE> <INDENT> raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') <NEW_LINE> <... | Request a VPC peering connection between two VPCs.
:param conn_id: The ID to use. String type.
:param name: The name of this VPC peering connection. String type.
:param region: The AWS region to use. Type string.
:param key. The key to use for this connection. Type string.
:param keyid. The key id to use.
:param profi... | 625941da4f6381625f114d00 |
def _generate_new_id(self): <NEW_LINE> <INDENT> self._last_id += 1 <NEW_LINE> while f'_{self._last_id}' in self.nodes: <NEW_LINE> <INDENT> self._last_id += 1 <NEW_LINE> <DEDENT> return f'_{self._last_id}' | For private use, generates new id for nodes. | 625941da004d5f362079a5f6 |
def dajaxice_autodiscover(): <NEW_LINE> <INDENT> global LOADING_DAJAXICE <NEW_LINE> if LOADING_DAJAXICE: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> LOADING_DAJAXICE = True <NEW_LINE> import imp <NEW_LINE> from django.conf import settings <NEW_LINE> for app in settings.INSTALLED_APPS: <NEW_LINE> <INDENT> try: <NEW_L... | Auto-discover INSTALLED_APPS ajax.py modules and fail silently when
not present. NOTE: dajaxice_autodiscover was inspired/copied from
django.contrib.admin autodiscover | 625941da9c8ee82313fbba3a |
def enumerate(s, start=0): <NEW_LINE> <INDENT> zip(range(start, start+len(s)), s) | Returns a list of lists, where the i-th list contains i+`start` and the
i-th element of `s`.
>>> enumerate([6, 1, 'a'])
[[0, 6], [1, 1], [2, 'a']]
>>> enumerate('five', 5)
[[5, 'f'], [6, 'i'], [7, 'v'], [8, 'e']] | 625941da07d97122c4178b55 |
def download(url: str, dest: str) -> bool: <NEW_LINE> <INDENT> ydl_opts = { 'logger': logger, } <NEW_LINE> with change_dir(dest): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with youtube_dl.YoutubeDL(ydl_opts) as ydl: <NEW_LINE> <INDENT> ydl.download([url]) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> except yo... | Download media from url. | 625941da7d43ff24873a2f66 |
def create_volume(self, volume): <NEW_LINE> <INDENT> dres = self.is_clean_volume_name(volume['id'], DM_VN_PREFIX) <NEW_LINE> res = self.call_or_reconnect(self.odm.create_resource, dres, self.empty_dict) <NEW_LINE> self._check_result(res, ignore=[dm_exc.DM_EEXIST], ret=None) <NEW_LINE> (_, drbd_vol) = self._resource_nam... | Creates a DRBD resource.
We address it later on via the ID that gets stored
as a private property. | 625941dad10714528d5fffaa |
def setDescription(self, description): <NEW_LINE> <INDENT> self.description = description | Sets the description of the LookbackMultiple.
Arguments:
description - str value representing the description of the
LookbackMultiple. | 625941dad6c5a10208144311 |
@login_required() <NEW_LINE> def map_view_split(request): <NEW_LINE> <INDENT> toggledem = ToggleSwitch(display_text='Styled Toggle', name='toggledem', on_label='Yes', off_label='No', on_style='success', off_style='danger', initial=True, size='large', ) <NEW_LINE> toggle_switch_mun = ToggleSwitch(display_text='Styled To... | Controller for the app home page. | 625941da32920d7e50b28497 |
def get_exam_attempt_by_code(self, attempt_code): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> exam_attempt_obj = self.get(attempt_code=attempt_code) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> exam_attempt_obj = None <NEW_LINE> <DEDENT> return exam_attempt_obj | Returns the Student Exam Attempt object if found
else Returns None. | 625941da2ae34c7f2600d3f5 |
def dictfetchall(self): <NEW_LINE> <INDENT> desc = self.cursor.description <NEW_LINE> return [ dict(zip([col[0] for col in desc], row)) for row in self.cursor.fetchall() ] | Returns all rows from a cursor as a dict | 625941daaad79263cf390d09 |
def _update_from_compute_node(self, compute): <NEW_LINE> <INDENT> if 'free_disk_gb' not in compute or compute.free_disk_gb is None: <NEW_LINE> <INDENT> LOG.debug('Ignoring compute node %s as its usage has not been ' 'updated yet.', compute.uuid) <NEW_LINE> return <NEW_LINE> <DEDENT> if (self.updated and compute.updated... | Update information about a host from a ComputeNode object. | 625941da566aa707497f482a |
def requirements(filename='requirements.txt'): <NEW_LINE> <INDENT> pathname = os.path.join(os.path.dirname(__file__), filename) <NEW_LINE> with io.open(pathname, 'r') as f: <NEW_LINE> <INDENT> return [line.strip() for line in f if line.strip() and line[0] != '#'] | Read the requirements file | 625941da5fcc89381b1e1986 |
def build_blimp(self, tag): <NEW_LINE> <INDENT> boards = self.common_boards() <NEW_LINE> self.build_vehicle(tag, "Blimp", boards, "Blimp", "blimp") | build Blimp binaries | 625941da004d5f362079a5f7 |
def start(self): <NEW_LINE> <INDENT> self.pm.start() | Start the process manager within this session. | 625941da8c3a873295158682 |
def drect(n,N): <NEW_LINE> <INDENT> x = np.zeros(len(n)) <NEW_LINE> for k,nn in enumerate(n): <NEW_LINE> <INDENT> if nn >= 0 and nn < N: <NEW_LINE> <INDENT> x[k] = 1.0 <NEW_LINE> <DEDENT> <DEDENT> return x | Discrete rectangle function of duration N samples.
The signal is active on the interval 0 <= n <= N-1. Also known
as the rectangular window function, which is available in
scipy.signal.
Parameters
----------
n : ndarray of the time axis
N : the pulse duration
Returns
-------
x : ndarray of the signal
Notes
-----
T... | 625941da8e7ae83300e4b292 |
def clip_line_poly(shp, clip_obj): <NEW_LINE> <INDENT> poly = clip_obj.geometry.unary_union <NEW_LINE> spatial_index = shp.sindex <NEW_LINE> bbox = poly.bounds <NEW_LINE> sidx = list(spatial_index.intersection(bbox)) <NEW_LINE> shp_sub = shp.iloc[sidx] <NEW_LINE> clipped = shp_sub.copy() <NEW_LINE> clipped["geometry"] ... | A function to clip line and polygon data using geopandas.
Takes an input GeoDataFrame that is used as the clipped data, and a second
GeoDataFrame that is used as the clipping object or reference area.
A spatial index is created around the shp input and is then intersected
with the bounding box of the clip_obj.
Data ... | 625941da91af0d3eaac9bce0 |
def _force_update(self, root, options): <NEW_LINE> <INDENT> cleaned_results = self._clean(root, options) <NEW_LINE> cleaned_doc = cleaned_results.document.as_element() <NEW_LINE> remapped = cleaned_results.remapped_ids <NEW_LINE> removed = cleaned_results.removed <NEW_LINE> updated = self._update(cleaned_doc, options) ... | Removes untranslatable fields from the `root` document and calls
``self._update(...)``.
Returns:
An instance of ``ramrod.UpdateResults`` for the updated document. | 625941da23e79379d52ee826 |
@pytest.mark.manual <NEW_LINE> @pytest.mark.tier(2) <NEW_LINE> def test_auto_placement_provision_to_dvswitch_vlan_vmware(): <NEW_LINE> <INDENT> pass | Bugzilla:
1467399
Description of problem: issue appeared after 1458363
Auto_placement provision into DVS vlan fails with Error "Destination
placement_ds_name not provided]" if provider Network with the same
name exists
Version-Release number of selected component (if applicable):5.8.1
Virtualcenter: 6.5
How reprod... | 625941da5510c4643540f6a3 |
def verify(self, request, **kwargs): <NEW_LINE> <INDENT> logger.debug("verify(%s)" % request) <NEW_LINE> if isinstance(request, basestring): <NEW_LINE> <INDENT> _dict = parse_qs(request) <NEW_LINE> <DEDENT> elif isinstance(request, dict): <NEW_LINE> <INDENT> _dict = request <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Verifies that the given username and password was correct
:param request: Either the query part of a URL a urlencoded
body of a HTTP message or a parse such.
:param kwargs: Catch whatever else is sent.
:return: redirect back to where ever the base applications
wants the user after authentication. | 625941da377c676e9127246d |
def _indent(text, margin, newline='\n', key=bool): <NEW_LINE> <INDENT> indented_lines = [(margin + line if key(line) else line) for line in text.splitlines()] <NEW_LINE> return newline.join(indented_lines) | based on boltons.strutils.indent | 625941da24f1403a92600e29 |
def isaddindex(self, kdesc): <NEW_LINE> <INDENT> if self._isfd_ is None: raise IsamNotOpen <NEW_LINE> if not isinstance(kdesc, keydesc): raise ValueError('Must be an instance of keydesc') <NEW_LINE> self._chkerror(lib.isaddindex(self._isfd_, kdesc.value), 'isaddindex') | Add an index to an open ISAM table | 625941daac7a0e7691ed438d |
def DeviceRank(self, **kwargs): <NEW_LINE> <INDENT> return self.api_request(self._get_method_fullname("DeviceRank"), kwargs) | The rank of this device in its virtual brotherhood
**Inputs**
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` True
| ``default:`` None
:param DeviceID: An internal NetMRI identifier for the device.
:type DeviceID: Integer
**Outputs**
| ``api version min:`` None
| ``api version max:`... | 625941da6e29344779a628d5 |
@util.once <NEW_LINE> def copy_openal(): <NEW_LINE> <INDENT> gamedir = util.get_game_install_path() <NEW_LINE> shutil.copy(os.path.join(gamedir, 'OpenAL32.dll'), os.path.join(gamedir, 'jre/bin')) <NEW_LINE> shutil.copy(os.path.join(gamedir, 'OpenAL64.dll'), os.path.join(gamedir, 'jre/bin')) | Copy OpenAL*.dll to the java dir to avoid the audio
being sent to the wrong audio card | 625941da44b2445a33932359 |
def stack_the_deck(self): <NEW_LINE> <INDENT> stacked_deck = [] <NEW_LINE> suits = itertools.cycle("CHSD") <NEW_LINE> ranks = itertools.cycle( ["8", "K", "3", "T", "2", "7", "9", "5", "Q", "4", "A", "6", "J"] ) <NEW_LINE> for card in range(52): <NEW_LINE> <INDENT> stacked_deck.append(str(next(ranks)) + str(next(suits))... | BONUS! A card pseudo-memorized deck setup. "Eight Kings
threatened to save 95 Queens for one sick Knave." Stacking
the deck always builds an entire deck! (Reference:
https://sistebbins.com/eight-kings-card-stack.html)
DEMONSTRATES: itertools.cycle, list.append. | 625941da8e71fb1e9831da6d |
def _csv_dict_writer(file_or_path, ordered_columns: _collections.Sequence, data: _collections.Sequence): <NEW_LINE> <INDENT> def write_data(out_file): <NEW_LINE> <INDENT> writer = _csv.DictWriter( f=out_file, fieldnames=ordered_columns, dialect='excel') <NEW_LINE> writer.writeheader() <NEW_LINE> for row in data: <NEW_L... | Write a CSV file using `csv.DictWriter`.
:param file_or_path: Either a file path (in this case the CSV data is written to a file at this
location) or a file object (in this case the CSV data is written to its ``.write()``
function).
:param ordered_columns: A `Sequence` of column names (atoms). The columns are
... | 625941da5fc7496912cc3c43 |
def _seg_text(self, line_json): <NEW_LINE> <INDENT> fact = line_json.get("fact") <NEW_LINE> sen_list = splitSentence(fact, object_end=True) <NEW_LINE> facts = [] <NEW_LINE> for sen in sen_list: <NEW_LINE> <INDENT> fact_jiebaed = jieba.cut(sen) <NEW_LINE> fact_jiebaed_refined = refine_text(fact_jiebaed, self._stopwords)... | :param line_json:
:param taks:
:return: | 625941da5e10d32532c5f1eb |
def retrieve(self, request, *args, **kwargs): <NEW_LINE> <INDENT> logger.debug( f"{self.__class__.__name__}.{_getframe().f_code.co_name} " f"Retrieving user: {self.lookup_field}={kwargs[self.lookup_field]}" ) <NEW_LINE> return super().retrieve(request, *args, **kwargs) | overriding to enable logging | 625941da236d856c2ad44aa2 |
def sasimport(modname): <NEW_LINE> <INDENT> if not modname.startswith('sas.'): <NEW_LINE> <INDENT> emsg = 'Module name must start with "sas."' <NEW_LINE> raise ValueError(emsg) <NEW_LINE> <DEDENT> mobj = None <NEW_LINE> try: <NEW_LINE> <INDENT> exec('import %s as mobj' % modname) <NEW_LINE> <DEDENT> except ImportError:... | Import specified module from the SasView sas package.
modname -- absolute module name contained in the sas package.
When specified import does not work directly, try older API-s and raise
DeprecationWarning. Raise ImportError if nothing works. | 625941da3346ee7daa2b3032 |
def closeFiles( self ): <NEW_LINE> <INDENT> for f in self.files: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass | **Public Method**
This method attempts to close any files that may have been opened.
Catches and passes all exceptions.
:return: n/a: | 625941da8a349b6b435e8438 |
def write(self, filename=None): <NEW_LINE> <INDENT> if filename: <NEW_LINE> <INDENT> self.filen = filename <NEW_LINE> <DEDENT> if self.intab != None: <NEW_LINE> <INDENT> self.intab = self.render() <NEW_LINE> if not self.filen: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> if self.filen: <NEW_LINE> <INDENT> fi... | Write the crontab to the system. Saves all information. | 625941da046cf37aa974d00b |
def gt_aug(self, input_img_gt): <NEW_LINE> <INDENT> gt_nparray = input_img_gt['gt'] <NEW_LINE> img_nparray = input_img_gt['img'] <NEW_LINE> return img_nparray.shape[0] - gt_nparray - 1 | Note this function assumes the img_nparray has the shape: row x column and the surface position starts from 0.
The gt needs to do the operation: row_nb - surface position -1. | 625941dad18da76e2353279e |
def set(self, field, val): <NEW_LINE> <INDENT> raise RuntimeError("must override base method 'set'!") | set a value in a debugfs field | 625941daadb09d7d5db6ca53 |
def test_json_web_token_rs512(self): <NEW_LINE> <INDENT> token_contents = self.common_test_json_web_token('RS512') <NEW_LINE> self.assertEqual( sorted(token_contents.keys()), sorted(['exp', 'nbf', 'iss', 'aud', 'iat', 'user_id'])) | Execute the JSON Web Token test using RS512 algorithm | 625941da66656f66f7cbc472 |
def check_filename_tsp(filename: str) -> bool: <NEW_LINE> <INDENT> print(filename) <NEW_LINE> if filename.endswith(".tsp"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Check if the file provided is a valid TSP file
...ends with .tsp | 625941da8c0ade5d55d3ec82 |
def transcribe(config): <NEW_LINE> <INDENT> long_mode = True <NEW_LINE> if 'audio_data' not in config: <NEW_LINE> <INDENT> raise KeyError("`audio_data` not specified for transcription operation.") <NEW_LINE> <DEDENT> if 'timeout' not in config: <NEW_LINE> <INDENT> raise KeyError("`timeout` not specified for transcripti... | Automatically handles the interaction with Google Speech-to-text in order to
automagically transcribe some audio data.
GCloud requires a different mechanism if the audio file is longer than 60 seconds,
we can save a few steps and have the operation complete quicker if it is less than
that specified duration though.... | 625941da44b2445a3393235a |
@array_function_dispatch(_unary_dispatcher) <NEW_LINE> def arccos(x): <NEW_LINE> <INDENT> x = _fix_real_abs_gt_1(x) <NEW_LINE> return nx.arccos(x) | Compute the inverse cosine of x.
Return the "principal value" (for a description of this, see
`numpy.arccos`) of the inverse cosine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[0, \pi]`. Otherwise, the complex principle value is returned.
Parameters
----------
x ... | 625941dac432627299f04f0d |
def rjust(self, width: int, fillchar: str = " ") -> SeriesOrIndex: <NEW_LINE> <INDENT> if not isinstance(fillchar, str): <NEW_LINE> <INDENT> msg = ( f"fillchar must be a character, not {type(fillchar).__name__}" ) <NEW_LINE> raise TypeError(msg) <NEW_LINE> <DEDENT> if len(fillchar) != 1: <NEW_LINE> <INDENT> raise TypeE... | Filling left side of strings in the Series/Index with an additional
character. Equivalent to `str.rjust()
<https://docs.python.org/3/library/stdtypes.html#str.rjust>`_.
Parameters
----------
width : int
Minimum width of resulting string;
additional characters will be filled
with fillchar.
fillchar : str, ... | 625941da1f5feb6acb0c4e12 |
def wait_completion(self): <NEW_LINE> <INDENT> self.tasks.join() <NEW_LINE> self.remove_finished_threads() | Wait for completion of all the tasks in the queue | 625941da627d3e7fe0d69116 |
def get_pic_size(self): <NEW_LINE> <INDENT> return (self.origin + self.pitch * (self.model.picSize + Point(1.0,1.0))) | Return the size of ASCII-art picture of the pipeline scaled by
the blob pitch | 625941dac4546d3d9de72cfb |
def _get_tau(tau_model, TAU, imt, mag): <NEW_LINE> <INDENT> return TAU_EXECUTION[tau_model](imt, mag, TAU) | Returns the inter-event standard deviation (tau) | 625941da3eb6a72ae02ec7a9 |
def get_shape_classes(self, name): <NEW_LINE> <INDENT> if isinstance(name, ir.Var): <NEW_LINE> <INDENT> name = name.name <NEW_LINE> <DEDENT> typ = self.typemap[name] if name in self.typemap else None <NEW_LINE> if not (isinstance(typ, types.BaseTuple) or isinstance(typ, types.ArrayCompatible)): <NEW_LINE> <INDENT> retu... | Instead of the shape tuple, return tuple of int, where
each int is the corresponding class index of the size object.
Unknown shapes are given class index -1. Return empty tuple
if the input name is a scalar variable. | 625941dae76e3b2f99f3aacd |
def hough_transform(): <NEW_LINE> <INDENT> pass | -Check hough_transform.py to make sure it gives expected hough and resampled
-Check that it yields the correct slope
TBW
:return: | 625941da1d351010ab855de1 |
def calcular_validez(self): <NEW_LINE> <INDENT> formato_fecha = "%Y-%m-%d" <NEW_LINE> print('Fecha Recibo: '+self.fecha) <NEW_LINE> print('Validez: '+self.validez) <NEW_LINE> fecha = datetime.strptime(self.fecha, formato_fecha).date() <NEW_LINE> fecha_rec = fecha + timedelta(days = int(self.validez)) <NEW_LINE> print("... | Verifica si el recibo aun es valido | 625941da71ff763f4b549955 |
def test_review_reject_removes_review_task(self): <NEW_LINE> <INDENT> video = self.data_utils.create_video() <NEW_LINE> tv = TeamVideoFactory(team=self.team, added_by=self.owner, video=video) <NEW_LINE> data = {'language_code': 'en', 'video': video.pk, 'primary_audio_language_code': 'en', 'draft': open('apps/webdriver_... | Review task is removed when transcription rejected by reviewer | 625941da4428ac0f6e5baab9 |
def p_units_iter(self, p): <NEW_LINE> <INDENT> p[0] = self._iter(p) | units : units unit | 625941da7b180e01f3dc4abe |
def FixNANtoInt(value): <NEW_LINE> <INDENT> if np.isnan(value): return gglobs.NAN <NEW_LINE> else: return round(value, 1) | if value is NAN, it returns NAN, otherwise a value rounded to integer | 625941daa17c0f6771cbe315 |
def _stream_data(self, response, iterator, chunked=False, calculate_hash=True, chunk_size=None): <NEW_LINE> <INDENT> chunk_size = chunk_size or CHUNK_SIZE <NEW_LINE> data_hash = None <NEW_LINE> if calculate_hash: <NEW_LINE> <INDENT> data_hash = hashlib.md5() <NEW_LINE> <DEDENT> generator = utils.read_in_chunks(iterator... | Stream a data over an http connection.
@type response: C{RawResponse}
@param response: RawResponse object.
@type iterator: C{}
@param response: An object which implements an iterator interface
or a File like object with read method.
@type chunk_size: C{int}
@param chunk_size: Optional chunk size (de... | 625941da097d151d1a22311d |
def extend(self, pool_or_size=10): <NEW_LINE> <INDENT> if type(pool_or_size) == ConnectionPool: <NEW_LINE> <INDENT> assert isinstance(pool_or_size, ConnectionPool) <NEW_LINE> while pool_or_size.size() > 0: <NEW_LINE> <INDENT> self._queue.put(pool_or_size.get()) <NEW_LINE> <DEDENT> <DEDENT> elif type(pool_or_size) == in... | 扩展连接池 | 625941dab830903b967e9bce |
def createZMQSocket(self, sock_type): <NEW_LINE> <INDENT> sock = self.ZMQcontext.socket(sock_type) <NEW_LINE> sock.setsockopt(zmq.LINGER, LINGER_TIME) <NEW_LINE> sock.setsockopt(zmq.IPV4ONLY, 0) <NEW_LINE> sock.setsockopt(zmq.SNDHWM, 0) <NEW_LINE> sock.setsockopt(zmq.RCVHWM, 0) <NEW_LINE> try: <NEW_LINE> <INDENT> sock.... | Create a socket of the given sock_type and deactivate message dropping | 625941da29b78933be1e596d |
def _cur_tok_precedence(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._precedence_map[self.cur_tok.value] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return -1 | Get the operator precedence of the current token. | 625941da91f36d47f21ac7ba |
def _get_item_cache(self, item: Hashable) -> Series: <NEW_LINE> <INDENT> cache = self._item_cache <NEW_LINE> res = cache.get(item) <NEW_LINE> if res is None: <NEW_LINE> <INDENT> loc = self.columns.get_loc(item) <NEW_LINE> values = self._mgr.iget(loc) <NEW_LINE> res = self._box_col_values(values, loc).__finalize__(self)... | Return the cached item, item represents a label indexer. | 625941da656771135c3ebb37 |
def id2num(s): <NEW_LINE> <INDENT> n = 0 <NEW_LINE> for ch in s.upper(): <NEW_LINE> <INDENT> n = n * 26 + (ord(ch) - 65) + 1 <NEW_LINE> <DEDENT> return n - 1 | spreadsheet column name to number
ref: http://stackoverflow.com/questions/7261936
:param s: str -- spreadsheet column alpha ID (i.e. A, B, ... AA, AB,...)
:returns: int -- spreadsheet column number (zero-based index)
>>> id2num('A')
0
>>> id2num('B')
1
>>> id2num('XFD')
16383
>>>
| 625941da8e7ae83300e4b293 |
def GetRMSChange(self): <NEW_LINE> <INDENT> return _itkFiniteDifferenceImageFilterPython.itkFiniteDifferenceImageFilterID3ID3_GetRMSChange(self) | GetRMSChange(self) -> double | 625941da63b5f9789fde73ab |
def borrar_arista(self, desde, hasta): <NEW_LINE> <INDENT> if((desde or hasta) not in self.vetices.keys()): <NEW_LINE> <INDENT> raise KeyError("Alguno de los nombres ingresados no forma parte del grafo") <NEW_LINE> <DEDENT> if(hasta not in self.vertices[desde].keys()): <NEW_LINE> <INDENT> raise ValueError("La arista in... | Borra una arista que conecta los vertices indicados. Parametros:
- desde y hasta: nombres de vertices dentro del grafo. Si alguno de estos no existe dentro del grafo, lanzara KeyError.
En caso de no existir la arista, se lanzara ValueError.
Si el grafo no es dirigido, se borrará la arista inversa. | 625941da67a9b606de4a817e |
def _calculate_constants(self, spatial_distribution): <NEW_LINE> <INDENT> if spatial_distribution == 'gaussian': <NEW_LINE> <INDENT> self.two_sigma2 = 2. * self._params['sigma']**2 <NEW_LINE> <DEDENT> elif spatial_distribution == 'gamma': <NEW_LINE> <INDENT> self.kappa_m_1 = self._params['kappa'] - 1 <NEW_LINE> self.ga... | Calculate constant variables used when calculating distributions and probability density functions
Variables that can be pre-calculated are calculated here to make the calculation of distributions
and probability density functions more efficient. | 625941da21bff66bcd684c15 |
def exponential(self,value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> try: <NEW_LINE> <INDENT> for k in (1,100000000): <NEW_LINE> <INDENT> exp = ((1+1.0/k)**k)**value <NEW_LINE> yield exp <NEW_LINE> <DEDENT> if self.value == 1: <NEW_LINE> <INDENT> print("e = %s " % repr(exp)) <NEW_LINE> <DEDENT> else: <NEW_LIN... | Compute exponential e and exp(value) for a given value | 625941da7c178a314d6ef729 |
def extract_msg_from_line(line): <NEW_LINE> <INDENT> myline = line.split() <NEW_LINE> if len(myline[3]) == 2: <NEW_LINE> <INDENT> return (binascii.unhexlify(myline[3].encode()), "tx") <NEW_LINE> <DEDENT> elif (len(myline[5]) == 2): <NEW_LINE> <INDENT> return (binascii.unhexlify(myline[5].encode()), "rx") <NEW_LINE> <DE... | Returns the transmitted char logged by a line, and whether it was
a Tx or an Rx. Returned char is in bytes format
>>> extract_msg_from_line("78 08/21/13 17:10:37.007.295 2c , 1 0 0 0 0 0")
(2c, tx)
>>> extract_msg_from_line("83 08/21/13 17:10:37.071.151 0 0 0d < CR> 0 0 0 0")
(0d, rx) | 625941da21bff66bcd684c16 |
def linear_regression_single_vars(self, df_y, df_x, y_vars, x_vars, use_stats_models = True): <NEW_LINE> <INDENT> stats = [] <NEW_LINE> for i in range(0, len(y_vars)): <NEW_LINE> <INDENT> y = df_y[y_vars[i]] <NEW_LINE> x = df_x[x_vars[i]] <NEW_LINE> try: <NEW_LINE> <INDENT> if pandas.__version__ < '0.17' or not(use_sta... | Do a linear regression of a number of y and x variable pairs in different dataframes, report back the coefficients.
Parameters
----------
df_y : DataFrame
y variables to regress
df_x : DataFrame
x variables to regress
y_vars : str (list)
Which y variables should we regress
x_vars : str (list)
Which x v... | 625941da796e427e537b088d |
def upload_file(fapi, file_name, conf): <NEW_LINE> <INDENT> if not conf.has_key('file-type'): <NEW_LINE> <INDENT> raise SmarterlingError("%s doesn't have a file-type" % file_name) <NEW_LINE> <DEDENT> print("Uploading %s to smartling" % file_name) <NEW_LINE> data = UploadData( os.path.dirname(file_name)+os.sep, os.path.... | Uploads a file to smartling
| 625941da379a373c97cfae0c |
def get_person(self, _id): <NEW_LINE> <INDENT> raise NotImplementedError() | Get a person object from an ID.
:param _id: ID of person
:type _id: str
:rtype: :class:`Person` | 625941da30c21e258bdfa764 |
def dbsize(self): <NEW_LINE> <INDENT> self.connect() <NEW_LINE> self.sock.sendall(comm.constructMessage("DBSIZE")) <NEW_LINE> return self.handleResponse() | Returns the number of keys in the currently selected database
@return: Integer reply | 625941da8e05c05ec3eea63c |
def set_permissions(self, key, permissions): <NEW_LINE> <INDENT> for store in self.stores: <NEW_LINE> <INDENT> if store.exists(key): <NEW_LINE> <INDENT> store.set_permissions(key, permissions) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> raise KeyError(key) | Set the permissions on a key the user owns
Parameters
----------
key : str
The key for the resource which you want to know the permissions.
permissions : dict of str: set of str
A dictionary whose keys are the permissions and values are sets of
tags which have that permission. There must be an 'owned'
... | 625941da99cbb53fe6792eac |
def test_list_utils_groupby_with_delimiter_single_element(): <NEW_LINE> <INDENT> elements = ['1'] <NEW_LINE> delimiter = '1' <NEW_LINE> expected = [] <NEW_LINE> actual = groupby_with_delimiter(elements, delimiter) <NEW_LINE> assert expected == actual | Test that the an empty list is returned back. | 625941da92d797404e304451 |
def run_server(cmd: List[str], workdir: str, envs=None): <NEW_LINE> <INDENT> if os.name == "nt": <NEW_LINE> <INDENT> startupinfo = subprocess.STARTUPINFO() <NEW_LINE> startupinfo.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> startupinfo = None <NEW_LINE> <... | run server with specific environment
windows command:
~\miniconda3\Script\activate envqt && python server | 625941da5166f23b2e1a541f |
def shouldBeAssociated(self, mTemplate): <NEW_LINE> <INDENT> mId = mTemplate.getAnnotatedId() <NEW_LINE> vId = self.token.getAnnotationAttribute(self.type, mTemplate.type) <NEW_LINE> if len(mId) > 0 and len(vId) > 0 and vId == mId: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Fal... | return true if this quantity template should be associated with
a given mention template. | 625941dacc0a2c11143dd157 |
def test_lookup_called_by_init(self, ): <NEW_LINE> <INDENT> patcher = patch('drogulus.dht.node.NodeLookup._lookup') <NEW_LINE> mock_lookup = patcher.start() <NEW_LINE> NodeLookup(self.key, FindNode, self.node, self.timeout) <NEW_LINE> self.assertEqual(1, mock_lookup.call_count) <NEW_LINE> patcher.stop() | Ensure that the __init__ method kicks off the lookup by calling the
NodeLookup's _lookup method. | 625941dabde94217f36830b4 |
def check_paths(data): <NEW_LINE> <INDENT> new_app_path = [] <NEW_LINE> for app_path in data["app_path"]: <NEW_LINE> <INDENT> app_path = replace_vars_path(app_path, data["exec_path_script"]) <NEW_LINE> if path.isdir(app_path) or path.isfile(app_path): <NEW_LINE> <INDENT> new_app_path.append(app_path) <NEW_LINE> <DEDENT... | Check if the app_path exists to detect if the application is installed
Also check if the icons path exists, and force creating needed folders.
See the json key "force_create_folder" | 625941da7cff6e4e81117c4b |
def get_latest_dl_link(): <NEW_LINE> <INDENT> r = requests.get(gecko_url) <NEW_LINE> logger.info(f"Requested from {gecko_url}.") <NEW_LINE> dl_base_url = r.url.replace("tag", "download") <NEW_LINE> logger.info(f"Download base url is {dl_base_url}") <NEW_LINE> breakdown = r.url.strip("https://").split("/") <NEW_LINE> lo... | By requesting latest release url, the current release url will be returned.
:return: Download link of the latest release. | 625941dadd821e528d63b46d |
def mult(a, b): <NEW_LINE> <INDENT> return a * b | Multiply a by b | 625941da30bbd722463cc08e |
def confirm_instruction(self): <NEW_LINE> <INDENT> user_confirmation = DIALOG.yesno(self.lang(32116), '[CR]'.join([self.lang(32117), self.lang(32118), self.lang(32119)])) <NEW_LINE> return user_confirmation | Asks the user to confirm that they wish to apply the instruction.
Returns TRUE, only if user clicks Yes. | 625941dad8ef3951e3243804 |
def kill(self, *args): <NEW_LINE> <INDENT> self.logger.info("Shutting down process monitor.") <NEW_LINE> self.stopped = True <NEW_LINE> self.killed = True <NEW_LINE> for bot in self.bots: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bot.stop() <NEW_LINE> bot.join() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <... | Shuts down the monitor and all bots. | 625941da8da39b475bd6523c |
def listAlarms(self, *args): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> type, types = 'id', ['id','names','aid'] <NEW_LINE> if len(args)>0 and args[0] in types: type = args[0] <NEW_LINE> for alert in self.__alerts: <NEW_LINE> <INDENT> if type=='names': <NEW_LINE> <INDENT> ret[alert.progname] = alert.progpath <NEW_LINE> <D... | Lists all the alarms with their ID or name. | 625941dabd1bec0571d908f5 |
def load_database(filename): <NEW_LINE> <INDENT> print("[database] Loading database from '" + filename + "'") <NEW_LINE> with open(filename) as f: <NEW_LINE> <INDENT> database = json.load(f) <NEW_LINE> <DEDENT> return decompress_database(database) | Loads a database from disk | 625941dab5575c28eb68e2c8 |
def instantiate_this(class_path, init_args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cls = import_this(class_path) <NEW_LINE> if init_args is None: <NEW_LINE> <INDENT> return cls() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cls(*init_args) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> log.exce... | Instantiates an object of the class in class_path with the given initializantion arguments.
Parameters
----------
class_path: str
String to the path of the class.
init_args: dict
Dictionary of the names and values of the initialization arguments to the class
Return
------
Instantiated object | 625941dabe383301e01b5747 |
def extractInfo(inps): <NEW_LINE> <INDENT> from isceobj.Planet.Planet import Planet <NEW_LINE> from isceobj.Util.geo.ellipsoid import Ellipsoid <NEW_LINE> planet = Planet(pname='Earth') <NEW_LINE> elp = Ellipsoid(planet.ellipsoid.a, planet.ellipsoid.e2, 'WGS84') <NEW_LINE> hgt = 0 <NEW_LINE> lat = 0 <NEW_LINE> hdg = 0 ... | Extract required information | 625941da07f4c71912b1174a |
def remove_neutron_ports(task, params): <NEW_LINE> <INDENT> client = get_client() <NEW_LINE> node_uuid = task.node.uuid <NEW_LINE> try: <NEW_LINE> <INDENT> response = client.list_ports(**params) <NEW_LINE> <DEDENT> except neutron_exceptions.NeutronClientException as e: <NEW_LINE> <INDENT> msg = (_('Could not get given ... | Deletes the neutron ports matched by params.
:param task: a TaskManager instance.
:param params: Dict of params to filter ports.
:raises: NetworkError | 625941daa8ecb033257d3392 |
def language_body_size(self): <NEW_LINE> <INDENT> pass | If the language attribute is not empty, then the size of the body and language arrays must be the same.
.. ocl::
language->notEmpty() implies (_'body'->size() = language->size()) | 625941dad7e4931a7ee9e1e4 |
def _generateLogs(self, num): <NEW_LINE> <INDENT> with open(os.path.join(self.tempdir, 'cbuildbot.log'), 'w') as f: <NEW_LINE> <INDENT> f.write(str(num + 1)) <NEW_LINE> <DEDENT> for i in range(1, num + 1): <NEW_LINE> <INDENT> with open(os.path.join(self.tempdir, 'cbuildbot.log.' + str(i)), 'w') as f: <NEW_LINE> <INDENT... | Generates cbuildbot.log and num backups. | 625941dad268445f265b5135 |
def is_close_all(self): <NEW_LINE> <INDENT> return self.type == CLOSE_ALL | Checks if instance of frame is close_all type
:return: bool | 625941da4527f215b584c71a |
def _set_updates_thread(self, running): <NEW_LINE> <INDENT> if running == self._updates_thread_running.is_set(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._logger.info('Changing updates thread running status to %s', running) <NEW_LINE> if running: <NEW_LINE> <INDENT> self._updates_thread_running.set() <NEW_LI... | Sets the updates thread status (running or not) | 625941da4527f215b584c71b |
def calculate_annual_salary(employee: EmployeeDto): <NEW_LINE> <INDENT> return (EmployeeContractFactory(employee).get_contract()).get_annual_salary() | Business rule that calculates the annual salary for a employee.
Args:
employee:
Returns: annual salary | 625941da4428ac0f6e5baaba |
def test_display_all_account(self): <NEW_LINE> <INDENT> self.assertEqual(Account.display_accounts(),Account.account_list) | method that returns a list of all account saved | 625941dac432627299f04f0e |
def update(self, instance, validated_data): <NEW_LINE> <INDENT> instance.nom = validated_data.get('nom', instance.nom) <NEW_LINE> instance.url_map = validated_data.get('url_map', instance.url_map) <NEW_LINE> instance.telephone = validated_data.get('telephone', instance.telephone) <NEW_LINE> instance.language = validate... | Update and return an existing `Snippet` instance, given the validated data. | 625941da099cdd3c635f0f20 |
def test_account_integration_router_get_monitored_ip_stats(self): <NEW_LINE> <INDENT> pass | Test case for account_integration_router_get_monitored_ip_stats
| 625941da8c0ade5d55d3ec83 |
def reverse(vector, n): <NEW_LINE> <INDENT> list1 = [] <NEW_LINE> vector_length = len(vector) <NEW_LINE> difference = vector_length-n <NEW_LINE> new_vector = vector[difference:] <NEW_LINE> list1.append(new_vector) <NEW_LINE> left_vector = vector[:difference] <NEW_LINE> if len(left_vector) >= n: <NEW_LINE> <INDENT> chun... | function to reverse the input vector of size n
| 625941daf8510a7c17cf99c4 |
def handle_user_config_changes(self): <NEW_LINE> <INDENT> changelist = None <NEW_LINE> if changelist: <NEW_LINE> <INDENT> logger.warning("Wanted to reconfigure acs device %s due to user config changes, disabled waiting for TA approval. Changed items: %s" % (self, changelist)) <NEW_LINE> pass | Check self.acs_parameters for changes to settings configurable by the user | 625941da442bda511e8be6db |
def _get_file_info(self): <NEW_LINE> <INDENT> file_name, delim = None, None <NEW_LINE> if self.set_name == 'volk': <NEW_LINE> <INDENT> file_name, delim = 'volkova.csv', ',' <NEW_LINE> <DEDENT> elif self.set_name == 'mult': <NEW_LINE> <INDENT> file_name, delim = 'corpus.tsv', '\t' <NEW_LINE> <DEDENT> elif self.set_name ... | Return file directory and delimiter by set identifier. | 625941da8c3a873295158683 |
def clear(self) -> None: <NEW_LINE> <INDENT> self._rows.clear() <NEW_LINE> self._volatile_index = 0 | Clear the table of all rows. | 625941da15fb5d323cde0dd9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.