code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_get_order_by_default(self): <NEW_LINE> <INDENT> request = Mock(GET=QueryDict('')) <NEW_LINE> sort_headers = SortHeaders(request, self.header_list) <NEW_LINE> eq_(sort_headers.get_order_by(), 'field_1') | Default order by is first field ascending. | 625941e78da39b475bd653df |
def testPrice(self): <NEW_LINE> <INDENT> pass | Test Price | 625941e7c432627299f050af |
def target_train(self): <NEW_LINE> <INDENT> weights = self.model.get_weights() <NEW_LINE> target_weights = self.target_model.get_weights() <NEW_LINE> for i in range(len(target_weights)): <NEW_LINE> <INDENT> target_weights[i] = weights[i] * self.tau + target_weights[i] * (1 - self.tau) <NEW_LINE> <DEDENT> self.target_mo... | Work in progress | 625941e7b57a9660fec33cf0 |
def test_remove(self): <NEW_LINE> <INDENT> print("test scenario 1: START") <NEW_LINE> id_to_remove = 2 <NEW_LINE> self.todo_list.remove(id_to_remove) <NEW_LINE> err = "id 2 should not exist" <NEW_LINE> self.assertNotIn(id_to_remove, self.todo_list.id_to_todo, err) <NEW_LINE> err = "the length should only decrease by 1"... | to test remove method
Scenarios:
1. If I remove a todo, then there should be one less todos in the list
2. If I remove non existent todo, then it should return a KeyError and
there should not be a change in the list | 625941e7e1aae11d1e74a121 |
@app.route('/sessions/<userid>/<filename>', methods=['GET', 'POST']) <NEW_LINE> def send_file(userid, filename): <NEW_LINE> <INDENT> uploads = os.path.join(sessions_root, userid) <NEW_LINE> return send_from_directory(uploads, filename) | Allow user to download the requested file. The download is possible only from
the user's session folder, i.e. 'sessions/<userid>' | 625941e7fb3f5b602dac3afd |
def add(self): <NEW_LINE> <INDENT> if not self.exists() and self._name is not None and self._type is not None: <NEW_LINE> <INDENT> if self._type in self.STYPES: <NEW_LINE> <INDENT> querystring = "type={}&name={}&scenetype={}".format( self._type_add_scene, self._name, self._type) <NEW_LINE> self._api.querystring = query... | Add scene/group to Domoticz
Add least type(SCENE or GROUP) and name are required | 625941e7aad79263cf390ead |
@pytest.mark.parametrize( "pre,post", compare_postupgrade('sync-plan', 'interval') ) <NEW_LINE> def test_positive_syncplans_by_interval(pre, post): <NEW_LINE> <INDENT> assert pre == post | Test all sync plans interval time is retained after upgrade
:id: 058eeba9-9a4d-44c5-a759-48c3199b70f0
:expectedresults: All sync plans interval time should be retained post
upgrade | 625941e7656771135c3ebcda |
@ndb.tasklet <NEW_LINE> def GetPlanetsSizeChartAsync(planets): <NEW_LINE> <INDENT> planets_by_size = collections.defaultdict(int) <NEW_LINE> for planet in planets: <NEW_LINE> <INDENT> if planet.radius < models.Earth.RADIUS: <NEW_LINE> <INDENT> planets_by_size['Smaller Than Earth Size'] += 1 <NEW_LINE> <DEDENT> if plane... | Gets planets by size chart data.
Args:
planets: models.ExoPlanet, the exo planets. | 625941e7379a373c97cfafac |
def testPuestosOcupadosVariosSolapamientos(self): <NEW_LINE> <INDENT> capacidad = 2 <NEW_LINE> horaIni = timeDesdeCadena("07:00") <NEW_LINE> horaFin = timeDesdeCadena("10:00") <NEW_LINE> puestosOcupados = [("07:00","08:00") , ("09:00","10:00"), ("7:59","09:01") ... | Prueba Malicia ( Caso interesante) | 625941e7a934411ee3751afa |
def __init__(self, jobs): <NEW_LINE> <INDENT> jobs = jobs if isinstance(jobs, list) else [jobs] <NEW_LINE> for j in jobs: <NEW_LINE> <INDENT> if not isinstance(j, QcTask): <NEW_LINE> <INDENT> raise ValueError("jobs must be a list QcInput object") <NEW_LINE> <DEDENT> self.jobs = jobs | Args:
jobs: The QChem jobs
(List of QcInput object) | 625941e78e7ae83300e4b434 |
def pc_output_buffers_full_avg(self, *args): <NEW_LINE> <INDENT> return _blocks_swig4.probe_signal_i_sptr_pc_output_buffers_full_avg(self, *args) | pc_output_buffers_full_avg(probe_signal_i_sptr self, int which) -> float
pc_output_buffers_full_avg(probe_signal_i_sptr self) -> pmt_vector_float | 625941e78a349b6b435e85d8 |
def updateMutexProposition(self): <NEW_LINE> <INDENT> currentLayerPropositions = self.propositionLayer.getPropositions() <NEW_LINE> currentLayerMutexActions = self.actionLayer.getMutexActions() <NEW_LINE> for p_i in currentLayerPropositions: <NEW_LINE> <INDENT> for p_j in currentLayerPropositions: <NEW_LINE> <INDENT> ... | updates the mutex propositions in the current proposition layer | 625941e715fb5d323cde0f7c |
def test_project_list_view(self): <NEW_LINE> <INDENT> expected = { 'status_code':200, 'template_used':'project/project_list.html', } <NEW_LINE> response = self.client.get(reverse('project-list')) <NEW_LINE> self.assert_(response.status_code == expected['status_code']) <NEW_LINE> self.assertTemplateUsed(response, expect... | Tests the project list view | 625941e77b25080760e398bc |
def handle_rx(self, packet, in_port): <NEW_LINE> <INDENT> if isinstance(packet, basics.HostDiscoveryPacket): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.table[packet.src] = in_port <NEW_LINE> if packet.dst in self.table: <NEW_LINE> <INDENT> self.send(packet, self.table[packet.dst], flood=False) <NEW_LINE> <DEDE... | Called when a packet is received.
You most certainly want to process packets here, learning where
they're from, and either forwarding them toward the destination
or flooding them. | 625941e7097d151d1a2232bd |
def calculate_avg_adjacency(self) -> np.ndarray: <NEW_LINE> <INDENT> avg_adj = np.zeros((self.graph.nodes, self.graph.nodes)) <NEW_LINE> connections = self.graph.connections <NEW_LINE> connections[connections == 0] = np.nan <NEW_LINE> for a in self.graph.adj_matrices: <NEW_LINE> <INDENT> avg_adj = np.nansum(np.dstack((... | Creates average adjacency matrix | 625941e730dc7b7665901dc8 |
@click.command() <NEW_LINE> @click.option('--host', help='gocd hostname without protocol eg gocd.tools.edx.org', required=True) <NEW_LINE> @click.option('--token', help='gocd auth token', required=True) <NEW_LINE> @click.option('--config_repo', help='config repo name to update', required=True) <NEW_LINE> @click.option(... | Trigger a config update | 625941e7bf627c535bc13635 |
def arpabet_to_ipa(arpabet_list): <NEW_LINE> <INDENT> arpabet_list = [phoeme.rstrip('012') for phoeme in arpabet_list] <NEW_LINE> IPA_list = [] <NEW_LINE> for index in range(len(arpabet_list)): <NEW_LINE> <INDENT> phoeme = arpabet_list[index] <NEW_LINE> if phoeme in r_colored and index < len(arpabet_list)-1 and arpa... | Converts a list of ARPABET phoemes into a list of IPA phoemes. Does not handle syllabe stresses | 625941e7a8ecb033257d3531 |
@cache.memoize('badge_thumbnail', make_key=make_key) <NEW_LINE> def generate_thumbnail_tag(badge, width=0, height=0): <NEW_LINE> <INDENT> size = (width and height) and (width, height) or get_default_thumbnailsize(badge) <NEW_LINE> img_template = """<img src="data:%s;base64,%s" width="%s" height="%s" />""" <NEW_L... | Returns string with the badge thumbnail img tag
The image is resized and converted to PNG. | 625941e73cc13d1c6d3c77de |
def remove_objects(request, model, queryset, redirect): <NEW_LINE> <INDENT> FormSet = modelformset_factory(model, fields=("removed_by",), extra=0, can_delete=True) <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> formset = FormSet(request.POST, request.FILES) <NEW_LINE> if 'cancel' in request.POST: <NEW_LINE... | Returns either a formset or a redirect for removing objects from a queryset
Sample usage:
dict = remove_objects(request, TournamentTeam, tournament_teams, reverse('tournament_teams', kwargs=tournament.get_url_kwargs()))
if dict['response']:
return dict['response']
formset = dict['formset'... | 625941e724f1403a92600fc8 |
def call_function(func_def, *inputs, **kwargs): <NEW_LINE> <INDENT> name = kwargs.pop("name", None) <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> raise ValueError("Unknown keyword arguments: %s" % kwargs.keys()) <NEW_LINE> <DEDENT> func_name = func_def.signature.name <NEW_LINE> with ops.op_scope(inputs, name, func_name) as... | Calls the function described by `func_def`.
This adds a `call` op to the default graph that calls the function described
by `func_def` with the tensors listed in `inputs` as arguments. It returns
the outputs of the call, which are one or more tensors.
`func_def` is a
[`FunctionDef`](
https://www.tensorflow.org/code/... | 625941e7d18da76e23532942 |
def __init__(self): <NEW_LINE> <INDENT> self.cards = [] <NEW_LINE> for suit in range(4): <NEW_LINE> <INDENT> for rank in range(1, 14): <NEW_LINE> <INDENT> card = Card(suit, rank) <NEW_LINE> self.cards.append(card) | Initialize a new deck. | 625941e776d4e153a657ef99 |
def get_base64(image): <NEW_LINE> <INDENT> image_bytes_stream = io.BytesIO() <NEW_LINE> image.save(image_bytes_stream, format='PNG') <NEW_LINE> image64 = base64.b64encode(image_bytes_stream.getvalue()).decode('utf-8') <NEW_LINE> image_bytes_stream.close() <NEW_LINE> return image64 | Gets the base64 representation of the PNG bytes.
:return: The base64 representation of the PNG bytes. | 625941e70fa83653e465741e |
def test_list_users(self): <NEW_LINE> <INDENT> resp = self.client.get(reverse("administration:user_list")) <NEW_LINE> self.assertContains(resp, "<td>admin@example.com</td>") | The user list is available to all users. | 625941e791f36d47f21ac95d |
def __init__(self, api_key, query, image_filters='', safe=False, custom_params=''): <NEW_LINE> <INDENT> PyBingSearch.__init__(self, api_key, query, self.IMAGE_QUERY_BASE + custom_params, safe=safe) <NEW_LINE> self.image_filters = image_filters | :param image_filters: Array of strings that filter the response the API sends based on size, aspect,
color, style, face or any combination thereof.
Valid values are:
- Size:Small, Size:Medium, Size:Large, Size:Width:[Width], Size:Height:[Height]
- Aspect:Square, Aspect:Wide, Aspect:Tall
- Color:Color, Color:Monochr... | 625941e71f5feb6acb0c4faf |
def create_check(self, name, *, descriptor=None): <NEW_LINE> <INDENT> pass | Create check
Parameters:
name (str): check name
descriptor (dict): check descriptor
Returns:
Check: check | 625941e7d58c6744b42580c4 |
def get_media_types(): <NEW_LINE> <INDENT> for media_type in mg_globals.app_config['media_types']: <NEW_LINE> <INDENT> yield media_type | Generator, yields the available media types | 625941e7435de62698dfe0b3 |
def join_lines(code_edit): <NEW_LINE> <INDENT> textCursor = code_edit.textCursor() <NEW_LINE> blocks = get_selected_blocks(code_edit, ignoreEmpty=False) <NEW_LINE> if len(blocks) > 1: <NEW_LINE> <INDENT> text = textCursor.selectedText() <NEW_LINE> text = ' '.join(ln.strip() for ln in text.splitlines()) <NEW_LINE> textC... | Joins current line(s) with next by deleting the
newline at the end of the current line(s). | 625941e73346ee7daa2b31d6 |
def enter_file_name(read_write): <NEW_LINE> <INDENT> file = "" <NEW_LINE> if read_write == "w": <NEW_LINE> <INDENT> file = input("Please type a file name to save bills data [.dat]: ") <NEW_LINE> <DEDENT> elif read_write == "r": <NEW_LINE> <INDENT> file = input("Please type a file name to read bills data [.dat]: ") <NEW... | Asks the user to input a .dat file name
:param read_write: (string) to show whether file is to read or write
:return: (string) of file name | 625941e701c39578d7e752a2 |
def gettsnbyvernacularlanguage(language, **kwargs): <NEW_LINE> <INDENT> out= Refactor(itis_base + 'getTsnByVernacularLanguage', payload={'language': language}, request='get').xml(**kwargs) <NEW_LINE> matches = ["commonName","language","tsn"] <NEW_LINE> return _itisdf(out, ns21, matches, _tolower(matches)) | Get tsn by vernacular language not the international language code (character)
Usage:
pytaxize.gettsnbyvernacularlanguage("french") | 625941e7b5575c28eb68e46a |
def test_am_replacer_invalidop(): <NEW_LINE> <INDENT> from ..automodapi import automodapi_replace <NEW_LINE> fakeapp = FakeApp() <NEW_LINE> automodapi_replace(am_replacer_invalidop_str, fakeapp) <NEW_LINE> expected_warnings = [('Found additional options invalid-option in ' 'automodapi.', None)] <NEW_LINE> assert fakeap... | Tests that a sphinx warning is produced with an invalid option. | 625941e7507cdc57c630714b |
def update_score(self, screen): <NEW_LINE> <INDENT> score = Assets.FONT.render("Score : %d" % self.score, True, TXT_COLOR) <NEW_LINE> screen.blit(score, POS_SCORE) | Pokazuje na ekranie gry aktualną ilość punktów. | 625941e7d268445f265b52d5 |
def prepare_depth_df(file_path): <NEW_LINE> <INDENT> concat_depth_uk = merge_depth_data(file_path) <NEW_LINE> concat_depth_yale = merge_depth_data(file_path, UK=False) <NEW_LINE> depth_df_uk = recalculate_depth(concat_depth_uk) <NEW_LINE> depth_df_yale = recalculate_depth(concat_depth_yale) <NEW_LINE> depth_df_uk['Coho... | Construct a dataframe which combines all of the CSVs containing
sequencing depth information for the TAAD cohorts and recalulates
the depth data of interest.
Args:
file_path: absolute path to the input directory | 625941e776e4537e8c351adc |
def shape(x): <NEW_LINE> <INDENT> return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2) | projection | 625941e7090684286d50f153 |
@pytest.mark.skipif('not HAS_SCIPY') <NEW_LINE> @pytest.mark.parametrize("renormalize_psf", (True, False)) <NEW_LINE> def test_psf_photometry_gaussian2(renormalize_psf): <NEW_LINE> <INDENT> psf = Gaussian2D(1. / (2 * np.pi * GAUSSIAN_WIDTH ** 2), PSF_SIZE // 2, PSF_SIZE // 2, GAUSSIAN_WIDTH, GAUSSIAN_WIDTH) <NEW_LINE> ... | Test psf_photometry with Gaussian PSF model from Astropy. | 625941e78e05c05ec3eea7df |
def plot_mod(self): <NEW_LINE> <INDENT> d = [] <NEW_LINE> d.append(0) <NEW_LINE> for i in range(len(self.__thick)): <NEW_LINE> <INDENT> d.append(d[-1] + self.__thick[i]) <NEW_LINE> <DEDENT> d = np.repeat(d, 2) <NEW_LINE> fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 5)) <NEW_LINE> ax[0].set_title('Curve Matchin... | for plotting of curve matching and earth model
parameter:
save_fig : if 'True' will saving figure. | 625941e799cbb53fe679304c |
def test_get_item_invalid_key(self): <NEW_LINE> <INDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> self.gb['invalid_key'] | Test __get_item__ for invalid key | 625941e731939e2706e4d2ca |
def _enable_cleanup(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> self = args[0] <NEW_LINE> result = func(*args, **kwargs) <NEW_LINE> self.cleanup(self) <NEW_LINE> return result <NEW_LINE> <DEDENT> return wrapper | Execute cleanup operation when the decorated function completed. | 625941e77b180e01f3dc4c5b |
@dcc.reroute <NEW_LINE> def shot_camera(shot_node): <NEW_LINE> <INDENT> raise NotImplementedError() | Returns camera associated given node
:param shot_node: str
:return: str | 625941e7498bea3a759b9f14 |
def __init__(self, file_name, *args, **kwargs): <NEW_LINE> <INDENT> super(FileImport, self).__init__(*args, **kwargs) <NEW_LINE> self.files = {'file': open(file_name, 'rb')} | :param file_name: File name (paths are supported)
:param args: Sent to parent class
:param kwargs: Sent to parent class
:return: | 625941e7be7bc26dc91cda5e |
def make_rdm2(mycc, t1, t2, l1, l2, ao_repr=False): <NEW_LINE> <INDENT> d1 = _gamma1_intermediates(mycc, t1, t2, l1, l2) <NEW_LINE> f = lib.H5TmpFile() <NEW_LINE> d2 = _gamma2_outcore(mycc, t1, t2, l1, l2, f, False) <NEW_LINE> return _make_rdm2(mycc, d1, d2, with_dm1=True, with_frozen=True, ao_repr=ao_repr) | Spin-traced two-particle density matrix in MO basis
dm2[p,q,r,s] = \sum_{sigma,tau} <p_sigma^\dagger r_tau^\dagger s_tau q_sigma>
Note the contraction between ERIs (in Chemist's notation) and rdm2 is
E = einsum('pqrs,pqrs', eri, rdm2) | 625941e7adb09d7d5db6cbf3 |
def give_user_permission(self, perm_name): <NEW_LINE> <INDENT> role_id = entities.Role().create()['id'] <NEW_LINE> permission_ids = [ permission['id'] for permission in entities.Permission(name=perm_name).search() ] <NEW_LINE> self.assertEqual(len(permission_ids), 1) <NEW_LINE> entities.Filter(permission=permission_ids... | Give ``self.user`` the ``perm_name`` permission.
This method creates a role and filter to accomplish the above goal.
When complete, the relevant relationhips look like this:
user → role ← filter → permission
:param str perm_name: The name of a permission. For example:
'create_architectures'.
:raises: ``Asser... | 625941e763f4b57ef0001573 |
def parse_query_string(query_string): <NEW_LINE> <INDENT> params = {} <NEW_LINE> for k, v in QS_PATTERN.findall(query_string): <NEW_LINE> <INDENT> params[k] = v <NEW_LINE> <DEDENT> return params | Parse a query string into a dict
Query string parameters are assumed to use standard form-encoding. Only
parameters with values are parsed. for example, given "foo=bar&flag",
this function would ignore "flag".
Args:
query_string: The query string to parse
Returns:
A dict containing (name, value) pairs, one p... | 625941e7d58c6744b42580c5 |
def test_message_fullchain(self): <NEW_LINE> <INDENT> print("checking message fullchain") <NEW_LINE> self.iterate(self.__fullchain) <NEW_LINE> print("...message fullchain ok") | Test message fullchain.
Generate a message, serialize it and deserialize it, the result should
be equal to the first generated message. | 625941e729b78933be1e5b0d |
def parse_cs(ivoid, cap_index=1): <NEW_LINE> <INDENT> if isinstance(ivoid, bytes): <NEW_LINE> <INDENT> ivoid = ivoid.decode('ascii') <NEW_LINE> <DEDENT> url = ("http://vao.stsci.edu/regtap/tapservice.aspx/sync?lang=adql&" "query=select%20detail_xpath%2Cdetail_value%20from%20" "rr.res_detail%20where%20" "ivoid%3D%27{0}%... | Return test query pars as dict for given IVO ID and capability index. | 625941e7dc8b845886cb599d |
def binario_decimal(numero_de_entrada): <NEW_LINE> <INDENT> contador = 0 <NEW_LINE> sumando = 2**(len(numero_de_entrada)-1) <NEW_LINE> for a in numero_de_entrada: <NEW_LINE> <INDENT> contador += sumando * int(a) <NEW_LINE> sumando //=2 <NEW_LINE> <DEDENT> result_bin_dec = contador <NEW_LINE> return result_bin_dec | Función 1 única para pasar binario a decimal | 625941e7851cf427c661a972 |
def test_absolute_url_behind_older_proxy(self): <NEW_LINE> <INDENT> proxy_headers = { 'Front-End-Https': 'on', 'X-Forwarded-Host': 'example.org', 'X-Forwarded-By': 'localhost', 'X-Forwarded-Proto': 'https', 'X-Forwarded-Ssl': 'on', 'X-Forwarded-For': '0.0.0.0, 127.0.0.1' } <NEW_LINE> response = requests.get(self.root_u... | Does the server return User-Agent-facing absolute URIs behind proxies?
Using older, de facto standards:
https://en.wikipedia.org/wiki/X-Forwarded-For
Relies on the root returing a ``self`` object. | 625941e74527f215b584c8b9 |
def create_channel(self, display_name): <NEW_LINE> <INDENT> url_name = name.replace('_', '-').lower() <NEW_LINE> r = self.api.create_channel(url_name, display_name, self.user["team_id"], description="", channel_type="O") <NEW_LINE> if r["status_code"] == 400: <NEW_LINE> <INDENT> logging.error("Unable to create channel ... | Create a channel.
This action also makes the user a 'channel administrator'. If the
channel already exists, this will give us an error.
Arguments:
display_name -- The user-visible name of the channel. We automatically
convert it to a viable url-name. | 625941e7236d856c2ad44c47 |
def main(): <NEW_LINE> <INDENT> data = input() <NEW_LINE> print(int(data[0])+int(data[1])) | defining the data function
| 625941e74f6381625f114ea3 |
def as_column(self): <NEW_LINE> <INDENT> return self | A column, seen as a column.
| 625941e78e71fb1e9831dc0e |
def send_text(self, textfile, update, context): <NEW_LINE> <INDENT> with open(textfile, 'r') as file: <NEW_LINE> <INDENT> MSG = file.read() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> context.bot.send_message( chat_id=update.message.chat_id, text=MSG, disable_web_page_preview=True, parse_mode='MarkdownV2' ) <NEW_LINE>... | Takes a textfile (path) and sends it as mesage to the user. | 625941e7d6c5a102081444b5 |
def modtime_id(*mod_times): <NEW_LINE> <INDENT> digest = hashlib.sha1() <NEW_LINE> for mod_time in mod_times: <NEW_LINE> <INDENT> digest.update(str(mod_time)) <NEW_LINE> <DEDENT> return base64.b32encode(digest.digest()).lower().strip('=') | Creates a unique ID from a list of modification times. | 625941e7e76e3b2f99f3ac6c |
def _propagate_delete(self, u, v): <NEW_LINE> <INDENT> nodes = list(self.descendants(v)) <NEW_LINE> nodes.append(v) <NEW_LINE> self.ancestor_matrix[nodes] = False <NEW_LINE> for n in topsort(self.adj, nodes): <NEW_LINE> <INDENT> parents = self.adj.parents(n) <NEW_LINE> ancestors = chain.from_iterable(self.ancestors(u) ... | Update ancestor matrix after edge removal following the algorithm of Giudici (2003)
Parameters
----------
v : int
The head of the arc that was removed | 625941e7eab8aa0e5d26dfc1 |
def loadxlsx(self): <NEW_LINE> <INDENT> filename = self.ents[1][1].get() <NEW_LINE> if (filename.endswith(".xlsx") or filename.endswith(".xls")): <NEW_LINE> <INDENT> print("Processing: %s" % filename.encode().decode()) <NEW_LINE> f = path.basename(filename) <NEW_LINE> self.status.set("Status: loading sheets of %s" % f.... | Get the sheet names in the chosen excel file. | 625941e7c432627299f050b0 |
def test_array_epochs(): <NEW_LINE> <INDENT> tempdir = _TempDir() <NEW_LINE> rng = np.random.RandomState(42) <NEW_LINE> data1 = rng.randn(20, 60) <NEW_LINE> sfreq = 1e3 <NEW_LINE> ch_names = ['EEG %03d' % (i + 1) for i in range(20)] <NEW_LINE> types = ['eeg'] * 20 <NEW_LINE> info = create_info(ch_names, sfreq, types) <... | Test creating evoked from array. | 625941e72eb69b55b151cd1d |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941e707d97122c4178cfc |
def get_pixel_center(self, row, column): <NEW_LINE> <INDENT> result = self.map_pixel_center_positions[row][column] <NEW_LINE> return result[1], result[0] | Get the pixel enter of a given grid position
:param row:
:param column:
:return: | 625941e7d99f1b3c44c679ee |
def onItemClicked (self,item,col,auto_edit=False): <NEW_LINE> <INDENT> trace = False and not g.unitTesting <NEW_LINE> verbose = False <NEW_LINE> if self.busy(): return <NEW_LINE> c = self.c <NEW_LINE> qt = QtCore.Qt <NEW_LINE> try: <NEW_LINE> <INDENT> self.selecting = True <NEW_LINE> p = self.item2position(item) <NEW_L... | Handle a click in a baseNativeTree widget item. | 625941e7d53ae8145f87a6ce |
def __add__(self, val): <NEW_LINE> <INDENT> return Point3(self[0] + val[0], self[1] + val[1], self[2] + val[2]) | A + B both vectors | 625941e7baa26c4b54cb1582 |
def test_recorder_setup_failure(): <NEW_LINE> <INDENT> hass = get_test_home_assistant() <NEW_LINE> with patch.object(Recorder, "_setup_connection") as setup, patch( "homeassistant.components.recorder.time.sleep" ): <NEW_LINE> <INDENT> setup.side_effect = ImportError("driver not found") <NEW_LINE> rec = Recorder( hass, ... | Test some exceptions. | 625941e7187af65679ca5587 |
def test_exclude_lines(self): <NEW_LINE> <INDENT> self.render_config_template( path=os.path.abspath(self.working_dir) + "/log/*", exclude_lines=["^DBG"] ) <NEW_LINE> os.mkdir(self.working_dir + "/log/") <NEW_LINE> testfile = self.working_dir + "/log/test.log" <NEW_LINE> file = open(testfile, 'w') <NEW_LINE> iterations ... | Checks if the lines matching exclude_lines regexp are dropped | 625941e7a219f33f34628dcb |
def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(SaffronConfirmationEmail, self).get_context_data(**kwargs) <NEW_LINE> return set_saffron_info(context) | テンプレートに埋め込む変数をオーバーライド
:param kwargs:
:return: context | 625941e7d486a94d0b98e5ae |
@listener.route('/VolumeDriver.Remove', methods=['POST']) <NEW_LINE> def remove(): <NEW_LINE> <INDENT> request_data = log_input('Remove', request) <NEW_LINE> volume_name = request_data['Name'] <NEW_LINE> target_host_name = request.remote_addr <NEW_LINE> LOG.debug('Target host address = {0}'.format(target_host_name)) <N... | 1. Unexport the volume from the target host;
2. Check if the current target host is the last target host of this volume,
if yes, remove the volume.
Returns: The error message needed by Docker daemon. | 625941e7bd1bec0571d90a96 |
def latest_message_group(text): <NEW_LINE> <INDENT> for group_type, group in group_tokens(text): <NEW_LINE> <INDENT> if group_type == 'message': <NEW_LINE> <INDENT> return group | Args:
text - changelog text
Returns: return latest message group | 625941e71d351010ab855f82 |
def test_get_strategy_commission(self): <NEW_LINE> <INDENT> strategy = BillStrategyFactory.get_strategy(self.bill_commission) <NEW_LINE> self.assertIsInstance(strategy, BillStrategyCommission) | should get correct strategy instance | 625941e7be8e80087fb210a3 |
def get_lat_long_coords(graph): <NEW_LINE> <INDENT> return [(graph.node[n]['y'], graph.node[n]['x']) for n in graph.nodes()] | returns list of tuples giving latitude, longitude pair | 625941e732920d7e50b2863b |
def find_by_query(self, query): <NEW_LINE> <INDENT> qry = query.lower().strip() <NEW_LINE> resp = self._fixture('query', qry) or self._find({'query': qry, 'sublanguageid': 'eng'}) <NEW_LINE> return self._resp_to_model(resp) | Find subtitles by query.
Note that it first tries to find and return a local fixture,
and only does an HTTP call if none was found.
:param query: query string describing movie
:returns: list of subtitles that match query | 625941e74c3428357757c78d |
def within_line(self, x: int, y) -> bool: <NEW_LINE> <INDENT> rect = self.get_rect() <NEW_LINE> coords = [rect[0], rect[1], rect[2] + rect[0], rect[3] + rect[1]] <NEW_LINE> return coords[0] < x < coords[2] and coords[1] < y < coords[3] | Check if given coordinates are within the line.
Parameters
----------
x
x coordinate of point
y
y coordinate of point | 625941e792d797404e3045f3 |
def extraOpOnChanged(self, obj, prop): <NEW_LINE> <INDENT> pass | otherOpOnChanged(obj, porp) ... overwrite to process onChange() events.
Can safely be overwritten by subclasses. | 625941e76fb2d068a760f50c |
def describe_battery(self): <NEW_LINE> <INDENT> return("This car has a " + str(self.battery_size) + "-kWh battery.") | Print a statement describing the battery size. | 625941e729b78933be1e5b0e |
def rbridge_id_interface_ve_ip_ip_config_address_ospf_passive(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> rbridge_id = ET.SubElement(config, "rbridge-id", xmlns="urn:brocade.com:mgmt:brocade-rbridge") <NEW_LINE> if kwargs.pop('delete_rbridge_id', False) is True: <NEW_LINE> <INDENT> delete_rb... | Auto Generated Code
| 625941e74e696a04525c98b5 |
def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None | MotionStatus - a model defined in Swagger | 625941e7cad5886f8bd27440 |
def getBooksByYear(catalog, year): <NEW_LINE> <INDENT> year = mp.get(catalog['years'], year) <NEW_LINE> if year: <NEW_LINE> <INDENT> return me.getValue(year)['books'] <NEW_LINE> <DEDENT> return None | Retorna los libros publicados en un año | 625941e75510c4643540f840 |
def _szukaj_warstwa(sql,nazwa_warstwy): <NEW_LINE> <INDENT> qv = get_warstwa(nazwa_warstwy) <NEW_LINE> nuri = QgsDataSourceUri(qv.dataProvider().dataSourceUri()) <NEW_LINE> nuri.setSql(sql) <NEW_LINE> mid = _SZUKAJ_IDS.get(nazwa_warstwy,0)+1 <NEW_LINE> nwar = QgsVectorLayer(nuri.uri(),nazwa_warstwy+'_szukaj_'+str(mid),... | Wyszukuje na warstwie wszystkie obiekty, ktore spelniaja polecenie sql i zwraca je w postaci
nowej warstwy QgsVectorLayer | 625941e7462c4b4f79d1db37 |
def build_fields(arg_fields): <NEW_LINE> <INDENT> if(arg_fields is None): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> fields = [] <NEW_LINE> for i, field in enumerate(arg_fields): <NEW_LINE> <INDENT> el = field.split(":") <NEW_LINE> column_index = i <NEW_LINE> cast = str <NEW_LINE> if(len(el) == 2): <NEW_LINE> ... | arg_fields:
List of strings representing field definitions. An field definition is in the form field_name:field_index (offset 1):cast_type.
field_name - any string without spaces can be used to name a field
field_index - 1 offset integer for the position in the tab-delimited file where this field occurs.
... | 625941e7d164cc61757831b7 |
def check_scenario_name(given_args): <NEW_LINE> <INDENT> scenario_name = given_args.get('scenario_name', False) <NEW_LINE> if not scenario_name: <NEW_LINE> <INDENT> raise ValueError("Required `scenario_name` not defined.") <NEW_LINE> <DEDENT> return scenario_name | Ensures given output path exists.
Arguments:
*given_args* : dict, of keyword arguments.
Returns:
*str* : scenario_name | 625941e7656771135c3ebcdb |
def Keywords(lang_id=0): <NEW_LINE> <INDENT> return [MASM_CPU_INST, MASM_FPU_INST, MASM_REGISTERS, MASM_DIRECTIVES, MASM_DIREC_OP, MASM_EXT_INST] | Returns Specified Keywords List
@param lang_id: used to select specific subset of keywords | 625941e7de87d2750b8601ff |
def _add_add_submenu(self, oMenuWidget): <NEW_LINE> <INDENT> oAddMenu = self.create_submenu(oMenuWidget, 'Add Pane') <NEW_LINE> self.create_menu_item("Add New Blank Pane", oAddMenu, self._oMainWindow.add_pane_end) <NEW_LINE> self.__oAddPCLPane = self.create_menu_item("Add White Wolf Card List", oAddMenu, self._oMainWin... | Create a submenu for the add pane options | 625941e7baa26c4b54cb1583 |
def test_valid_codes(self): <NEW_LINE> <INDENT> valid_codes = range(1000, 1004) + range(1007, 1012) <NEW_LINE> for code in valid_codes: <NEW_LINE> <INDENT> self.assertTrue(hybi.is_valid_close_code(code)) | All other codes are considered valid (or are undefined by the spec). | 625941e78a43f66fc4b544c8 |
def y_residuals_leverage(ax): <NEW_LINE> <INDENT> for j in range(MODEL.p): <NEW_LINE> <INDENT> for i in range(MODEL.n): <NEW_LINE> <INDENT> scatter_wrapper(ax, MODEL.leverage[i], MODEL.E_y[i, j], TRAIN_SET.categorical_y[i]) <NEW_LINE> <DEDENT> <DEDENT> ax.set_title('Leverage – Y residuals') <NEW_LINE> ax.set_xlabel('Le... | Plot Y residuals over the leverage. | 625941e707f4c71912b118ec |
def test_update_user_profile(self): <NEW_LINE> <INDENT> payload = { 'name': 'new name', 'password': 'newtest123' } <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(self.user.name, payload['name']) <NEW_LINE> self.assertTrue(self.user.check_password(p... | Test updating the user profile for authenticated user | 625941e74527f215b584c8ba |
def __len__(self): <NEW_LINE> <INDENT> node = self.first_node <NEW_LINE> size = 0 <NEW_LINE> while node is not None: <NEW_LINE> <INDENT> node = node.next <NEW_LINE> size += 1 <NEW_LINE> <DEDENT> return size | Implementar o tamanho a lista. | 625941e710dbd63aa1bd3009 |
def handle_updates(self, all_updates): <NEW_LINE> <INDENT> for dataset in sorted(all_updates): <NEW_LINE> <INDENT> updates = all_updates[dataset] <NEW_LINE> if updates: <NEW_LINE> <INDENT> log.verbose("-" * 120) <NEW_LINE> for update in sorted(updates): <NEW_LINE> <INDENT> new_ref = update.new_reference.upper() <NEW_LI... | Base handle_updates() updates the loaded headers with the computed bestrefs for use
with --save-pickle. | 625941e756ac1b37e626462e |
def lift_from_homology(self, x): <NEW_LINE> <INDENT> return x.lift() | Lift a cohomology class to the algebra of mixed differential forms.
EXAMPLES::
sage: M = Manifold(2, 'M')
sage: X.<x,y> = M.chart()
sage: C = M.de_rham_complex()
sage: H = C.cohomology()
sage: alpha = M.diff_form(1, [1,1], name='alpha')
sage: alpha.display()
alpha = dx + dy
sage: a = H... | 625941e7d53ae8145f87a6cf |
@user_language <NEW_LINE> def settings(bot, update): <NEW_LINE> <INDENT> msg = _("Please, choose a language:\n") <NEW_LINE> msg += "en_US - English (US)\n" <NEW_LINE> msg += "pt_BR - Português (Brasil)\n" <NEW_LINE> languages_keyboard = [ [telegram.KeyboardButton('en_US - English (US)')], [telegram.KeyboardButton('pt_B... | Configure the messages language using a custom keyboard. | 625941e723e79379d52ee9c6 |
def stop(self): <NEW_LINE> <INDENT> self.bserver.stop() <NEW_LINE> self.iserver.stop() | Stop server | 625941e7d6c5a102081444b6 |
def minDeletionSize(A): <NEW_LINE> <INDENT> asc = [[ord(x) for x in a] for a in A] <NEW_LINE> l = len(A) <NEW_LINE> res = 0 <NEW_LINE> if l > 0: <NEW_LINE> <INDENT> wl = len(A[0]) <NEW_LINE> for i in range(wl): <NEW_LINE> <INDENT> for j in range(1, l): <NEW_LINE> <INDENT> if asc[j][i] < asc[j-1][i]: <NEW_LINE> <INDENT>... | 944. 删列造序
给定由 N 个小写字母字符串组成的数组 A,其中每个字符串长度相等。
选取一个删除索引序列,对于 A 中的每个字符串,删除对应每个索引处的字符。 所余下的字符串行从上往下读形成列。
比如,有 A = ["abcdef", "uvwxyz"],删除索引序列 {0, 2, 3},删除后 A 为["bef", "vyz"], A 的列分别为["b","v"], ["e","y"], ["f","z"]。(形式上,第 n 列为 [A[0][n], A[1][n], ..., A[A.length-1][n]])。
假设,我们选择了一组删除索引 D,那么在执行删除操作之后,A 中所剩余的每一列都必须是 非降序 排列的,然后... | 625941e7009cb60464c63816 |
def GetPours(self): <NEW_LINE> <INDENT> pass | GetPours(self: Part) -> ModelObjectEnumerator | 625941e78e7ae83300e4b436 |
def run(self): <NEW_LINE> <INDENT> items = [] <NEW_LINE> data = self.indata['Cluster'] <NEW_LINE> meta = data[0].metadata['Cluster'] <NEW_LINE> if 'obj_fcn' in meta: <NEW_LINE> <INDENT> items += ['Objective Function'] <NEW_LINE> <DEDENT> if 'vrc' in meta and len(data) > 1: <NEW_LINE> <INDENT> items += ['Variance Ratio ... | Run.
Returns
-------
None. | 625941e7d8ef3951e32439a5 |
def read_version(s): <NEW_LINE> <INDENT> tokens = s.split() <NEW_LINE> if len(tokens) != 3: <NEW_LINE> <INDENT> raise ValueError("File header has unsupported format.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> version = float(tokens[0]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError("Version number... | Read the Gmsh file version. | 625941e75510c4643540f841 |
def top_and_tail(*arrays): <NEW_LINE> <INDENT> if len(arrays) > 1: <NEW_LINE> <INDENT> for arr in arrays[1:]: <NEW_LINE> <INDENT> assert len(arr) == len(arrays[0]) <NEW_LINE> <DEDENT> <DEDENT> nans = np.where(~np.isnan(arrays[0]))[0] <NEW_LINE> first, last = nans[0], nans[-1] <NEW_LINE> return [array[first:last+1] for ... | Top and tail all arrays to the non-NaN extent of the first array.
E.g. crop the NaNs from the top and tail of a well log.
Args:
arrays (list): A list of arrays to treat.
Returns:
list: A list of treated arrays. | 625941e78a349b6b435e85db |
def false_if_raises(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> async def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = await f(*args, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> res = False <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> return wrapper | Return False if `f` raises an exception | 625941e701c39578d7e752a3 |
def get_replication_group(self, replication_group_id): <NEW_LINE> <INDENT> return self.conn.get( url='vdc/data-service/vpools/{0}'.format(replication_group_id)) | Gets the details for the specified replication group.
Required role(s):
SYSTEM_ADMIN
SYSTEM_MONITOR
NAMESPACE_ADMIN
Example JSON result from the API:
{
u'isAllowAllNamespaces': True,
u'remote': None,
u'name': u'us2',
u'tags': [
],
u'global': None,
u'creation_time': 1434740060384,
u'... | 625941e72ae34c7f2600d598 |
def tree_difference(a, b): <NEW_LINE> <INDENT> return _do_tree_difference(a, b, "", True) | Compare TreeNodes A and B, and create a TreeDifference instance. | 625941e738b623060ff0b255 |
def get_dataset(dataset_split): <NEW_LINE> <INDENT> def make_input_dataset(): <NEW_LINE> <INDENT> test_data = tfds.load(name=FLAGS.target_dataset, split=dataset_split) <NEW_LINE> test_data = test_data.batch(FLAGS.train_batch_size) <NEW_LINE> dataset = tf.data.Dataset.zip((test_data,)) <NEW_LINE> dataset = dataset.map(_... | Returns dataset creation function. | 625941e7ad47b63b2c50a3e7 |
def record(self, is_result, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> stream = self.generator.stream <NEW_LINE> try: <NEW_LINE> <INDENT> depth = s_delta(stream)[0] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> depth = -1 <NEW_LINE> <DEDENT> if depth >= self._deepest and is_result: <NEW_LINE> ... | Record the data. | 625941e7379a373c97cfafaf |
def testLogin(self): <NEW_LINE> <INDENT> self.cls = common.getXls("testCase.xlsx","test1") <NEW_LINE> self.log = log.get_log() <NEW_LINE> self.logger = self.log.getLogger() <NEW_LINE> self.Http = configHttp.ConfigHttp() <NEW_LINE> self.HttpUrl = self.Http.setUrl(self.cls.get(4).get("url")) <NEW_LINE> self.logger.info(s... | 登陆 | 625941e75e10d32532c5f38d |
def test_m2m_dict_multiple_field_diff(self): <NEW_LINE> <INDENT> new_state = { u'foo': [ {u'id': 1, 'name': u'bar' } ], u'toppings': [ {u'id': 1, 'name': u'ceboloa'}, {u'id': 5, 'name': u'cogumelo'}, {u'id': 6, 'name': u'abobrinha'}, {u'id': 8, 'name': u'codorna'}, {u'id': 9, 'name': u'banana'}, {u'id': 10, 'name': u'a... | test where old state and new state contains multiple fields,
with one field having a changed value | 625941e73617ad0b5ed6835f |
def __repr__(self): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> lines.append(self.delim + " FIELDS " + " ".join(self.fields)) <NEW_LINE> for name, value in self.constants.items(): <NEW_LINE> <INDENT> lines.append(f"{self.delim} SET {name} {value}") <NEW_LINE> <DEDENT> return "\n".join(lines) | Returns header as string with newlines to be printed to file.
Can be used directly as header argument to numpys savetxt. | 625941e70c0af96317bb8650 |
def fpb_replace_plugin_content(self, local_file, remote_file): <NEW_LINE> <INDENT> self.execute_in_container( "rm -rf {0}".format(remote_file), self.container) <NEW_LINE> self.ssh_manager.upload_to_remote( ip=self.admin_ip, source=local_file, target="/tmp/temp.file" ) <NEW_LINE> self.copy_between_node_and_container( '/... | Replaces file inside nailgun container with given local file
:param local_file: path to the local file
:param remote_file: file to be replaced
:return: nothing | 625941e755399d3f05588b1f |
def encrypt(plaintext, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import base64 <NEW_LINE> from Crypto import Random <NEW_LINE> from Crypto.Cipher import AES <NEW_LINE> <DEDENT> except ImportError as e: <NEW_LINE> <INDENT> exit_message(str(e), 1, False) <NEW_LINE> <DEDENT> iv = Random.new().read(AES.block_size)... | Encrypt the plaintext with AES method.
Parameters:
plaintext -- String to be encrypted.
key -- Key for encryption. | 625941e73346ee7daa2b31d7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.