code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def to_string(self): <NEW_LINE> <INDENT> csv_str =CSV_DELIMITER.join(self.csv_row) <NEW_LINE> message = "[MAPPING-URI:<{0}>] [MAPPING-ACTION:<{1}>] [CSV:<{2}>] [MAPPING-INFO:<{3}>] ".format(self.uri_dataset,self.action, csv_str, self.mapping_info) <NEW_LINE> return message | reate a string version of the Mapping
:return: | 625941c082261d6c526ab3fe |
def assign_site_properties(self, slab, height=0.9): <NEW_LINE> <INDENT> if 'surface_properties' in slab.site_properties.keys(): <NEW_LINE> <INDENT> return slab <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> surf_sites = self.find_surface_sites_by_height(slab, height) <NEW_LINE> <DEDENT> surf_props = ['surface' if site in surf_sites else 'subsurface' for site in slab.sites] <NEW_LINE> return slab.copy( site_properties={'surface_properties': surf_props}) | Assigns site properties. | 625941c096565a6dacc8f62e |
def convert_vals(x): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return float(x) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return np.NaN | Helper Function for make_parents() | 625941c08da39b475bd64ed3 |
def _process_noise( self ): <NEW_LINE> <INDENT> return np.matrix( np.random.multivariate_normal( np.zeros((self.n_states,)), self.Sw, 1 ).reshape(self.n_states,1) ) | Get some noise. | 625941c0b57a9660fec337e3 |
@pytest.mark.sauce <NEW_LINE> @pytest.mark.tier(0) <NEW_LINE> @pytest.mark.parametrize('context', [ViaREST, ViaUI]) <NEW_LINE> def test_generic_object_definition_crud(appliance, context, soft_assert): <NEW_LINE> <INDENT> with appliance.context.use(context): <NEW_LINE> <INDENT> definition = appliance.collections.generic_object_definitions.create( name="{}_generic_class{}".format(context.name.lower(), fauxfactory.gen_alphanumeric()), description="Generic Object Definition", attributes={"addr01": "string"}, associations={"services": "Service"}, methods=["hello_world"]) <NEW_LINE> if context.name == 'UI': <NEW_LINE> <INDENT> view = appliance.browser.create_view(BaseLoggedInPage) <NEW_LINE> view.flash.assert_success_message( 'Generic Object Class "{}" has been successfully added.'.format(definition.name)) <NEW_LINE> <DEDENT> assert definition.exists <NEW_LINE> with update(definition): <NEW_LINE> <INDENT> definition.name = '{}_updated'.format(definition.name) <NEW_LINE> definition.attributes = {"new_address": "string"} <NEW_LINE> <DEDENT> if context.name == 'UI': <NEW_LINE> <INDENT> view.flash.assert_success_message( 'Generic Object Class "{}" has been successfully saved.'.format(definition.name)) <NEW_LINE> view = navigate_to(definition, 'Details') <NEW_LINE> soft_assert(view.summary('Attributes (2)').get_text_of('new_address')) <NEW_LINE> soft_assert(view.summary('Attributes (2)').get_text_of('addr01')) <NEW_LINE> soft_assert(view.summary('Associations (1)').get_text_of('services')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rest_definition = appliance.rest_api.collections.generic_object_definitions.get( name=definition.name) <NEW_LINE> soft_assert("new_address" in rest_definition.properties['attributes']) <NEW_LINE> soft_assert("addr01" not in rest_definition.properties['attributes']) <NEW_LINE> <DEDENT> definition.delete() <NEW_LINE> if context.name == 'UI' and not BZ(bug_id=1644658, forced_streams=["5.10"]).blocks: <NEW_LINE> <INDENT> view.flash.assert_success_message( 'Generic Object Class:"{}" was successfully deleted'.format(definition.name)) <NEW_LINE> <DEDENT> assert not definition.exists | Polarion:
assignee: jdupuy
casecomponent: GenericObjects
caseimportance: high
initialEstimate: 1/12h
tags: 5.9 | 625941c0925a0f43d2549dd7 |
@app.cli.command() <NEW_LINE> @click.option('--coverage/--no-coverage', default=False, help='Run tests under code coverage.') <NEW_LINE> def test(coverage): <NEW_LINE> <INDENT> if coverage and not os.environ.get('FLASK_COVERAGE'): <NEW_LINE> <INDENT> import subprocess <NEW_LINE> os.environ['FLASK_COVERAGE'] = '1' <NEW_LINE> sys.exit(subprocess.call(sys.argv)) <NEW_LINE> <DEDENT> import unittest <NEW_LINE> tests = unittest.TestLoader().discover('tests') <NEW_LINE> unittest.TextTestRunner(verbosity=2).run(tests) <NEW_LINE> if COV: <NEW_LINE> <INDENT> COV.stop() <NEW_LINE> COV.save() <NEW_LINE> print('Coverage Sumary:') <NEW_LINE> COV.report() <NEW_LINE> basedir = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> covdir = os.path.join(basedir, 'tmp/coverage') <NEW_LINE> COV.html_report(directory=covdir) <NEW_LINE> print('HTML version: file://%s/index.html' % covdir) <NEW_LINE> COV.erase() | Run the unit tests. | 625941c0b830903b967e986f |
def error_500(request): <NEW_LINE> <INDENT> t = loader.get_template('500.html') <NEW_LINE> exc_type, value, tb = sys.exc_info() <NEW_LINE> context = RequestContext(request) <NEW_LINE> if exc_type == URLError: <NEW_LINE> <INDENT> context['error'] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context['error'] = None <NEW_LINE> <DEDENT> return HttpResponseServerError(t.render(Context(context))) | Custom error 500 handler.
Connected in cghub.urls. | 625941c0009cb60464c63315 |
def load_activity_from_newest_file(activity): <NEW_LINE> <INDENT> fpath = get_newest_file(activity.folder_path) <NEW_LINE> frame = pd.read_csv(fpath) <NEW_LINE> frame.submitted = pd.to_datetime( frame.submitted ) <NEW_LINE> if 'student_id' not in frame.index: <NEW_LINE> <INDENT> frame.rename( { 'id': 'student_id' }, axis=1, inplace=True ) <NEW_LINE> <DEDENT> return frame | Uses the creation time of the files in the activity's folder
to determine which is the newest and loads data from it
:param activity:
:return: | 625941c030bbd722463cbd25 |
def destroy(self, project, organization=None): <NEW_LINE> <INDENT> path = "organizations/%d/projects/%d" % (organization, project) if organization else "projects/%d" % (project) <NEW_LINE> return self.delete(path) | Destroys a project.
.. note::
You must be the owner in order to perform this action. | 625941c094891a1f4081ba0a |
def get_me(self): <NEW_LINE> <INDENT> return self._get_resource(('user'), CurrentUser) | Get the authenticated user. | 625941c0f9cc0f698b14055f |
def RMS(sig): <NEW_LINE> <INDENT> n = len(sig) <NEW_LINE> return(np.sqrt(( 1 / n) * np.sum(sig ** 2)) * sig) | Inputs:
sig = input signal in x [m = position] or time domain.
Output:
RMS = RMS signal in x [m = position] or time domain.
Return Root Mean Square (RMS) value of (time) signal
for more info see: https://en.wikipedia.org/wiki/Root_mean_square
1
RMS =sqrt(- * (x_1^2 + x_2^2 + ... x_n^2))
n | 625941c05f7d997b871749f7 |
def is_full_rank(self): <NEW_LINE> <INDENT> return self.rank() == len(self._rows) | Checks if the matrix is full rank - that is, whether its rank equals
the number of dimensions of its column space.
:rtype: ``bool`` | 625941c04527f215b584c3bc |
def _handleBackspaces(self, text): <NEW_LINE> <INDENT> if '\b' in text: <NEW_LINE> <INDENT> nb, text = self._handleBackspaces_split(text) <NEW_LINE> if nb: <NEW_LINE> <INDENT> self._cursor1.clearSelection() <NEW_LINE> self._cursor1.movePosition(self._cursor1.Left, A_KEEP, nb) <NEW_LINE> self._cursor1.removeSelectedText() <NEW_LINE> <DEDENT> <DEDENT> return text | Apply backspaces in the string itself and if there are
backspaces left at the start of the text, remove the appropriate
amount of characters from the text.
Returns the new text. | 625941c08c3a87329515831a |
def writeMetadataFile(self,metadataFile): <NEW_LINE> <INDENT> rootElement = ET.Element("Metadata",{"type":self.metadataType,"metadata_version":self.metadataVersion,"script_version":self.scriptVersion}) <NEW_LINE> nodeTool = ET.SubElement(rootElement,"Tool") <NEW_LINE> ET.SubElement(nodeTool,"Name").text = self.toolName <NEW_LINE> ET.SubElement(nodeTool,"Version").text = self.toolVersion <NEW_LINE> nodeProcessing = ET.SubElement(rootElement,"Processing") <NEW_LINE> ET.SubElement(nodeProcessing,"ComputerID").text = self.computerID <NEW_LINE> ET.SubElement(nodeProcessing,"Operator").text = self.operator <NEW_LINE> nodeRuns = ET.SubElement(nodeProcessing,"Runs") <NEW_LINE> for run in self.Runs: <NEW_LINE> <INDENT> nodeRun = ET.SubElement(nodeRuns,"Run",{"status":run.status}) <NEW_LINE> ET.SubElement(nodeRun,"TimeStart").text = run.timestampStart.strftime('%Y-%m-%dT%H:%M:%S') <NEW_LINE> ET.SubElement(nodeRun,"TimeStop").text = run.timestampStop.strftime('%Y-%m-%dT%H:%M:%S') <NEW_LINE> ET.SubElement(nodeRun,"TotalProcessingTime").text = str(run.timeProcessing.total_seconds()) <NEW_LINE> nodeParameters = ET.SubElement(nodeRun,"Parameters") <NEW_LINE> for parameter in run.Parameters: <NEW_LINE> <INDENT> nodeParameter = ET.SubElement(nodeParameters,"Parameter") <NEW_LINE> ET.SubElement(nodeParameter,"Name").text = parameter.Name <NEW_LINE> ET.SubElement(nodeParameter,"Value").text = parameter.Value <NEW_LINE> <DEDENT> nodeOutputs = ET.SubElement(nodeRun,"Outputs") <NEW_LINE> for output in run.Outputs: <NEW_LINE> <INDENT> nodeOutput = ET.SubElement(nodeOutputs,"Output") <NEW_LINE> ET.SubElement(nodeOutput,"Name").text = output.Name <NEW_LINE> ET.SubElement(nodeOutput,"Value").text = output.Value <NEW_LINE> <DEDENT> nodeMessages = ET.SubElement(nodeRun,"Messages") <NEW_LINE> for message in run.Messages: <NEW_LINE> <INDENT> ET.SubElement(nodeMessages,"Message",{"Level":message.Level}).text = message.Message <NEW_LINE> <DEDENT> nodeResults = ET.SubElement(nodeRun,"Results") <NEW_LINE> for result in run.Results: <NEW_LINE> <INDENT> ET.SubElement(nodeResults,result.Name).text = result.Value <NEW_LINE> <DEDENT> <DEDENT> indent(rootElement) <NEW_LINE> tree = ET.ElementTree(rootElement) <NEW_LINE> tree.write(metadataFile,'utf-8',True) | save the final metadata xml file | 625941c06aa9bd52df036d04 |
def delete_glossary(self, glossaryId: int): <NEW_LINE> <INDENT> return self.requester.request( method="delete", path=self.get_glossaries_path(glossaryId=glossaryId), ) | Delete Glossary.
Link to documentation:
https://support.crowdin.com/api/v2/#operation/api.glossaries.delete | 625941c055399d3f05588615 |
def all_output_analogs(self): <NEW_LINE> <INDENT> return (a for a in self.aliases if a.name in self.analog_send_port_names) | Returns an iterator over all aliases that are required for analog
send ports | 625941c030bbd722463cbd26 |
def resolve_conflicts(self): <NEW_LINE> <INDENT> neighbors = self.nodes <NEW_LINE> new_chain = None <NEW_LINE> max_length = len(self.chain) <NEW_LINE> for node in neighbors: <NEW_LINE> <INDENT> response = requests.get(f'http://{node}/chain') <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> length = response.json()['length'] <NEW_LINE> chain = response.json()['chain'] <NEW_LINE> if length > max_length and self.valid_chain(chain): <NEW_LINE> <INDENT> max_length = length <NEW_LINE> new_chain = chain <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if new_chain: <NEW_LINE> <INDENT> self.chain = new_chain <NEW_LINE> return True <NEW_LINE> <DEDENT> return False | This is the consensus algorithm, it resolves resolve_conflicts
by replacing our chain with the longest one in the networkself.
:return: True if chain was replaced, False if not | 625941c09b70327d1c4e0d36 |
def vgg11(pretrained=False, **kwargs): <NEW_LINE> <INDENT> if pretrained: <NEW_LINE> <INDENT> kwargs['init_weights'] = False <NEW_LINE> <DEDENT> model = VGG(make_layers(cfg['A']), **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> model.load_state_dict(model_zoo.load_url(model_urls['vgg11'])) <NEW_LINE> <DEDENT> return model | VGG 11-layer model (configuration "A")
Agrs:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941c06e29344779a62576 |
def _fullyear(year): <NEW_LINE> <INDENT> if year > 100: <NEW_LINE> <INDENT> return year <NEW_LINE> <DEDENT> year += 1900 + 100 * (year < 90) <NEW_LINE> return year | Convert | 625941c091af0d3eaac9b979 |
def get_hypervisor_type(self): <NEW_LINE> <INDENT> return self._conn.getType() | Get hypervisor type.
:returns: hypervisor type (ex. qemu) | 625941c06fb2d068a760effd |
def assertOperatorNormClose(self, U: qtypes.UnitaryMatrix, V: qtypes.UnitaryMatrix, rtol: float = 1e-5, atol: float = 1e-8) -> None: <NEW_LINE> <INDENT> message = (f"Matrices U = \n{U}\nand V = \n{V}\nare not close " f"enough! ||U-V|| = {qdists.operator_norm(U - V)}.") <NEW_LINE> self.assertTrue( numpy.isclose(qdists.operator_norm(U - V), 0, rtol=rtol, atol=atol), msg=message) | Check if the two unitary matrices are close to each other.
The check is performed by computing the operator norm of the
difference of the two matrices and check that this norm is below
a given tolerence.
:param U: First array.
:param V: Second array.
:param rtol: Relative tolerance. See numpy.isclose documentation
for a more detailed explanation.
:param atol: Absolute tolerance. See numpy.isclose documentation
for a more detailed explanation. | 625941c0e8904600ed9f1e8c |
def getRelativeTimeColumns(series): <NEW_LINE> <INDENT> if series[0] == np.NaN: <NEW_LINE> <INDENT> start_time = series.dropna().index[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start_time = series[0] <NEW_LINE> <DEDENT> new_series = series - start_time <NEW_LINE> return new_series | normalize the time features by
the start_time, the first none-NaN
value | 625941c0462c4b4f79d1d632 |
@app.route('/apps/accounting/ledgeractors/<ledgerId>', methods=['GET', 'POST']) <NEW_LINE> @userRoleRequired({('system', 'admin')}) <NEW_LINE> def accountingLedgerActorsView(ledgerId): <NEW_LINE> <INDENT> user = g.user <NEW_LINE> db = dbGetDatabase() <NEW_LINE> request._onErrorUrl = url_for('accountingIndexView') <NEW_LINE> pageFeatures = prepareTaskPageFeatures( appsPageDescriptor, ['root', 'accounting'], g, overrides={ 'pageTitle': 'Actors for ledger "%s"' % ledgerId, 'pageSubtitle': 'Configure actors taking part in the ledger', 'iconUrl': makeSettingImageUrl( g, 'custom_apps_images', 'accounting_ledger', ), }, appendedItems=[{ 'kind': 'link', 'target': None, 'name': 'Actors for ledger', }], ) <NEW_LINE> ledger = dbGetLedger(db, user, ledgerId) <NEW_LINE> if ledger is None: <NEW_LINE> <INDENT> raise OstracionError('Unknown ledger "%s"' % ledgerId) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> actorform = AccountingLedgerActorForm() <NEW_LINE> if actorform.validate_on_submit(): <NEW_LINE> <INDENT> newLedger = Ledger(**recursivelyMergeDictionaries( { 'configuration_date': datetime.datetime.now(), }, defaultMap=ledger.asDict(), )) <NEW_LINE> dbUpdateLedger(db, user, newLedger) <NEW_LINE> newActor = Actor( ledger_id=ledger.ledger_id, actor_id=actorform.actorId.data, name=actorform.name.data, ) <NEW_LINE> dbAddActorToLedger(db, user, ledger, newActor) <NEW_LINE> return redirect(url_for( 'accountingLedgerActorsView', ledgerId=ledger.ledger_id, )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> actorsInLedger = sorted( dbGetActorsForLedger(db, user, ledger), key=lambda a: a.actor_id.lower(), ) <NEW_LINE> return render_template( 'apps/accounting/ledgeractors.html', user=user, ledger=ledger, actorsInLedger=actorsInLedger, actorform=actorform, backToUrl=url_for('accountingIndexView'), **pageFeatures, ) | Actors configured for a ledger. | 625941c021bff66bcd6848b7 |
def test_aat_from_file(self): <NEW_LINE> <INDENT> file_path = os.path.join(os.path.dirname(__file__), '..', 'igc_files', 'aat_strepla.igc') <NEW_LINE> with open(file_path, 'r', encoding='utf-8') as f: <NEW_LINE> <INDENT> parsed_igc_file = Reader().read(f) <NEW_LINE> <DEDENT> trace_errors, trace = parsed_igc_file['fix_records'] <NEW_LINE> self.assertEqual(len(trace_errors), 0) <NEW_LINE> task, _, _ = get_info_from_comment_lines(parsed_igc_file) <NEW_LINE> self.assertIsInstance(task, AAT) <NEW_LINE> self.assertEqual(task.t_min, datetime.timedelta(hours=2, minutes=30)) <NEW_LINE> expected_waypoints = [ ('AP3 Muellhalde', None), ('Loreley', 20000), ('Kusel', 40000), ('Loreley', 20000), ('ZP Anspach/Taunus', None), ] <NEW_LINE> self.assertEqual(len(task.waypoints), len(expected_waypoints)) <NEW_LINE> for i, waypoint in enumerate(task.waypoints): <NEW_LINE> <INDENT> expected_name, expected_r_max = expected_waypoints[i] <NEW_LINE> self.assertEqual(waypoint.name, expected_name) <NEW_LINE> if 0 < i < len(expected_waypoints) - 1: <NEW_LINE> <INDENT> self.assertEqual(waypoint.r_max, expected_r_max) <NEW_LINE> <DEDENT> <DEDENT> competitor = Competitor(trace, 'CX', 'Discus2b', 1, 'Karsten Leucker') <NEW_LINE> competitor.analyse(task, 'pysoar') <NEW_LINE> time_diff = seconds_time_difference(competitor.trip.refined_start_time, datetime.time(13, 22, 40)) <NEW_LINE> dist_diff = sum(competitor.trip.distances) - 283500 <NEW_LINE> self.assertLessEqual(abs(time_diff), 1) <NEW_LINE> self.assertEqual(len(competitor.trip.fixes), len(expected_waypoints)) <NEW_LINE> self.assertLessEqual(abs(dist_diff), 1000) | Test if aat is correctly recognised and waypoint are correct
file from: https://www.strepla.de/scs/Public/scoreDay.aspx?cId=451&idDay=7912, competitor 1 CX | 625941c06aa9bd52df036d05 |
def do_clear_error(self, args) : <NEW_LINE> <INDENT> if self.deferred > 0 : return False <NEW_LINE> self.bindings.bind('_error_code_', str(0)) <NEW_LINE> self.bindings.bind('_error_message_', "") <NEW_LINE> self.exit_code = 0 <NEW_LINE> self.exit_message = '' <NEW_LINE> return False | clear_error -- clear any error status | 625941c0d7e4931a7ee9de7f |
def parseOpenFmt(self, storage): <NEW_LINE> <INDENT> if (six.PY3 and isinstance(storage, bytes)): <NEW_LINE> <INDENT> if storage.startswith(b'{"'): <NEW_LINE> <INDENT> return 'jsonpickle' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'pickle' <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if storage.startswith('{"'): <NEW_LINE> <INDENT> return 'jsonpickle' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'pickle' | Look at the file and determine the format
| 625941c023e79379d52ee4c8 |
def toCamelCase(name, has_title=False): <NEW_LINE> <INDENT> capitalize_next = False <NEW_LINE> result = [] <NEW_LINE> for c in name: <NEW_LINE> <INDENT> if c == '_': <NEW_LINE> <INDENT> if result: <NEW_LINE> <INDENT> capitalize_next = True <NEW_LINE> <DEDENT> <DEDENT> elif capitalize_next: <NEW_LINE> <INDENT> result.append(c.upper()) <NEW_LINE> capitalize_next = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result += c <NEW_LINE> <DEDENT> <DEDENT> if not has_title: <NEW_LINE> <INDENT> if result and result[0].isupper(): <NEW_LINE> <INDENT> result[0] = result[0].lower() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result[0] = result[0].title() <NEW_LINE> <DEDENT> return ''.join(result) | Converts name to camel-case and returns it. | 625941c0187af65679ca5080 |
def out_links(self): <NEW_LINE> <INDENT> return {link for compFa in self._comportamentalFAs for link in compFa.out_links()} | Returns the list of links exiting in the ComportamentalFAN
:return: The list of links exiting in the ComportamentalFAN
:rtype: list | 625941c0d53ae8145f87a1d6 |
def append(self, el): <NEW_LINE> <INDENT> type_args = type(el), str(self), type(el), self._expected_type <NEW_LINE> assert isinstance(el, self._expected_type), ('Invalid type {} appended' ' to {}; got {}, expected {}').format(*type_args) <NEW_LINE> self._elements.append(el) <NEW_LINE> return el | Append an element (parameter, constraint, or variable) to the
collection. This checks for consistency, i.e. an error is thrown if
anything but a :class:`symenergy.core.Parameter` is appended to a
:class:`symenergy.core.ParameterCollection`.
Parameters
----------
el : appropriate SymEnergy class
Parameter, Constraint, or Variable | 625941c01f5feb6acb0c4ab6 |
def GetResponseText(self): <NEW_LINE> <INDENT> return self.RespTextCtrl.GetValue() | Return the modify Response report text
| 625941c0c432627299f04ba7 |
def start(self): <NEW_LINE> <INDENT> return _transmit_nodes_swig.howto_ekf2_ff_sptr_start(self) | start(howto_ekf2_ff_sptr self) -> bool | 625941c0cad5886f8bd26f3c |
def __selectDir__(self): <NEW_LINE> <INDENT> p = tk.filedialog.askdirectory(initialdir=".") <NEW_LINE> if p: <NEW_LINE> <INDENT> self.folder.set(p) <NEW_LINE> self.update() <NEW_LINE> self._fsearch = FileSearch(self.folder.get()) <NEW_LINE> self.__search__() | callback function for the "Change Folder" button | 625941c085dfad0860c3adbc |
def test_article_vor(self): <NEW_LINE> <INDENT> resp = self.c.get(reverse("v2:article", kwargs={"msid": self.msid1})) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertEqual( resp.content_type, "application/vnd.elife.article-vor+json; version=6" ) <NEW_LINE> data = utils.json_loads(resp.content) <NEW_LINE> utils.validate(data, SCHEMA_IDX["vor"]) <NEW_LINE> self.assertEqual(data["version"], 3) | the latest version of the requested article is returned | 625941c04428ac0f6e5ba754 |
def _do_explicite_matrix_(self, params): <NEW_LINE> <INDENT> self.axes_wrapper.matrix_trafo(params) | Does explicite matrix transformation | 625941c0cc40096d615958b4 |
def test_smooth_mni(self): <NEW_LINE> <INDENT> assert False | test if spatial smoothing works as expected
Parameters
----------
self
Returns
-------
generates an exception if smooth_mni_test fails
Notes
-----
On Real Data -
Verify that the intensiy distribution in smoothed image is still centered at zero and have unit variance
Load the z_2standard input image in python. Form the (2-D ) Guassian kernel matrix( TODO: determine the size of the gaussian matrix)
Perform convolution of the loaded input image and the gaussian matrix to get the guassian smoothed image
Perform mean filtering (substitute the intensity of the voxel with the average intesity of the neighbouring voxels)
Compare the image yeilded from the previous step with the smoothed image input image(z_2standard_FWHM)
if the values are +- epsilon away then return True else return False
On Simulation Data -
Not sure | 625941c03c8af77a43ae3701 |
def isReady(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.client.server_info() is not None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return False | see Storage class | 625941c0d6c5a10208143fab |
def is_touch_right(x1,rad): <NEW_LINE> <INDENT> return x1+rad >= 1 | check if disk is touch right side | 625941c04e4d5625662d433d |
def instruction_distributor(self, instructions): <NEW_LINE> <INDENT> print('in1', instructions) <NEW_LINE> instructions = instructions.split('|') <NEW_LINE> print('in2', instructions) <NEW_LINE> function_str = instructions[0] <NEW_LINE> if hasattr(self, function_str): <NEW_LINE> <INDENT> func = getattr(self, function_str) <NEW_LINE> func(instructions[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Invalid instruction') | 指令分发
:param instructions: 客户端发送的指令信息
:return: | 625941c0b545ff76a8913d79 |
def generate_fake_files(format='example_name_%Y%m%dT%H%M%S.tar.bz2', starting=datetime(2016, 2, 8, 9), every=relativedelta(minutes=30), ending=datetime(2015, 12, 25), maxfiles=None): <NEW_LINE> <INDENT> if every.years: <NEW_LINE> <INDENT> ts = datetime(starting.year, 1, 1) <NEW_LINE> <DEDENT> elif every.months: <NEW_LINE> <INDENT> ts = datetime(starting.year, starting.month, 1) <NEW_LINE> <DEDENT> elif every.days: <NEW_LINE> <INDENT> ts = datetime(starting.year, starting.month, starting.day) <NEW_LINE> <DEDENT> elif every.hours: <NEW_LINE> <INDENT> ts = datetime(starting.year, starting.month, starting.day, starting.hour) <NEW_LINE> <DEDENT> elif every.minutes: <NEW_LINE> <INDENT> ts = datetime(starting.year, starting.month, starting.day, starting.hour, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError("not sure what you're trying to do here") <NEW_LINE> <DEDENT> fake_files = [] <NEW_LINE> count = 0 <NEW_LINE> while ending < ts: <NEW_LINE> <INDENT> fake_files.append(ts.strftime(format=format)) <NEW_LINE> count += 1 <NEW_LINE> if maxfiles and maxfiles == 'all' or maxfiles and count >= maxfiles: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> ts -= every <NEW_LINE> <DEDENT> return fake_files | For starting, make sure that it's over a week from the beginning of the month
For every, pick only one of minutes, hours, days, weeks, months or years
For ending, the further away it is from starting, the slower the tests run
Full coverage requires over a year of separation, but that's painfully slow. | 625941c056ac1b37e6264136 |
def flat_map(pvalue, fn, *side_inputs, **options): <NEW_LINE> <INDENT> import bigflow.transform_impls.flat_map <NEW_LINE> return bigflow.transform_impls.flat_map.flat_map(pvalue, fn, *side_inputs, **options) | 对PCollection中的每个元素做一对N映射
对变换函数必须返回一个可遍历变量(即实现了__iter__()方法),将迭代器中的所有元素
构造PCollection
假设输入类型为I,fn的期望签名为 fn(I) => [O...],[]表示返回结果可遍历
Args:
pvalue (PCollection or PObject): 输入P类型
fn (function): 变换函数
*side_inputs: 参与运算的SideInputs
**options: 可配置选项
Results:
PCollection: 变换后的PCollection
>>> from bigflow import transforms
>>> _p = _pipeline.parallelize([1, 3, 5, 7])
>>> transforms.flat_map(_p, lambda x: [x, x * 2]).get()
[1, 2, 3, 5, 6, 7, 10, 14]
>>> transforms.flat_map(_p, lambda x: [[x, x * 2]]).get()
[[1, 2], [3, 6], [5, 10], [7, 14]]
>>> transforms.flat_map(_p, lambda x: (x, x * 2)).get()
[1, 2, 3, 6, 5, 10, 7, 14]
>>> transforms.flat_map(_p, lambda x: [(x, x * 2)]).get()
[(1, 2), (3, 6), (5, 10), (7, 14)]
注意返回结果可以为空:
>>> transforms.flat_map(_p, lambda x: [])
[]
如果返回的对象不能被遍历,则运行时会报错。
典型的错误用法包括None或返回一个单个元素。
返回对象只要是可迭代类型即可,不必一定是list。
特别是,需要输出较多数据时,
使用list可能会导致内存占用过大,
用户可以直接利用python的yield语法生成一个generator,
达到不需要占用大量内存的目的。
>>> _p = _pipeline.parallelize([3, 5])
>>> def make_partial_sum(x):
... sum = 0
... for i in xrange(1, x + 1):
... sum += i
... yield sum
>>> transforms.flat_map(_p, make_partial_sum)
[1, 3, 6, 1, 3, 6, 10, 15]
这种用法可以避免产生大list,从而避免内存占用过大的问题。 | 625941c08e71fb1e9831d70d |
def testBeaconConceptDetail(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | Test BeaconConceptDetail | 625941c0f548e778e58cd4df |
def __init__(self, x, y, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.max_travel_dist = int(self.config.settings['max wall carver travel distance']) <NEW_LINE> self.min_travel_dist = int(self.config.settings['min wall carver travel distance']) <NEW_LINE> self.max_x = int(self.config.settings['width']) <NEW_LINE> self.max_y = int(self.config.settings['height']) <NEW_LINE> self.POSSIBLE_MOVES = [d.Direction.UP, d.Direction.DOWN, d.Direction.LEFT, d.Direction.RIGHT] <NEW_LINE> self.coord = coord_class.Coordinate(x, y) <NEW_LINE> self.get_travel_distance() <NEW_LINE> self.get_direction() <NEW_LINE> self.seen_coords = set([]) <NEW_LINE> self.marked_for_death = False | Initializes the WallCarver class. | 625941c01b99ca400220aa13 |
def _toggle_steno_engine(self, event=None): <NEW_LINE> <INDENT> self.steno_engine.set_is_running(not self.steno_engine.is_running) | Called when the status button is clicked. | 625941c0adb09d7d5db6c6f4 |
def __init__(self, data_root, splits_root, dataset_class, dataset_name, outer_folds, inner_folds, num_workers, pin_memory): <NEW_LINE> <INDENT> self.data_root = data_root <NEW_LINE> self.dataset_class = dataset_class <NEW_LINE> self.dataset_name = dataset_name <NEW_LINE> self.outer_folds = outer_folds <NEW_LINE> self.inner_folds = inner_folds <NEW_LINE> self.outer_k = None <NEW_LINE> self.inner_k = None <NEW_LINE> self.splits_root = splits_root <NEW_LINE> self.splitter = None <NEW_LINE> self.dataset = None <NEW_LINE> self.num_workers = num_workers <NEW_LINE> self.pin_memory = pin_memory | Initializes the object with all the relevant information
:param data_root: the path of the root folder in which data is stored
:param splits_root: the path of the splits folder in which data splits are stored
:param dataset_class: the class of the dataset
:param dataset_name: the name of the dataset
:param outer_folds: the number of outer folds for risk assessment. 1 means hold-out, >1 means k-fold
:param inner_folds: the number of outer folds for model selection. 1 means hold-out, >1 means k-fold
:param num_workers: the number of workers to use in the DataLoader. A value > 0 triggers multiprocessing. Useful to prefetch data from disk to GPU.
:param pin_memory: should be True when working on GPU. | 625941c0cc0a2c11143dcdf3 |
def build_rclick_tree(command_p, rclicks=None, top_level=False): <NEW_LINE> <INDENT> from collections import namedtuple <NEW_LINE> RClick = namedtuple('RClick', 'position,children') <NEW_LINE> if rclicks is None: <NEW_LINE> <INDENT> rclicks = list() <NEW_LINE> <DEDENT> if top_level: <NEW_LINE> <INDENT> if command_p: <NEW_LINE> <INDENT> if '@others' not in command_p.b: <NEW_LINE> <INDENT> rclicks.extend([ RClick(position=i.copy(), children=[]) for i in command_p.children() if i.h.startswith('@rclick ') ]) <NEW_LINE> <DEDENT> for i in command_p.following_siblings(): <NEW_LINE> <INDENT> if i.h.startswith('@rclick '): <NEW_LINE> <INDENT> rclicks.append(RClick(position=i.copy(), children=[])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for rc in rclicks: <NEW_LINE> <INDENT> build_rclick_tree(rc.position, rc.children, top_level=False) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not command_p: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if command_p.b.strip(): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> for child in command_p.children(): <NEW_LINE> <INDENT> rc = RClick(position=child.copy(), children=[]) <NEW_LINE> rclicks.append(rc) <NEW_LINE> build_rclick_tree(rc.position, rc.children, top_level=False) <NEW_LINE> <DEDENT> <DEDENT> return rclicks | Return a list of top level RClicks for the button at command_p, which can be
used later to add the rclick menus.
After building a list of @rclick children and following siblings of the
@button this method applies itself recursively to each member of that list
to handle submenus.
:Parameters:
- `command_p`: node containing @button. May be None
- `rclicks`: list of RClicks to add to, created if needed
- `top_level`: is this the top level? | 625941c00a366e3fb873e77b |
def _validate_and_set_general_data(self, index, requested_value): <NEW_LINE> <INDENT> row = index.row() <NEW_LINE> column = index.column() <NEW_LINE> if column == self.UNIT_PRICE_COLUMN: <NEW_LINE> <INDENT> current_value = self._po_prod_buffer[row].po_product.unit_price <NEW_LINE> converted_requested_value = monetary_float_to_int(requested_value, self.app_config) <NEW_LINE> <DEDENT> elif column == self.DISCOUNT_COLUMN: <NEW_LINE> <INDENT> current_value = self._po_prod_buffer[row].po_product.discount <NEW_LINE> converted_requested_value = monetary_decimal_to_int(requested_value, self.app_config) <NEW_LINE> <DEDENT> elif column == self.QUANTITY_COLUMN: <NEW_LINE> <INDENT> current_value = self._po_prod_buffer[row].po_product.quantity <NEW_LINE> converted_requested_value = int(requested_value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(("Invalid index. Column value {} is not " "considered to be \"general data\".").format( column)) <NEW_LINE> <DEDENT> if current_value != converted_requested_value: <NEW_LINE> <INDENT> if column == self.UNIT_PRICE_COLUMN: <NEW_LINE> <INDENT> self._po_prod_buffer[row].po_product.unit_price = converted_requested_value <NEW_LINE> <DEDENT> elif column == self.DISCOUNT_COLUMN: <NEW_LINE> <INDENT> self._po_prod_buffer[row].po_product.discount = converted_requested_value <NEW_LINE> <DEDENT> elif column == self.QUANTITY_COLUMN: <NEW_LINE> <INDENT> self._po_prod_buffer[row].po_product.quantity = converted_requested_value <NEW_LINE> <DEDENT> self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) | Validate and set data other than the product part number and
description.
The method checks that the requested value is different to the current
value. If it is then the data is set.
Emits the QAbstractTableModel.dataChanged signal if a new, different
value was written.
Args:
:param index: The model index being updated.
:type index: QModelIndex
:param requested_value: The requested value for the field.
:type requested_value: String
Raises:
:raises: ValueError if the index parameter indicates a column that is
not "general data". | 625941c0009cb60464c63316 |
def sanitize_filename(filename): <NEW_LINE> <INDENT> filename = convert_to_unicode(filename) <NEW_LINE> filename = unicodedata.normalize("NFKD", filename) <NEW_LINE> return convert_to_unicode(bytes(c for c in filename.encode("ascii", "ignore") if c in VALID_FILENAME_CHARS)) | Convert given filename to sanitized version. | 625941c0a4f1c619b28affa1 |
def create_render_filter(self, kind, options): <NEW_LINE> <INDENT> if kind not in ['group', 'namespace']: <NEW_LINE> <INDENT> raise UnrecognisedKindError(kind) <NEW_LINE> <DEDENT> filter_options = dict((entry, u'') for entry in self.default_members) <NEW_LINE> filter_options.update(options) <NEW_LINE> if 'members' in filter_options: <NEW_LINE> <INDENT> filter_options['members'] = u'' <NEW_LINE> <DEDENT> node = Node() <NEW_LINE> grandparent = Ancestor(2) <NEW_LINE> has_grandparent = HasAncestorFilter(2) <NEW_LINE> non_class_memberdef = has_grandparent & (grandparent.node_type == 'compounddef') & (grandparent.kind != 'class') & (grandparent.kind != 'struct') & (node.node_type == 'memberdef') <NEW_LINE> return (self.create_class_member_filter(filter_options) | non_class_memberdef) & self.create_innerclass_filter(filter_options) & self.create_outline_filter(filter_options) | Render filter for group & namespace blocks | 625941c024f1403a92600acb |
def get_refunded_payments(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_refunded_payments_with_http_info(**kwargs) | Get a list of refunded payments # noqa: E501
Get a list of refunded payments. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_refunded_payments(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param int limit: Number of returned operations.
:param int offset: Index of the first returned payment operation from all search results.
:param str id: ID of the refund.
:param str payment_id: ID of the payment.
:param datetime occurred_at_gte: Minimum date and time when the refund occurred provided in ISO 8601 format.
:param datetime occurred_at_lte: Maximum date and time when the refund occurred provided in ISO 8601 format.
:param list[str] status: Current status of payment refund.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: object
If the method is called asynchronously,
returns the request thread. | 625941c06e29344779a62577 |
def page(self, reservation_status=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'ReservationStatus': reservation_status, 'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) <NEW_LINE> response = self._version.page(method='GET', uri=self._uri, params=data, ) <NEW_LINE> return ReservationPage(self._version, response, self._solution) | Retrieve a single page of ReservationInstance records from the API.
Request is executed immediately
:param ReservationInstance.Status reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ReservationInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationPage | 625941c0b7558d58953c4e7b |
@blueprint.route('/method', methods=('GET', 'POST')) <NEW_LINE> @flask_login.login_required <NEW_LINE> def method_list(): <NEW_LINE> <INDENT> form_create_method = forms_method.MethodCreate() <NEW_LINE> method = Method.query.all() <NEW_LINE> method_all = MethodData.query.all() <NEW_LINE> return render_template('pages/method-list.html', method=method, method_all=method_all, method_info=METHOD_INFO, form_create_method=form_create_method) | List all methods on one page with a graph for each | 625941c06fb2d068a760effe |
def get_description(self) -> str: <NEW_LINE> <INDENT> return 'Disqus' | Get driver's description.
| 625941c09f2886367277a7f2 |
def fish_count(self): <NEW_LINE> <INDENT> return self.river.fish_count() | :return: number of fishes in river | 625941c063d6d428bbe44452 |
def _get_file(self, repo_type, repo_url, version, filename): <NEW_LINE> <INDENT> name = simplify_repo_name(repo_url) <NEW_LINE> repo_path = os.path.join(self._cache_location, name) <NEW_LINE> client = GitClient(repo_path) <NEW_LINE> updated = False <NEW_LINE> if client.path_exists(): <NEW_LINE> <INDENT> if client.get_url() == repo_url: <NEW_LINE> <INDENT> if not self._skip_update: <NEW_LINE> <INDENT> updated = client.update(version, force_fetch=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> updated = client._do_update(version) <NEW_LINE> <DEDENT> <DEDENT> if not updated: <NEW_LINE> <INDENT> shutil.rmtree(repo_path) <NEW_LINE> <DEDENT> <DEDENT> if not updated: <NEW_LINE> <INDENT> updated = client.checkout(repo_url, version) <NEW_LINE> <DEDENT> if not updated: <NEW_LINE> <INDENT> raise VcsError("Impossible to update/checkout repo '%s' with version '%s'." % (repo_url, version)) <NEW_LINE> <DEDENT> full_filename = os.path.join(repo_path, filename) <NEW_LINE> if not os.path.exists(full_filename): <NEW_LINE> <INDENT> raise VcsError("Requested file '%s' missing from repo '%s' version '%s' (viewed at version '%s'). It was expected at: %s" % (filename, repo_url, version, client.get_version(), full_filename)) <NEW_LINE> <DEDENT> return full_filename | Fetch the file specificed by filename relative to the root of the repository | 625941c066656f66f7cbc10d |
def testRegionStrings(self): <NEW_LINE> <INDENT> self.assertEqual(218, len(list( self.tabix.fetch("chr1")))) <NEW_LINE> self.assertEqual(218, len(list( self.tabix.fetch("chr1", 1000)))) <NEW_LINE> self.assertEqual(218, len(list( self.tabix.fetch("chr1", end=1000000)))) <NEW_LINE> self.assertEqual(218, len(list( self.tabix.fetch("chr1", 1000, 1000000)))) | test if access with various region strings
works | 625941c016aa5153ce3623db |
def test_table_content_init(self): <NEW_LINE> <INDENT> data_obj = self.get_data() <NEW_LINE> expected_data = self.get_test_expected()['test_table_content_init'] <NEW_LINE> table =Table(data_obj['data'], data_obj['headers']) <NEW_LINE> table.style.update(True, False, False) <NEW_LINE> table_str = str(table) <NEW_LINE> table_lines = table_str.split('\n') <NEW_LINE> table_lines = table_lines[3:] <NEW_LINE> for exp_line, exp_content in expected_data.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> index = int(exp_line) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.fail(f"Error in expected test data. Expected a `int` as key, found: {exp_line}") <NEW_LINE> <DEDENT> for exp_data in exp_content: <NEW_LINE> <INDENT> self.assertTrue(str(exp_data) in table_lines[index]) | Test printed table content | 625941c04d74a7450ccd4126 |
def yyyy_mm(yyyy_mm_dd: Union[str, datetime.date]) -> str: <NEW_LINE> <INDENT> date, _ = _parse(yyyy_mm_dd, at_least="%Y-%m") <NEW_LINE> return date.strftime("%Y-%m") | Extracts the year and month of a given date
>>> yyyy_mm('2020-05-14')
'2020-05'
>>> yyyy_mm(datetime.date(2020, 5, 14))
'2020-05' | 625941c04f6381625f11499f |
def __init__(self, name, watch_daemon=True, singleton=True): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._namewatch = None <NEW_LINE> self._watch_daemon = watch_daemon <NEW_LINE> self._loop = glib.MainLoop() <NEW_LINE> self._conn = dbus.SessionBus(mainloop=DBusGMainLoop()) <NEW_LINE> self._bus_names = [] <NEW_LINE> try: <NEW_LINE> <INDENT> self.request_bus_name(APP_BUS_PREFIX + name, singleton) <NEW_LINE> <DEDENT> except dbus.NameExistsException: <NEW_LINE> <INDENT> raise AlreadyRunningException( 'Process with bus name %s is already running' % ( APP_BUS_PREFIX + name)) <NEW_LINE> <DEDENT> self._parse_options() | Arguments:
- `name`: The suffix of the bus name. The full bus name is
`org.osdlyrics.` + name
- `watch_daemon`: Whether to watch daemon bus
- `singleton`: If True, raise AlreadyRunningException if the bus name
already has an owner. | 625941c0cad5886f8bd26f3d |
def parser(self): <NEW_LINE> <INDENT> if self.email or self.urls: <NEW_LINE> <INDENT> r = get(self.url).text <NEW_LINE> soup = bs(r, 'lxml') <NEW_LINE> <DEDENT> if self.email: <NEW_LINE> <INDENT> print('\nEMAILS IN URL:', self.url) <NEW_LINE> for email in re.findall(r'[\w.-]+\@[\w.-]+', soup.text): <NEW_LINE> <INDENT> if email not in self.unique_emails: <NEW_LINE> <INDENT> self.unique_emails.append(email) <NEW_LINE> print(' ', email) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.urls: <NEW_LINE> <INDENT> print('\nURLS IN URL: ', self.url) <NEW_LINE> for links in soup.find_all('a'): <NEW_LINE> <INDENT> with suppress(TypeError): <NEW_LINE> <INDENT> link = links.get('href') <NEW_LINE> if '/' in link and '.pdf' not in link: <NEW_LINE> <INDENT> if link.startswith('/'): <NEW_LINE> <INDENT> print(' ', f'{self.base}{link}') <NEW_LINE> <DEDENT> elif 'RouteMap' in link: <NEW_LINE> <INDENT> print(f' {self.base}/{link}') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(f' {link}') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if self.save and self.email: <NEW_LINE> <INDENT> file_name = self.save + '.txt' <NEW_LINE> with open(file_name, 'w') as file: <NEW_LINE> <INDENT> for i in self.unique_emails: <NEW_LINE> <INDENT> file.write(i+'\n') | Find email and urls
| 625941c0bd1bec0571d90592 |
def create_directory(Name=None, ShortName=None, Password=None, Description=None, Size=None, VpcSettings=None, Tags=None): <NEW_LINE> <INDENT> pass | Creates a Simple AD directory. For more information, see Simple Active Directory in the AWS Directory Service Admin Guide .
Before you call CreateDirectory , ensure that all of the required permissions have been explicitly granted through a policy. For details about what permissions are required to run the CreateDirectory operation, see AWS Directory Service API Permissions: Actions, Resources, and Conditions Reference .
See also: AWS API Documentation
Exceptions
:example: response = client.create_directory(
Name='string',
ShortName='string',
Password='string',
Description='string',
Size='Small'|'Large',
VpcSettings={
'VpcId': 'string',
'SubnetIds': [
'string',
]
},
Tags=[
{
'Key': 'string',
'Value': 'string'
},
]
)
:type Name: string
:param Name: [REQUIRED]
The fully qualified name for the directory, such as corp.example.com .
:type ShortName: string
:param ShortName: The NetBIOS name of the directory, such as CORP .
:type Password: string
:param Password: [REQUIRED]
The password for the directory administrator. The directory creation process creates a directory administrator account with the user name Administrator and this password.
If you need to change the password for the administrator account, you can use the ResetUserPassword API call.
:type Description: string
:param Description: A description for the directory.
:type Size: string
:param Size: [REQUIRED]
The size of the directory.
:type VpcSettings: dict
:param VpcSettings: A DirectoryVpcSettings object that contains additional information for the operation.
VpcId (string) -- [REQUIRED]The identifier of the VPC in which to create the directory.
SubnetIds (list) -- [REQUIRED]The identifiers of the subnets for the directory servers. The two subnets must be in different Availability Zones. AWS Directory Service creates a directory server and a DNS server in each of these subnets.
(string) --
:type Tags: list
:param Tags: The tags to be assigned to the Simple AD directory.
(dict) --Metadata assigned to a directory consisting of a key-value pair.
Key (string) -- [REQUIRED]Required name of the tag. The string value can be Unicode characters and cannot be prefixed with 'aws:'. The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\p{L}\p{Z}\p{N}_.:/=+\-]*)$').
Value (string) -- [REQUIRED]The optional value of the tag. The string value can be Unicode characters. The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\p{L}\p{Z}\p{N}_.:/=+\-]*)$').
:rtype: dict
ReturnsResponse Syntax
{
'DirectoryId': 'string'
}
Response Structure
(dict) --
Contains the results of the CreateDirectory operation.
DirectoryId (string) --
The identifier of the directory that was created.
Exceptions
DirectoryService.Client.exceptions.DirectoryLimitExceededException
DirectoryService.Client.exceptions.InvalidParameterException
DirectoryService.Client.exceptions.ClientException
DirectoryService.Client.exceptions.ServiceException
:return: {
'DirectoryId': 'string'
}
:returns:
DirectoryService.Client.exceptions.DirectoryLimitExceededException
DirectoryService.Client.exceptions.InvalidParameterException
DirectoryService.Client.exceptions.ClientException
DirectoryService.Client.exceptions.ServiceException
| 625941c0fbf16365ca6f6122 |
def inject_indent(self): <NEW_LINE> <INDENT> return (" " * 4) * self.tab_depth | Calculate the spaces required for the current indentation level
Return (str): n number of spaces | 625941c04f88993c3716bfcd |
def test_instance_method(self): <NEW_LINE> <INDENT> class Qux: <NEW_LINE> <INDENT> @validate(object, int, int, float) <NEW_LINE> def foo(obj, x, y, z): <NEW_LINE> <INDENT> self.assertIsInstance(obj, Qux) <NEW_LINE> <DEDENT> @parse(None, float, float, float) <NEW_LINE> def bar(obj, x, y, z): <NEW_LINE> <INDENT> self.assertIsInstance(obj, Qux) <NEW_LINE> <DEDENT> <DEDENT> Qux().foo(1, 1, 2.0) <NEW_LINE> Qux().bar(1, 1, 1) <NEW_LINE> Qux.foo(Qux(), 1, 1, 2.0) <NEW_LINE> Qux.bar(Qux(), 1, 1, 1) | Test if decorators can decorate instance methods.
:return: | 625941c0236d856c2ad4473a |
def as_gpconstr(self, x0): <NEW_LINE> <INDENT> gpconstrs = [constr.as_gpconstr(x0) for constr in self] <NEW_LINE> return ConstraintSet(gpconstrs, self.substitutions, recursesubs=False) | Returns GPConstraint approximating this constraint at x0
When x0 is none, may return a default guess. | 625941c021a7993f00bc7c4f |
def exist_line(self, number): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if(self.line.index(number) >= 0): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False | Test if the number of the line is in the list | 625941c0097d151d1a222dbf |
def computer_random(): <NEW_LINE> <INDENT> comp_no = random.sample(range(1, 59), 6) <NEW_LINE> return comp_no | let the computer create a list of 6 unique random integers from 1 to 59 | 625941c0c4546d3d9de72995 |
def ex_pulsar_search0(): <NEW_LINE> <INDENT> return rf_pipelines.chime_stream_from_times('/data2/17-02-08-incoherent-data-avalanche/frb_incoherent_search_0', 143897.510543, 144112.258908) | Example: a pulsar in an incoherent-beam acquisition (1K freq) | 625941c067a9b606de4a7e1e |
def get_download_link(self, obj): <NEW_LINE> <INDENT> if getattr(obj, 'file_id', None): <NEW_LINE> <INDENT> submission_file = OsfStorageFile.objects.get(id=obj.file_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> submission_file = self.get_submission_file(obj) <NEW_LINE> <DEDENT> if submission_file: <NEW_LINE> <INDENT> return get_file_download_link(submission_file) <NEW_LINE> <DEDENT> return None | First osfstoragefile on a node - if the node was created for a meeting,
assuming its first file is the meeting submission. | 625941c0d18da76e23532437 |
def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False): <NEW_LINE> <INDENT> if mode not in ("r", "w", "a"): <NEW_LINE> <INDENT> raise RuntimeError('ZipFile() requires mode "r", "w", or "a"') <NEW_LINE> <DEDENT> if compression == ZIP_STORED: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif compression == ZIP_DEFLATED: <NEW_LINE> <INDENT> if not zlib: <NEW_LINE> <INDENT> raise RuntimeError( "Compression requires the (missing) zlib module") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError("That compression method is not supported") <NEW_LINE> <DEDENT> self._allowZip64 = allowZip64 <NEW_LINE> self._didModify = False <NEW_LINE> self.debug = 0 <NEW_LINE> self.NameToInfo = {} <NEW_LINE> self.filelist = [] <NEW_LINE> self.compression = compression <NEW_LINE> self.mode = key = mode.replace('b', '')[0] <NEW_LINE> self.pwd = None <NEW_LINE> self.comment = b'' <NEW_LINE> if isinstance(file, str): <NEW_LINE> <INDENT> self._filePassed = 0 <NEW_LINE> self.filename = file <NEW_LINE> modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} <NEW_LINE> try: <NEW_LINE> <INDENT> self.fp = io.open(file, modeDict[mode]) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> if mode == 'a': <NEW_LINE> <INDENT> mode = key = 'w' <NEW_LINE> self.fp = io.open(file, modeDict[mode]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._filePassed = 1 <NEW_LINE> self.fp = file <NEW_LINE> self.filename = getattr(file, 'name', None) <NEW_LINE> <DEDENT> if key == 'r': <NEW_LINE> <INDENT> self._GetContents() <NEW_LINE> <DEDENT> elif key == 'w': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif key == 'a': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._RealGetContents() <NEW_LINE> self.fp.seek(self.start_dir, 0) <NEW_LINE> <DEDENT> except BadZipfile: <NEW_LINE> <INDENT> self.fp.seek(0, 2) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not self._filePassed: <NEW_LINE> <INDENT> self.fp.close() <NEW_LINE> self.fp = None <NEW_LINE> <DEDENT> raise RuntimeError('Mode must be "r", "w" or "a"') | Open the ZIP file with mode read "r", write "w" or append "a". | 625941c0a17c0f6771cbdfb6 |
def signup(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> username = request.POST['username'] <NEW_LINE> passwd = request.POST['passwd'] <NEW_LINE> passwd_confirmation = request.POST['passwd_confirmation'] <NEW_LINE> if passwd != passwd_confirmation: <NEW_LINE> <INDENT> return render(request, 'signup.html', {'error': 'Password confirmation does not match'}) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> user = User.objects.create_user(username=username, password=passwd) <NEW_LINE> <DEDENT> except IntegrityError: <NEW_LINE> <INDENT> return render(request, 'signup.html', {'error': 'Username is already in user'}) <NEW_LINE> <DEDENT> user.first_name = request.POST['first_name'] <NEW_LINE> user.last_name = request.POST['last_name'] <NEW_LINE> user.email = request.POST['email'] <NEW_LINE> user.save() <NEW_LINE> profile = Profile(user=user) <NEW_LINE> profile.save() <NEW_LINE> if user: <NEW_LINE> <INDENT> login(request, user) <NEW_LINE> return redirect('posts_list') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return render(request, 'login.html', {'error': 'Invalid username and password'}) <NEW_LINE> <DEDENT> <DEDENT> return render(request, 'signup.html') | Sign up view. | 625941c01f037a2d8b946162 |
def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> self.searching_player = game.active_player <NEW_LINE> return self.alphabeta_score(game, depth - 1, alpha, beta, True, True) | Implement depth-limited minimax search with alpha-beta pruning as
described in the lectures.
This should be a modified version of ALPHA-BETA-SEARCH in the AIMA text
https://github.com/aimacode/aima-pseudocode/blob/master/md/Alpha-Beta-Search.md
**********************************************************************
You MAY add additional methods to this class, or define helper
functions to implement the required functionality.
**********************************************************************
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
alpha : float
Alpha limits the lower bound of search on minimizing layers
beta : float
Beta limits the upper bound of search on maximizing layers
Returns
-------
(int, int)
The board coordinates of the best move found in the current search;
(-1, -1) if there are no legal moves
Notes
-----
(1) You MUST use the `self.score()` method for board evaluation
to pass the project tests; you cannot call any other evaluation
function directly.
(2) If you use any helper functions (e.g., as shown in the AIMA
pseudocode) then you must copy the timer check into the top of
each helper function or else your agent will timeout during
testing. | 625941c0ff9c53063f47c158 |
def obtain_image(img, Cnt=None, imtype=''): <NEW_LINE> <INDENT> output = {} <NEW_LINE> if isinstance(img, dict): <NEW_LINE> <INDENT> if Cnt is not None and img['im'].shape != (Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']): <NEW_LINE> <INDENT> log.error('provided ' + imtype + ' via the dictionary has inconsistent dimensions compared to Cnt.') <NEW_LINE> raise ValueError('Wrong dimensions of the mu-map') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output['im'] = img['im'] <NEW_LINE> output['exists'] = True <NEW_LINE> if 'fim' in img: output['fim'] = img['fim'] <NEW_LINE> if 'faff' in img: output['faff'] = img['faff'] <NEW_LINE> if 'fmuref' in img: output['fmuref'] = img['fmuref'] <NEW_LINE> if 'affine' in img: output['affine'] = img['affine'] <NEW_LINE> log.info('using ' + imtype + ' from dictionary') <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(img, (np.ndarray, np.generic)): <NEW_LINE> <INDENT> if Cnt is not None and img.shape != (Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']): <NEW_LINE> <INDENT> log.error('provided ' + imtype + ' via the numpy array has inconsistent dimensions compared to Cnt.') <NEW_LINE> raise ValueError('Wrong dimensions of the mu-map') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output['im'] = img <NEW_LINE> output['exists'] = True <NEW_LINE> output['fim'] = '' <NEW_LINE> log.info('using hardware mu-map from numpy array.') <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(img, str): <NEW_LINE> <INDENT> if os.path.isfile(img): <NEW_LINE> <INDENT> imdct = nimpa.getnii(img, output='all') <NEW_LINE> output['im'] = imdct['im'] <NEW_LINE> output['affine'] = imdct['affine'] <NEW_LINE> if Cnt and output['im'].shape != (Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']): <NEW_LINE> <INDENT> log.error('provided ' + imtype + ' via file has inconsistent dimensions compared to Cnt.') <NEW_LINE> raise ValueError('Wrong dimensions of the mu-map') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output['exists'] = True <NEW_LINE> output['fim'] = img <NEW_LINE> log.info('using ' + imtype + ' from NIfTI file.') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> log.error('provided ' + imtype + ' path is invalid.') <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(img, list): <NEW_LINE> <INDENT> output['im'] = np.zeros((Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']), dtype=np.float32) <NEW_LINE> log.info(imtype + ' has not been provided -> using blank.') <NEW_LINE> output['fim'] = '' <NEW_LINE> output['exists'] = False <NEW_LINE> <DEDENT> return output | Obtain the image (hardware or object mu-map) from file,
numpy array, dictionary or empty list (assuming blank then).
The image has to have the dimensions of the PET image used as in Cnt['SO_IM[X-Z]']. | 625941c044b2445a33931ffa |
def __repr__(self): <NEW_LINE> <INDENT> return "{}({}, {})".format(self.__class__.__name__, self._x, self._y) | Method providing the 'official' string representation of the object.
It provides a valid expression that could be used to recreate the
object.
:returns: As string with a valid expression to recreate the object
:rtype: string
>>> i = Interpolation([5, 3, 6, 1, 2, 4, 9], [10, 6, 12, 2, 4, 8])
>>> repr(i)
'Interpolation([1, 2, 3, 4, 5, 6], [2, 4, 6, 8, 10, 12])' | 625941c067a9b606de4a7e1f |
def GetNumberOfObjects(self): <NEW_LINE> <INDENT> return _itkBinaryStatisticsKeepNObjectsImageFilterPython.itkBinaryStatisticsKeepNObjectsImageFilterIUS2IUL2_GetNumberOfObjects(self) | GetNumberOfObjects(self) -> unsigned long | 625941c0925a0f43d2549dd8 |
def fit(train_data): <NEW_LINE> <INDENT> from sklearn.impute import SimpleImputer <NEW_LINE> logging.info("Fitting imputer for missing values") <NEW_LINE> data = train_data.drop(["median_house_value", "ocean_proximity"], axis=1).copy() <NEW_LINE> imputer = SimpleImputer(strategy="median").fit(data) <NEW_LINE> logging.info("Creating pickle file for Imputer") <NEW_LINE> os.makedirs(os.path.dirname(PKL_IMPUTER), exist_ok=True) <NEW_LINE> with open(PKL_IMPUTER, "wb") as file: <NEW_LINE> <INDENT> pickle.dump(imputer, file) | Fit the missing value imputer on train data
Args:
train_data (pd.DataFrame): training data | 625941c021bff66bcd6848b8 |
def send_push_notification(self, message, url=None, badge_count=None, sound=None, extra=None, category=None, **kwargs): <NEW_LINE> <INDENT> from .handlers import SNSHandler <NEW_LINE> if self.deleted_at: <NEW_LINE> <INDENT> raise DeviceIsNotActive <NEW_LINE> <DEDENT> message = self.prepare_message(message) <NEW_LINE> handler = SNSHandler(device=self) <NEW_LINE> message_payload, response = handler.send_push_notification(message, url, badge_count, sound, extra, category, **kwargs) <NEW_LINE> if DJANGO_SLOOP_SETTINGS["LOG_SENT_MESSAGES"]: <NEW_LINE> <INDENT> PushMessage.objects.create( device=self, body=message, data=message_payload, sns_message_id=response.get("MessageId") or None, sns_response=json.dumps(response) ) <NEW_LINE> <DEDENT> return response | Sends push message using device push token | 625941c04527f215b584c3bd |
def select_face(faces: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> idx = 0 <NEW_LINE> if len(faces) > 1: <NEW_LINE> <INDENT> for i in range(len(faces)): <NEW_LINE> <INDENT> if (faces[idx][2] * faces[idx][3]) < (faces[i][2] * faces[i][3]): <NEW_LINE> <INDENT> idx = i <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return faces[idx] | Selects the biggest face of 'faces'.
Chooses the one with the biggest area.
Parameters:
faces (np.ndarray): Array with the faces.
Returns:
np.ndarray: Biggest face. | 625941c0baa26c4b54cb1085 |
def parse_model_config(path): <NEW_LINE> <INDENT> file = open(path, 'r') <NEW_LINE> lines = file.read().split('\n') <NEW_LINE> lines = [x for x in lines if x and not x.startswith('#')] <NEW_LINE> lines = [x.rstrip().lstrip() for x in lines] <NEW_LINE> module_defs = [] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if line.startswith('#'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif line.startswith('['): <NEW_LINE> <INDENT> module_defs.append({}) <NEW_LINE> module_defs[-1]['type'] = line[1:-1].rstrip() <NEW_LINE> if module_defs[-1]['type'] == 'convolutional': <NEW_LINE> <INDENT> module_defs[-1]['batch_normalize'] = 0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> key, value = line.split("=") <NEW_LINE> value = value.strip() <NEW_LINE> module_defs[-1][key.rstrip()] = value <NEW_LINE> <DEDENT> <DEDENT> return module_defs | Parses the layer configuration file and returns module definitions | 625941c07b180e01f3dc4765 |
def test_add_user_to_workspace(self): <NEW_LINE> <INDENT> self.login_as_portal_owner() <NEW_LINE> ws = self._create_workspace() <NEW_LINE> user = self._create_user() <NEW_LINE> ws.add_to_team(user=user.getId()) <NEW_LINE> self.assertIn(user.getId(), [x for x in list(ws.members)]) | check that we can add a new user to a workspace | 625941c0eab8aa0e5d26dabb |
def test_bucket_get_not_found(self): <NEW_LINE> <INDENT> mock_error = requests.HTTPError() <NEW_LINE> mock_error.response = mock.Mock() <NEW_LINE> mock_error.response.status_code = 404 <NEW_LINE> self.mock_request.side_effect = mock_error <NEW_LINE> bucket = self.client.bucket_get('inexistent') <NEW_LINE> self.mock_request.assert_called_once_with( method='GET', path='/buckets/inexistent') <NEW_LINE> assert bucket is None | Test Client.bucket_get() when bucket does not exist. | 625941c04c3428357757c28d |
def create(self, validated_data): <NEW_LINE> <INDENT> return user_review.objects.create(**validated_data) | Create and return a new `book_review` instance, given the validated data. | 625941c0cc0a2c11143dcdf4 |
def icdf(self, x): <NEW_LINE> <INDENT> raise RuntimeError( 'Cumulative distribution function for multivariate variable ' 'is not invertible.') | Cumulative distribution function for multivariate variable is not
invertible. This function always raises :class:`RuntimeError`.
Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`): Data points in
the codomain of the distribution
Raises:
:class:`RuntimeError` | 625941c06fece00bbac2d6a0 |
def populate_sell_trend(self, dataframe: DataFrame) -> DataFrame: <NEW_LINE> <INDENT> dataframe.loc[ ( (dataframe['macd'] < dataframe['macdsignal']) & (dataframe['cci'] >= 100) ), 'sell'] = 1 <NEW_LINE> return dataframe | Based on TA indicators, populates the sell signal for the given dataframe
:param dataframe: DataFrame
:return: DataFrame with buy column | 625941c06fece00bbac2d6a1 |
def validate(request): <NEW_LINE> <INDENT> upload = request.files.get('upload', None) <NEW_LINE> if upload is None: <NEW_LINE> <INDENT> return {'upload': "PDF file is required"} <NEW_LINE> <DEDENT> name, ext = os.path.splitext(upload.filename) <NEW_LINE> if ext not in '.pdf' or not ext: <NEW_LINE> <INDENT> return {'upload': "Supported format for this request is PDF"} | The validate method will validate the incoming request against the request parameters
:param request:
:return: dictionary | 625941c0293b9510aa2c31fc |
def read_all(self, num_samples_1, num_samples_2): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for name, s in zip(self.physical_channel, [num_samples_1, num_samples_2]): <NEW_LINE> <INDENT> data.append(self.read_counter(name, num_samples=s)) <NEW_LINE> <DEDENT> return data | Read all counters from the physical channels dict | 625941c0cb5e8a47e48b7a11 |
def get_training_dataset(): <NEW_LINE> <INDENT> dataset = [[-1, 1, 1, 1], [-1, 0, 0, 0], [-1, 1, 0, 0], [-1, 0, 1, 0]] <NEW_LINE> return dataset | 基于and真值表构建训练数据 | 625941c097e22403b379cefd |
def src_inverse(self, src_cvs, src_cvs_KL): <NEW_LINE> <INDENT> self.src_icvs = np.zeros(src_cvs.shape) <NEW_LINE> for i in range(src_cvs.shape[0]): <NEW_LINE> <INDENT> self.src_icvs[i] = np.linalg.inv(src_cvs[i]) <NEW_LINE> <DEDENT> self.src_icvs_KL = np.zeros(src_cvs_KL.shape) <NEW_LINE> for i in range(src_cvs_KL.shape[0]): <NEW_LINE> <INDENT> self.src_icvs_KL[i] = np.linalg.inv(src_cvs_KL[i]) <NEW_LINE> <DEDENT> pass | TODO | 625941c021a7993f00bc7c50 |
def __init__(self, n_rows, n_cols): <NEW_LINE> <INDENT> self.dict = {} <NEW_LINE> self.n_rows = n_rows <NEW_LINE> self.n_cols = n_cols <NEW_LINE> self.endIdx = n_rows * n_cols - 1 | :type n_rows: int
:type n_cols: int | 625941c03317a56b86939bc1 |
def two_time_state_to_results(state): <NEW_LINE> <INDENT> for q in range(np.max(state.label_array)): <NEW_LINE> <INDENT> x0 = (state.g2)[q, :, :] <NEW_LINE> (state.g2)[q, :, :] = (np.tril(x0) + np.tril(x0).T - np.diag(np.diag(x0))) <NEW_LINE> <DEDENT> return results(state.g2, state.lag_steps, state) | Convert the internal state of the two time generator into usable results
Parameters
----------
state : namedtuple
The internal state that is yielded from `lazy_two_time`
Returns
-------
results : namedtuple
A results object that contains the two time correlation results
and the lag steps | 625941c0d268445f265b4dd2 |
@task(default=True) <NEW_LINE> def test(args=None): <NEW_LINE> <INDENT> default_args = "-sv --with-doctest --nologcapture --with-color" <NEW_LINE> default_args += (" " + args) if args else "" <NEW_LINE> try: <NEW_LINE> <INDENT> nose.core.run(argv=[''] + default_args.split()) <NEW_LINE> <DEDENT> except SystemExit: <NEW_LINE> <INDENT> abort("Nose encountered an error; you may be missing newly added test dependencies. Try running 'pip install -r requirements.txt'.") | Run all unit tests and doctests.
Specify string argument ``args`` for additional args to ``nosetests``. | 625941c0d10714528d5ffc44 |
def validate_coords(coords): <NEW_LINE> <INDENT> X,Y,Z = [np.asarray(coords[i]) for i in range(3)] <NEW_LINE> return X,Y,Z | Convert coords into a tuple of ndarrays | 625941c060cbc95b062c64a6 |
def cmd_opmode_rmpwfm(self, timeout=_TIMEOUT_OPMODE_CHANGE): <NEW_LINE> <INDENT> return self._command_all('OpMode-Sel', _PSConst.OpMode.RmpWfm, desired_readback=_PSConst.States.RmpWfm, timeout=timeout) | Select RmpWfm opmode for all power supplies. | 625941c015baa723493c3ed7 |
def FinishTransaction(self, commit): <NEW_LINE> <INDENT> raise Exception(str(self) + ": Method not implemented") | Commit or rollback the transaction | 625941c0d10714528d5ffc45 |
def heartbeat_tick(self, rate=2): <NEW_LINE> <INDENT> if not self.heartbeat: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> sent_now = self.method_writer.bytes_sent <NEW_LINE> recv_now = self.method_reader.bytes_recv <NEW_LINE> if self.prev_sent is None or self.prev_sent != sent_now: <NEW_LINE> <INDENT> self.last_heartbeat_sent = monotonic() <NEW_LINE> <DEDENT> if self.prev_recv is None or self.prev_recv != recv_now: <NEW_LINE> <INDENT> self.last_heartbeat_received = monotonic() <NEW_LINE> <DEDENT> self.prev_sent, self.prev_recv = sent_now, recv_now <NEW_LINE> if monotonic() > self.last_heartbeat_sent + self.heartbeat: <NEW_LINE> <INDENT> self.send_heartbeat() <NEW_LINE> self.last_heartbeat_sent = monotonic() <NEW_LINE> <DEDENT> if (self.last_heartbeat_received and self.last_heartbeat_received + 2 * self.heartbeat < monotonic()): <NEW_LINE> <INDENT> raise ConnectionForced('Too many heartbeats missed') | Send heartbeat packets, if necessary, and fail if none have been
received recently. This should be called frequently, on the order of
once per second.
:keyword rate: Ignored | 625941c05fcc89381b1e1621 |
def create_resource(self, namespace: "str" = None) -> "DaemonSetStatus": <NEW_LINE> <INDENT> names = ["create_namespaced_daemon_set", "create_daemon_set"] <NEW_LINE> response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) <NEW_LINE> output = DaemonSetStatus() <NEW_LINE> if response is not None: <NEW_LINE> <INDENT> output.from_dict(_kube_api.to_kuber_dict(response.status)) <NEW_LINE> <DEDENT> return output | Creates the DaemonSet in the currently
configured Kubernetes cluster and returns the status information
returned by the Kubernetes API after the create is complete. | 625941c056b00c62f0f145bc |
def is_connected(self): <NEW_LINE> <INDENT> return self._writer is not None and not self._writer.is_closing() | Return `True` if connection is established.
This does not check if the connection is still usable.
Returns:
bool | 625941c0b57a9660fec337e5 |
@task <NEW_LINE> def bootstrap_standby(cluster): <NEW_LINE> <INDENT> install_dir = cluster.get_hadoop_install_dir() <NEW_LINE> get_logger().info("Bootstrapping standby NameNode: {}".format(env.host_string)) <NEW_LINE> cmd = '{}/bin/hdfs namenode -bootstrapstandby'.format(install_dir) <NEW_LINE> return sudo(cmd, user=constants.HDFS_USER).succeeded | Bootstraps a standby NameNode | 625941c0be383301e01b53ee |
def _get_fns_from_datadir(self): <NEW_LINE> <INDENT> self._clufiles = self._parse_KK_files( glob.glob(os.path.join(self._data_dir, '*.clu.*')), 'clu') <NEW_LINE> self._fetfiles = self._parse_KK_files( glob.glob(os.path.join(self._data_dir, '*.fet.*')), 'fet') | Stores dicts of KlustaKwik *.clu and *.fet files from directory. | 625941c063b5f9789fde7049 |
def refine(img, corner): <NEW_LINE> <INDENT> corner_new = np.ones((1, 1, 2), np.float32) <NEW_LINE> corner_new[0][0] = corner[0][0][0], corner[0][0][1] <NEW_LINE> criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) <NEW_LINE> cv2.cornerSubPix(img, corner_new, (40, 40), (-1, -1), criteria) <NEW_LINE> return corner_new | Refine the corner location. | 625941c03cc13d1c6d3c72df |
def Parse(self, parser_mediator, **kwargs): <NEW_LINE> <INDENT> display_name = parser_mediator.GetDisplayName() <NEW_LINE> if not self._CheckSignature(parser_mediator): <NEW_LINE> <INDENT> raise errors.UnableToParseFile(( u'[{0:s}] unable to parse file: {1:s} with error: invalid ' u'signature.').format(self.NAME, display_name)) <NEW_LINE> <DEDENT> file_entry = parser_mediator.GetFileEntry() <NEW_LINE> try: <NEW_LINE> <INDENT> winreg_file = self._win_registry.OpenFileEntry( file_entry, codepage=parser_mediator.codepage) <NEW_LINE> <DEDENT> except IOError as exception: <NEW_LINE> <INDENT> raise errors.UnableToParseFile( u'[{0:s}] unable to parse file: {1:s} with error: {2:s}'.format( self.NAME, display_name, exception)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> registry_file_type = self._win_registry.GetRegistryFileType(winreg_file) <NEW_LINE> logging.debug( u'Windows Registry file {0:s}: detected as: {1:s}'.format( display_name, registry_file_type)) <NEW_LINE> self._ParseRegistryFile(parser_mediator, winreg_file, registry_file_type) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> winreg_file.Close() | Parses a Windows Registry file.
Args:
parser_mediator: A parser mediator object (instance of ParserMediator). | 625941c066656f66f7cbc10e |
def meniu_utilizator(): <NEW_LINE> <INDENT> print(' ') <NEW_LINE> print('1. Adaugare utilizator') <NEW_LINE> print('2. Actualizare nume utilizator') <NEW_LINE> print('3. Stergere utilizator') <NEW_LINE> print('4. Afisare optiuni') <NEW_LINE> print('5. Iesire din meniu') <NEW_LINE> print(' ') <NEW_LINE> opt = input('Alegeti o optiune: ') <NEW_LINE> while opt < '1' or opt > '5': <NEW_LINE> <INDENT> print('Optiunea aleasa nu exista\n') <NEW_LINE> opt = input('Alegeti o optiune: ') <NEW_LINE> <DEDENT> while '5': <NEW_LINE> <INDENT> if opt == '1': <NEW_LINE> <INDENT> ID = input('ID utilizator: ') <NEW_LINE> nume = input('Nume: ') <NEW_LINE> prenume = input('Prenume:') <NEW_LINE> nr_filme = int(input('Cate filme are deja comandate: ')) <NEW_LINE> comanda = [] <NEW_LINE> while nr_filme < 0: <NEW_LINE> <INDENT> nr_filme = int(input('Introudceti un numar de filme deja comandate valid: ')) <NEW_LINE> <DEDENT> for i in range(nr_filme): <NEW_LINE> <INDENT> cmd = int(input('ID film: ')) <NEW_LINE> comanda.append(cmd) <NEW_LINE> <DEDENT> U = Utilizator(ID, nume, prenume, comanda) <NEW_LINE> utilizator_control.add_utilizator(U) <NEW_LINE> <DEDENT> if opt == '2': <NEW_LINE> <INDENT> ID = int(input('ID utilizator: ')) <NEW_LINE> nume_nou = input('Numele nou: ') <NEW_LINE> if utilizator_control.update_utilizator(ID, nume_nou) == 1: <NEW_LINE> <INDENT> print('Nume actualizat') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Utilizatorul nu exista') <NEW_LINE> <DEDENT> <DEDENT> if opt == '3': <NEW_LINE> <INDENT> ID = int(input('ID utilizator: ')) <NEW_LINE> if (utilizator_control.del_utilizator(ID) == 1): <NEW_LINE> <INDENT> print('Utilizator sters.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Utilizatorul nu exista') <NEW_LINE> <DEDENT> <DEDENT> if opt == '4': <NEW_LINE> <INDENT> print(' ') <NEW_LINE> print('1. Adaugare utilizator') <NEW_LINE> print('2. Actualizare nume utilizator') <NEW_LINE> print('3. Stergere utilizator') <NEW_LINE> print('4. Afisare optiuni') <NEW_LINE> print('5. Iesire din meniu') <NEW_LINE> <DEDENT> if opt == '5': <NEW_LINE> <INDENT> main() <NEW_LINE> <DEDENT> print(' ') <NEW_LINE> opt = input('Alegeti o optiune: ') <NEW_LINE> while opt < '1' or opt > '5': <NEW_LINE> <INDENT> print('Optiunea aleasa nu exista\n') <NEW_LINE> opt = input('Alegeti o optiune: ') <NEW_LINE> <DEDENT> print(' ') | Meniul are 5 optiuni numerotate de la 1 la 5. Daca optiunea aleasa
nu exista se va afisa un mesaj de eroare si se va introduce o noua optiune
pana la alegerea optiunii 5 | 625941c026238365f5f0edcf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.