code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _transform(self): <NEW_LINE> <INDENT> np.clip(self._W, 0, self.v_max, out=self._W) <NEW_LINE> sumsq = np.sqrt(np.einsum('ij,ij->j', self._W, self._W)) <NEW_LINE> np.maximum(sumsq, 1, out=sumsq) <NEW_LINE> self._W /= sumsq | Apply boundaries on W. | 625941c057b8e32f524833e9 |
def filter_page_size(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> page_size = fields.IntegerField().from_native(value) <NEW_LINE> <DEDENT> except fields.ValidationError: <NEW_LINE> <INDENT> page_size = 20 <NEW_LINE> <DEDENT> if not (1 <= page_size < 100): <NEW_LINE> <INDENT> page_size = 100 <NEW_LINE> <DEDENT> self.query_values['page_size'] = page_size <NEW_LINE> return F() | Validate the page sizes, but don't return any filters. | 625941c03346ee7daa2b2cba |
def softmax_loss_vectorized(W, X, y, reg): <NEW_LINE> <INDENT> N = X.shape[0] <NEW_LINE> f = X.dot(W) <NEW_LINE> f -= np.max(f) <NEW_LINE> ENs = np.exp(f) <NEW_LINE> denoms = np.sum(ENs, axis=1) <NEW_LINE> f_y = f[np.arange(N), y] <NEW_LINE> loss = np.sum(-f_y) + np.sum(np.log(denoms)) <NEW_LINE> probs = ENs / denoms[:, np.newaxis] <NEW_LINE> indicator = np.zeros(probs.shape) <NEW_LINE> indicator[np.arange(N), y] = 1 <NEW_LINE> dW = X.T.dot(probs - indicator) <NEW_LINE> loss /= N <NEW_LINE> dW /= N <NEW_LINE> loss += reg * np.sum(W*W) <NEW_LINE> dW += 2 * reg * W <NEW_LINE> return loss, dW | Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive. | 625941c031939e2706e4cdbd |
def _updateStatusResponse(self, resp): <NEW_LINE> <INDENT> resp.addWakeups([(self.myAddress, T) for T in self._pendingWakeups]) <NEW_LINE> for each in self._activeWakeups: <NEW_LINE> <INDENT> resp.addPendingMessage(self.myAddress, self.myAddress, str(each.message)) | Called to update a Thespian_SystemStatus or Thespian_ActorStatus
with common information | 625941c007f4c71912b113d0 |
def test_parser_with_no_args(parser): <NEW_LINE> <INDENT> with pytest.raises(SystemExit): <NEW_LINE> <INDENT> parser.parse_args([]) | Without any arguments | 625941c026238365f5f0edbb |
def CreateCustomizerFeed(client, feed_name): <NEW_LINE> <INDENT> ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', 'v201809') <NEW_LINE> customizer_feed = { 'feedName': feed_name, 'feedAttributes': [ {'type': 'STRING', 'name': 'Name'}, {'type': 'STRING', 'name': 'Price'}, {'type': 'DATE_TIME', 'name': 'Date'} ] } <NEW_LINE> feed_service_operation = { 'operator': 'ADD', 'operand': customizer_feed } <NEW_LINE> response = ad_customizer_feed_service.mutate([feed_service_operation]) <NEW_LINE> if response and 'value' in response: <NEW_LINE> <INDENT> feed = response['value'][0] <NEW_LINE> feed_data = { 'feedId': feed['feedId'], 'nameId': feed['feedAttributes'][0]['id'], 'priceId': feed['feedAttributes'][1]['id'], 'dateId': feed['feedAttributes'][2]['id'] } <NEW_LINE> print(('Feed with name "%s" and ID %s was added with:\n' '\tName attribute ID %s and price attribute ID %s and date attribute' 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], feed_data['priceId'], feed_data['dateId'])) <NEW_LINE> return feed <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise errors.GoogleAdsError('No feeds were added') | Creates a new AdCustomizerFeed.
Args:
client: an AdWordsClient instance.
feed_name: the name for the new AdCustomizerFeed.
Returns:
The new AdCustomizerFeed. | 625941c0c432627299f04b94 |
def submit(command, name, threads=None, time=None, cores=None, mem=None, partition=None, modules=[], path=None, dependencies=None): <NEW_LINE> <INDENT> check_queue() <NEW_LINE> if QUEUE == 'slurm' or QUEUE == 'torque': <NEW_LINE> <INDENT> return submit_file(make_job_file(command, name, time, cores, mem, partition, modules, path), dependencies=dependencies) <NEW_LINE> <DEDENT> elif QUEUE == 'normal': <NEW_LINE> <INDENT> return submit_file(make_job_file(command, name), name=name, threads=threads) | Submit a script to the cluster.
Used in all modes::
:command: The command to execute.
:name: The name of the job.
Used for normal mode::
:threads: Total number of threads to use at a time, defaults to all.
Used for torque and slurm::
:time: The time to run for in HH:MM:SS.
:cores: How many cores to run on.
:mem: Memory to use in MB.
:partition: Partition to run on, default 'normal'.
:modules: Modules to load with the 'module load' command.
:path: Where to create the script, if None, current dir used.
Returns:
Job number in torque/slurm mode, 0 in normal mode | 625941c0925a0f43d2549dc5 |
def create_directory(self): <NEW_LINE> <INDENT> if not os.path.exists(self.original_path): <NEW_LINE> <INDENT> os.mkdir(self.original_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise DirectoryAlreadyExistsException( "'%s' already exists" % self.original_path) | fi.create_directory() -> None
Create a directory represented by this instance of the FileInfo. | 625941c08da39b475bd64ec1 |
def get_columns(self,table_name): <NEW_LINE> <INDENT> columns_l = list(map(lambda x: x[0], self.mx_cursor.execute('select * from {table_name}'.format(table_name = table_name )).description)) <NEW_LINE> print(columns_l) <NEW_LINE> return columns_l | return all columns of table | 625941c073bcbd0ca4b2bfc7 |
def string_attributes(domain): <NEW_LINE> <INDENT> return [attr for attr in domain.variables + domain.metas if attr.is_string] | Return all string attributes from the domain. | 625941c0d4950a0f3b08c2a1 |
def datetime_str(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): <NEW_LINE> <INDENT> dt = datetime(year, month, day, hour, minute, second, microsecond) <NEW_LINE> if tzinfo: <NEW_LINE> <INDENT> dt = timezone(tzinfo).localize(dt).astimezone(utc) <NEW_LINE> <DEDENT> return fields.Datetime.to_string(dt) | Return a fields.Datetime value with the given timezone. | 625941c0fbf16365ca6f610f |
def __eq__(self, *args): <NEW_LINE> <INDENT> return _itkNeighborhoodPython.itkNeighborhoodVF33___eq__(self, *args) | __eq__(self, itkNeighborhoodVF33 other) -> bool | 625941c0a8ecb033257d301e |
def median(): <NEW_LINE> <INDENT> items = [] <NEW_LINE> with open(DATA) as file: <NEW_LINE> <INDENT> for x in file: <NEW_LINE> <INDENT> items.append(int(x)) <NEW_LINE> <DEDENT> ordered = sorted(items) <NEW_LINE> size = total() <NEW_LINE> if size % 2 == 0: <NEW_LINE> <INDENT> middle = int(size / 2) <NEW_LINE> return ordered[middle] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> middle = size // 2 <NEW_LINE> return ordered[middle] | calculates the median for a dataset. | 625941c0bf627c535bc1311e |
def temps_in_use(self): <NEW_LINE> <INDENT> used = [] <NEW_LINE> for name, type, manage_ref, static in self.temps_allocated: <NEW_LINE> <INDENT> freelist = self.temps_free.get((type, manage_ref)) <NEW_LINE> if freelist is None or name not in freelist[1]: <NEW_LINE> <INDENT> used.append((name, type, manage_ref and type.is_pyobject)) <NEW_LINE> <DEDENT> <DEDENT> return used | Return a list of (cname,type,manage_ref) tuples of temp names and their type
that are currently in use. | 625941c07c178a314d6ef3ab |
def test_select_maze_type_error(self): <NEW_LINE> <INDENT> rob = roboc.Roboc('testmazedicttwo') <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> rob.select_maze(1.5) | Test for selecting maze. | 625941c045492302aab5e211 |
def extract(self, data): <NEW_LINE> <INDENT> return data.mean(1) | required input: data - a 2-dim array (channel, time) of floats | 625941c0d164cc6175782c9e |
def move_cursor_up(self, number=1): <NEW_LINE> <INDENT> pos = self.pos <NEW_LINE> if self.pos-number >= 0: <NEW_LINE> <INDENT> self.pos -= number <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pos = 0 <NEW_LINE> <DEDENT> if self.pos <= self.start_pos: <NEW_LINE> <INDENT> if number == 1: <NEW_LINE> <INDENT> self.scroll_up(8) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.scroll_up(self.start_pos-self.pos + self.height // 2) <NEW_LINE> <DEDENT> <DEDENT> return pos != self.pos | Return True if we scrolled, False otherwise | 625941c06aa9bd52df036cf3 |
def deactivate(self, comment=None, validate=True, pre_deactivate=True): <NEW_LINE> <INDENT> if validate: <NEW_LINE> <INDENT> errors = self.canDeactivate() <NEW_LINE> assert not errors, ' & '.join(errors) <NEW_LINE> <DEDENT> if pre_deactivate and not comment: <NEW_LINE> <INDENT> raise AssertionError("Require a comment to deactivate.") <NEW_LINE> <DEDENT> if pre_deactivate: <NEW_LINE> <INDENT> self.preDeactivate(comment) <NEW_LINE> <DEDENT> for membership in self.team_memberships: <NEW_LINE> <INDENT> self.leave(membership.team) <NEW_LINE> <DEDENT> for coc in self.signedcocs: <NEW_LINE> <INDENT> coc.active = False <NEW_LINE> <DEDENT> params = BugTaskSearchParams(self, assignee=self) <NEW_LINE> for bug_task in self.searchTasks(params): <NEW_LINE> <INDENT> if bug_task.conjoined_master is not None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> assert bug_task.assignee.id == self.id, ( "Bugtask %s assignee isn't the one expected: %s != %s" % ( bug_task.id, bug_task.assignee.name, self.name)) <NEW_LINE> bug_task.transitionToAssignee(None, validate=False) <NEW_LINE> <DEDENT> for spec in Store.of(self).find(Specification, _assignee=self): <NEW_LINE> <INDENT> spec.assignee = None <NEW_LINE> <DEDENT> registry_experts = getUtility(ILaunchpadCelebrities).registry_experts <NEW_LINE> for team in Person.selectBy(teamowner=self): <NEW_LINE> <INDENT> team.teamowner = registry_experts <NEW_LINE> <DEDENT> for pillar_name in self.getAffiliatedPillars(self): <NEW_LINE> <INDENT> pillar = pillar_name.pillar <NEW_LINE> changed = False <NEW_LINE> if pillar.owner.id == self.id: <NEW_LINE> <INDENT> pillar.owner = registry_experts <NEW_LINE> changed = True <NEW_LINE> <DEDENT> if pillar.driver is not None and pillar.driver.id == self.id: <NEW_LINE> <INDENT> pillar.driver = None <NEW_LINE> changed = True <NEW_LINE> <DEDENT> if IProduct.providedBy(pillar): <NEW_LINE> <INDENT> if (pillar.bug_supervisor is not None and pillar.bug_supervisor.id == self.id): <NEW_LINE> <INDENT> pillar.bug_supervisor = None <NEW_LINE> changed = True <NEW_LINE> <DEDENT> <DEDENT> if not changed: <NEW_LINE> <INDENT> raise AssertionError( "%s was expected to be owner or driver of %s" % (self.name, pillar.name)) <NEW_LINE> <DEDENT> <DEDENT> removals = [ ('BranchSubscription', 'person'), ('BugSubscription', 'person'), ('QuestionSubscription', 'person'), ('SpecificationSubscription', 'person'), ('AnswerContact', 'person'), ('LatestPersonSourcePackageReleaseCache', 'creator'), ('LatestPersonSourcePackageReleaseCache', 'maintainer')] <NEW_LINE> cur = cursor() <NEW_LINE> for table, person_id_column in removals: <NEW_LINE> <INDENT> cur.execute("DELETE FROM %s WHERE %s=%d" % (table, person_id_column, self.id)) <NEW_LINE> <DEDENT> base_new_name = self.name + '-deactivatedaccount' <NEW_LINE> self.name = self._ensureNewName(base_new_name) | See `IPersonSpecialRestricted`. | 625941c0566aa707497f44bd |
def handle_charref(self, char): <NEW_LINE> <INDENT> self.result.append('&#' + char + ';') | An escaped umlaut like ``"ä"`` | 625941c071ff763f4b5495d8 |
def close(self): <NEW_LINE> <INDENT> if self._db is not None: <NEW_LINE> <INDENT> self._db.close() <NEW_LINE> <DEDENT> self._db = None <NEW_LINE> self._openPath = None <NEW_LINE> self._openDBType = None | close the db. | 625941c00a50d4780f666de0 |
def test_structured_data_custom_domain_id(self): <NEW_LINE> <INDENT> domain = 'https://foundation.mozilla.org' <NEW_LINE> assert (self._render('en-US', domain) == 'https://foundation.mozilla.org/#firefoxbrowser') <NEW_LINE> assert (self._render('es-ES', domain) == 'https://foundation.mozilla.org/#firefoxbrowser-es-es') <NEW_LINE> assert (self._render('de', domain) == 'https://foundation.mozilla.org/#firefoxbrowser-de') | should return id for a custom domain | 625941c0d58c6744b4257bb0 |
@optional_scope <NEW_LINE> def eta(h, kernel_size=PARAMS.LSTM_KERNEL_SIZE, channels=PARAMS.Z_CHANNELS): <NEW_LINE> <INDENT> eta = tf.layers.conv2d( h, filters=2*channels, kernel_size=kernel_size, padding='SAME') <NEW_LINE> mu, sigma = tf.split(eta, num_or_size_splits=2, axis=-1) <NEW_LINE> sigma = tf.nn.softplus(sigma + .5) + 1e-8 <NEW_LINE> return mu, sigma | Computes sufficient statistics of a normal distribution (mu, sigma) from a
hidden state representation via convolution. | 625941c021bff66bcd6848a5 |
def optim_greedy(mat_l, mat_r, verbose=True): <NEW_LINE> <INDENT> from tqdm import tqdm <NEW_LINE> n = mat_l.shape[1] <NEW_LINE> sigma = np.ones(n, dtype=np.int) <NEW_LINE> stop_criterion = False <NEW_LINE> current_spec = f_spec(sigma, mat_l, mat_r) <NEW_LINE> highest_loop = current_spec <NEW_LINE> it = 0 <NEW_LINE> while not stop_criterion: <NEW_LINE> <INDENT> it += 1 <NEW_LINE> previous = highest_loop <NEW_LINE> highest_idx = -1 <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> change = 1 - sigma[i] <NEW_LINE> sigma[i] = change <NEW_LINE> spec = f_spec(sigma, mat_l, mat_r) <NEW_LINE> if highest_loop < spec: <NEW_LINE> <INDENT> highest_loop = spec <NEW_LINE> highest_idx = i <NEW_LINE> current_spec = spec <NEW_LINE> <DEDENT> sigma[i] = 1 - change <NEW_LINE> <DEDENT> if highest_idx < 0: <NEW_LINE> <INDENT> stop_criterion = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sigma[highest_idx] = 1 - sigma[highest_idx] <NEW_LINE> if verbose: <NEW_LINE> <INDENT> sign_change = '+' if sigma[highest_idx] > 0.5 else '-' <NEW_LINE> print('[{}] {} Best at position {}: {:.4f} > {:.4f}'.format( it, sign_change, highest_idx, highest_loop, previous)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return current_spec, sigma | Greedy algorithm to perform the following optimization problem:
max | U d(sigma) V|
where |.| is the spectral norm, with sigma being in the cube [0, 1] | 625941c0e8904600ed9f1e7a |
def _validate_options(self): <NEW_LINE> <INDENT> pass | Sub-commands can override to do any argument validation they
require. | 625941c0e8904600ed9f1e7b |
def test_instructor_not_owner(self): <NEW_LINE> <INDENT> password = 'password' <NEW_LINE> new_instructor_user = User.objects.create_user(username='new_instructor', password=password) <NEW_LINE> new_instructor = models.Instructor(user=new_instructor_user, wwuid='8888888') <NEW_LINE> new_instructor.save() <NEW_LINE> self.client.logout() <NEW_LINE> self.client.login(username=new_instructor_user.username, password=password) <NEW_LINE> response = self.client.get(reverse(self.view_name, args=[self.assignment.id])) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) | Tests that a CSV is not generated if an instructor does not own the assignment. | 625941c029b78933be1e5600 |
def process_one(self): <NEW_LINE> <INDENT> pass | Select a full reservation and plan it.
To be implemented in concrete subclasses | 625941c030c21e258bdfa3ec |
@register.simple_tag <NEW_LINE> def bootstrap_jquery(): <NEW_LINE> <INDENT> url = bootstrap_jquery_url() <NEW_LINE> if url: <NEW_LINE> <INDENT> return '<script src="{url}"></script>\n'.format(url=url) | Return HTML for jQuery JavaScript
Adjust url in settings. If no url is returned, we don't want this statement to return any HTML.
This is intended behavior.
Default value: ``None``
this value is configurable, see Settings section
**Tag name**::
bootstrap_jquery
**usage**::
{% bootstrap_jquery %}
**example**::
{% bootstrap_jquery%} | 625941c0796e427e537b0514 |
def update(self, job_id, attributes): <NEW_LINE> <INDENT> the_url = self.build_url("v1", "jobs/" + job_id) <NEW_LINE> data = json.dumps(attributes) <NEW_LINE> return self.invoke_put(the_url, self.user, self.key, data) | Updates a Sauce Job with the data contained in the attributes dict | 625941c0d7e4931a7ee9de6d |
def init_widget(self): <NEW_LINE> <INDENT> super(QtWindow, self).init_widget() <NEW_LINE> d = self.declaration <NEW_LINE> if d.title: <NEW_LINE> <INDENT> self.set_title(d.title) <NEW_LINE> <DEDENT> if -1 not in d.initial_size: <NEW_LINE> <INDENT> self.set_initial_size(d.initial_size) <NEW_LINE> <DEDENT> if d.modality != 'non_modal': <NEW_LINE> <INDENT> self.set_modality(d.modality) <NEW_LINE> <DEDENT> if d.icon: <NEW_LINE> <INDENT> self.set_icon(d.icon) <NEW_LINE> <DEDENT> self.widget.closed.connect(self.on_closed) | Initialize the widget.
| 625941c0e1aae11d1e749c05 |
def get_stereo_two_rose(self): <NEW_LINE> <INDENT> self.fig.clf() <NEW_LINE> self.fig.patch.set_facecolor(self.props["canvas_color"]) <NEW_LINE> self.fig.set_dpi(self.props["pixel_density"]) <NEW_LINE> gridspec = GridSpec(2, 4) <NEW_LINE> sp_stereo = gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) <NEW_LINE> sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) <NEW_LINE> sp_rose = gridspec.new_subplotspec((0, 3), rowspan=1, colspan=1) <NEW_LINE> sp_drose = gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1) <NEW_LINE> ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) <NEW_LINE> ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar") <NEW_LINE> ax_drose = self.fig.add_subplot(sp_drose, projection="dippolar") <NEW_LINE> ax_cbar = self.fig.add_subplot(sp_cbar) <NEW_LINE> ax_cbar.axis("off") <NEW_LINE> ax_cbar.set_aspect(8) <NEW_LINE> return ax_stereo, ax_rose, ax_drose, ax_cbar | Resets the figure and returns a stereonet two rose diagrams axis.
When the view in the main window is changed to this setting, this
function is called and sets up a plot with a stereonet and two
rose diagram axis. One axis is for azimuth, the other one for
dip. | 625941c0a8370b77170527f1 |
def indexes(self, contype=None, username=None, password=None): <NEW_LINE> <INDENT> from pytest_splunk_env.splunk.helmut.manager.indexes import Indexes <NEW_LINE> return Indexes(self.connector(contype, username, password)) | Returns a Indexes manager that uses the specified connector. Defaults
to default connector if none specified.
This property creates a new Indexes manager each time it is called so
you may handle the object as you wish.
@param contype: type of connector, defined in L{Connector} class
@param username: connector's username
@type username: string
@rtype: L{Indexes} | 625941c04e4d5625662d432b |
def distance(self, A, B): <NEW_LINE> <INDENT> return round(abs(A - B), self.decimals) | The distance between two points. | 625941c0460517430c3940db |
def addNoise(self,dataIn): <NEW_LINE> <INDENT> dataOut = dataIn + np.random.normal(0,self.sigmaN,dataIn.size) <NEW_LINE> return dataOut | Description: Add noise to input sample or array
Params: dataIn: Input sample (float)
Returns: dataOut: Output sample(s) with noise added (float) | 625941c02c8b7c6e89b35713 |
def show_problem(self, pid, show_all=False): <NEW_LINE> <INDENT> if show_all: <NEW_LINE> <INDENT> problem = ProblemBodyQuery.get_problem_detail(pid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self._user_session.is_logined() and self._user_session.user_role >= 2: <NEW_LINE> <INDENT> problem = ProblemBodyQuery.get_problem_detail(pid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> problem = ProblemBodyQuery.get_problem_detail(pid, False) <NEW_LINE> <DEDENT> if problem is None: <NEW_LINE> <INDENT> self._context = kernel.error_const.ERROR_PROBLEM_NOT_FOUND <NEW_LINE> self._action = kernel.const.VIEW_ACTION_ERROR_PAGE <NEW_LINE> return False <NEW_LINE> <DEDENT> if problem.is_private and (not self._user_session.is_logined() or (self._user_session.user_role != 99 and self._user_session.user_id != problem.author.id)): <NEW_LINE> <INDENT> self._context = kernel.error_const.ERROR_PROBLEM_NOT_FOUND <NEW_LINE> self._action = kernel.const.VIEW_ACTION_ERROR_PAGE <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> self._context = { 'problem': problem, 'language_provider': kernel.const.LANGUAGE_PROVIDE } <NEW_LINE> self._template_file = "problem/problem/view.html" <NEW_LINE> return True | 题目展示(View)
:param pid: 问题ID
:param show_all: 强制显示
:return: | 625941c0711fe17d825422c1 |
def listHostnames(self,session,propertyId,version,contractId,groupId): <NEW_LINE> <INDENT> hostnameListUrl = 'https://' + self.access_hostname + '/papi/v1/properties/' + propertyId + '/versions/' + str(version) + '/hostnames'+ '?contractId=' + contractId + '&groupId=' + groupId <NEW_LINE> hostnameListUrl = self.formUrl(hostnameListUrl) <NEW_LINE> hostnameListResponse = session.get(hostnameListUrl) <NEW_LINE> return hostnameListResponse | Function to fetch all properties
Parameters
----------
session : <string>
An EdgeGrid Auth akamai session object
contractId : contractId
corresponding contractId
groupId : groupId
corresponding groupId
Returns
-------
hostNameList : hostName List object | 625941c0adb09d7d5db6c6e2 |
def delete_book(BID: str) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = True <NEW_LINE> database = open_database() <NEW_LINE> books = database['books'] <NEW_LINE> logs = database['logs'] <NEW_LINE> borrowing_books = database['borrowing_books'] <NEW_LINE> for book in books: <NEW_LINE> <INDENT> if book[0] == BID: <NEW_LINE> <INDENT> books.remove(book) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> i = 0 <NEW_LINE> while i < len(borrowing_books): <NEW_LINE> <INDENT> if borrowing_books[i][0] == BID: <NEW_LINE> <INDENT> borrowing_books.pop(i) <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> while i < len(logs): <NEW_LINE> <INDENT> if logs[i][0] == BID: <NEW_LINE> <INDENT> logs.pop(i) <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> close_database(database) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print('delete book error!') <NEW_LINE> print(e) <NEW_LINE> res = False <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return res | 传入BID
返回bool
会删除book,borrowing_book,log表内所有对应的记录 | 625941c063f4b57ef0001070 |
def test_representation(): <NEW_LINE> <INDENT> assert str(MINIMAL_SHAPE) != "" <NEW_LINE> assert repr(MINIMAL_SHAPE) != "" | test_representation: check if __str__ and __repr__ are defined | 625941c0ac7a0e7691ed4021 |
def address_exclude(self, other): <NEW_LINE> <INDENT> if not self._version == other._version: <NEW_LINE> <INDENT> raise TypeError("%s and %s are not of the same version" % ( str(self), str(other))) <NEW_LINE> <DEDENT> if not isinstance(other, _BaseNetwork): <NEW_LINE> <INDENT> raise TypeError("%s is not a network object" % str(other)) <NEW_LINE> <DEDENT> if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): <NEW_LINE> <INDENT> raise ValueError('%s not contained in %s' % (str(other), str(self))) <NEW_LINE> <DEDENT> if other == self: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> ret_addrs = [] <NEW_LINE> other = ip_network('%s/%s' % (str(other.network_address), str(other.prefixlen)), version=other._version) <NEW_LINE> s1, s2 = self.subnets() <NEW_LINE> while s1 != other and s2 != other: <NEW_LINE> <INDENT> if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): <NEW_LINE> <INDENT> yield s2 <NEW_LINE> s1, s2 = s1.subnets() <NEW_LINE> <DEDENT> elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): <NEW_LINE> <INDENT> yield s1 <NEW_LINE> s1, s2 = s2.subnets() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (str(s1), str(s2), str(other))) <NEW_LINE> <DEDENT> <DEDENT> if s1 == other: <NEW_LINE> <INDENT> yield s2 <NEW_LINE> <DEDENT> elif s2 == other: <NEW_LINE> <INDENT> yield s1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (str(s1), str(s2), str(other))) | Remove an address from a larger block.
For example:
addr1 = ip_network('192.0.2.0/28')
addr2 = ip_network('192.0.2.1/32')
addr1.address_exclude(addr2) =
[IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
or IPv6:
addr1 = ip_network('2001:db8::1/32')
addr2 = ip_network('2001:db8::1/128')
addr1.address_exclude(addr2) =
[ip_network('2001:db8::1/128'),
ip_network('2001:db8::2/127'),
ip_network('2001:db8::4/126'),
ip_network('2001:db8::8/125'),
...
ip_network('2001:db8:8000::/33')]
Args:
other: An IPv4Network or IPv6Network object of the same type.
Returns:
An iterator of the the IPv(4|6)Network objects which is self
minus other.
Raises:
TypeError: If self and other are of difffering address
versions, or if other is not a network object.
ValueError: If other is not completely contained by self. | 625941c07047854f462a135d |
def manager(self): <NEW_LINE> <INDENT> for arg in self.args: <NEW_LINE> <INDENT> self.tasks.put_nowait(arg) | A gevent manager, creating the initial gevents | 625941c0a219f33f346288bd |
def s3_guided_tour(output): <NEW_LINE> <INDENT> if request.get_vars.tour: <NEW_LINE> <INDENT> output = s3db.tour_builder(output) <NEW_LINE> <DEDENT> return output | Helper function to attach a guided tour (if required) to the output | 625941c08e7ae83300e4af1d |
def update_quota_set(self, tenant_id, user_id=None, force=None, injected_file_content_bytes=None, metadata_items=None, ram=None, floating_ips=None, fixed_ips=None, key_pairs=None, instances=None, security_group_rules=None, injected_files=None, cores=None, injected_file_path_bytes=None, security_groups=None): <NEW_LINE> <INDENT> post_body = {} <NEW_LINE> if force is not None: <NEW_LINE> <INDENT> post_body['force'] = force <NEW_LINE> <DEDENT> if injected_file_content_bytes is not None: <NEW_LINE> <INDENT> post_body['injected_file_content_bytes'] = injected_file_content_bytes <NEW_LINE> <DEDENT> if metadata_items is not None: <NEW_LINE> <INDENT> post_body['metadata_items'] = metadata_items <NEW_LINE> <DEDENT> if ram is not None: <NEW_LINE> <INDENT> post_body['ram'] = ram <NEW_LINE> <DEDENT> if floating_ips is not None: <NEW_LINE> <INDENT> post_body['floating_ips'] = floating_ips <NEW_LINE> <DEDENT> if fixed_ips is not None: <NEW_LINE> <INDENT> post_body['fixed_ips'] = fixed_ips <NEW_LINE> <DEDENT> if key_pairs is not None: <NEW_LINE> <INDENT> post_body['key_pairs'] = key_pairs <NEW_LINE> <DEDENT> if instances is not None: <NEW_LINE> <INDENT> post_body['instances'] = instances <NEW_LINE> <DEDENT> if security_group_rules is not None: <NEW_LINE> <INDENT> post_body['security_group_rules'] = security_group_rules <NEW_LINE> <DEDENT> if injected_files is not None: <NEW_LINE> <INDENT> post_body['injected_files'] = injected_files <NEW_LINE> <DEDENT> if cores is not None: <NEW_LINE> <INDENT> post_body['cores'] = cores <NEW_LINE> <DEDENT> if injected_file_path_bytes is not None: <NEW_LINE> <INDENT> post_body['injected_file_path_bytes'] = injected_file_path_bytes <NEW_LINE> <DEDENT> if security_groups is not None: <NEW_LINE> <INDENT> post_body['security_groups'] = security_groups <NEW_LINE> <DEDENT> post_body = json.dumps({'quota_set': post_body}) <NEW_LINE> if user_id: <NEW_LINE> <INDENT> resp, body = self.put('os-quota-sets/%s?user_id=%s' % (str(tenant_id), str(user_id)), post_body) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resp, body = self.put('os-quota-sets/%s' % str(tenant_id), post_body) <NEW_LINE> <DEDENT> body = json.loads(body) <NEW_LINE> self.validate_response(schema.update_quota_set, resp, body) <NEW_LINE> return service_client.ResponseBody(resp, body['quota_set']) | Updates the tenant's quota limits for one or more resources | 625941c00a50d4780f666de1 |
def background_knowledge(self): <NEW_LINE> <INDENT> modeslist, getters = [self.mode(self.__target_predicate(), [('+', self.db.target_table)], head=True)], [] <NEW_LINE> determinations, types = [], [] <NEW_LINE> for (table, ref_table) in self.db.connected.keys(): <NEW_LINE> <INDENT> if ref_table == self.db.target_table: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> modeslist.append( self.mode('%s_has_%s' % (table.lower(), ref_table), [('+', table), ('-', ref_table)], recall='*')) <NEW_LINE> determinations.append( ':- determination(%s/1, %s_has_%s/2).' % (self.__target_predicate(), table.lower(), ref_table)) <NEW_LINE> types.extend(self.concept_type_def(table)) <NEW_LINE> types.extend(self.concept_type_def(ref_table)) <NEW_LINE> getters.extend(self.connecting_clause(table, ref_table)) <NEW_LINE> <DEDENT> for table, atts in self.db.cols.items(): <NEW_LINE> <INDENT> for att in atts: <NEW_LINE> <INDENT> if att == self.db.target_att and table == self.db.target_table or att in self.db.fkeys[table] or att == self.db.pkeys[table]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> modeslist.append(self.mode('%s_%s' % (table, att), [('+', table), ('#', att.lower())], recall='*')) <NEW_LINE> determinations.append(':- determination(%s/1, %s_%s/2).' % (self.__target_predicate(), table, att)) <NEW_LINE> types.extend(self.constant_type_def(table, att)) <NEW_LINE> getters.extend(self.attribute_clause(table, att)) <NEW_LINE> <DEDENT> <DEDENT> return '\n'.join(self.user_settings() + modeslist + determinations + types + getters + self.dump_tables()) | Emits the background knowledge in prolog form for Aleph. | 625941c0091ae35668666eb3 |
def congestion_signal(self, x): <NEW_LINE> <INDENT> T = x.shape[0] <NEW_LINE> segmax = [1, 1, 1, .5, .5] <NEW_LINE> congestion_signal = np.zeros([T], dtype=bool) <NEW_LINE> for t in range(T): <NEW_LINE> <INDENT> if ((.5 < .5 * x[t, 2]) or (.8*(segmax[1] - x[t, 1]) < min(self.road_saturation, .5 * x[t, 0])) or (.8*(segmax[2] - x[t, 2]) < min(self.road_saturation, .5 * x[t, 1])) or (.2*(segmax[1] - x[t, 1]) < min(self.ramp_saturation, x[t, 3])) or (.2*(segmax[2] - x[t, 2]) < min(self.ramp_saturation, x[t, 4])) ): <NEW_LINE> <INDENT> congestion_signal[t] = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> congestion_signal[t] = True <NEW_LINE> <DEDENT> <DEDENT> return congestion_signal | Return a signal determining if congestion free exists at any given time. | 625941c09f2886367277a7e0 |
def sbd_disable(lib, argv, modifiers): <NEW_LINE> <INDENT> modifiers.ensure_only_supported("--request-timeout", "--skip-offline") <NEW_LINE> if argv: <NEW_LINE> <INDENT> raise CmdLineInputError() <NEW_LINE> <DEDENT> lib.sbd.disable_sbd(modifiers.get("--skip-offline")) | Options:
* --request-timeout - HTTP request timeout
* --skip-offline - skip offline cluster nodes | 625941c03539df3088e2e29c |
def pop(self): <NEW_LINE> <INDENT> return self.items.pop() | Removes and returns the last added element to the structure. | 625941c07d43ff24873a2bef |
def __iter__(self): <NEW_LINE> <INDENT> for w, i in sorted(iteritems(self.word_id), key=lambda wc: wc[1]): <NEW_LINE> <INDENT> yield w | Iterate over the words in a vocabulary. | 625941c0eab8aa0e5d26daa8 |
def test_create_file(self): <NEW_LINE> <INDENT> filename = self.got_filename <NEW_LINE> workbook = Workbook(filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.print_area('A1:XFD1') <NEW_LINE> worksheet.write('A1', 'Foo') <NEW_LINE> workbook.close() <NEW_LINE> got, exp = _compare_xlsx_files(self.got_filename, self.exp_filename, self.ignore_files, self.ignore_elements) <NEW_LINE> self.assertEqual(got, exp) | Test the creation of a simple XlsxWriter file with a print area. | 625941c0287bf620b61d39b6 |
def _setup_global_step(self, global_step): <NEW_LINE> <INDENT> graph_global_step = global_step <NEW_LINE> if graph_global_step is None: <NEW_LINE> <INDENT> graph_global_step = tf.training_util.get_global_step() <NEW_LINE> <DEDENT> return tf.cast(graph_global_step, tf.int32) | Fetches the global step. | 625941c0ab23a570cc2500d1 |
def Event(self, objId, msgStr, color=MSC_COLOR_NONE): <NEW_LINE> <INDENT> self.stdout.write('[-->"%s":%s\n' % (self.objList[objId], msgStr)) | Displays a asynchronous event to an object's life line
| 625941c045492302aab5e212 |
def generate(self, bundle): <NEW_LINE> <INDENT> if isinstance(bundle, string): <NEW_LINE> <INDENT> bundle = import_object(bundle) <NEW_LINE> <DEDENT> source = self._generate_binding(bundle) <NEW_LINE> return '%s.py' % bundle.name, source | Generates a binding for the specified bundle using this generator. | 625941c063d6d428bbe44440 |
def test_add_person_successfully(self): <NEW_LINE> <INDENT> staff_one = self.dojo.add_person("Stanley", "Lee", "staff") <NEW_LINE> self.assertTrue(staff_one) | Test if a person is added successfully using the add_person method in Dojo | 625941c0956e5f7376d70dbf |
def event_min_age(age): <NEW_LINE> <INDENT> return predet_wrapper( "event_min_age", lambda **kwargs: kwargs['event'].getArrivalTime()-kwargs['event'].getCreationTime() >= age ) | Minimum age (difference between creation and arrival time).
Uses the predet_wrapper. | 625941c01d351010ab855a6d |
def _concatenate_inner(self, direction): <NEW_LINE> <INDENT> result = [] <NEW_LINE> tmp_bucket = [] <NEW_LINE> chunks = self.chunks if direction else self.chunks[::-1] <NEW_LINE> for chunk in chunks: <NEW_LINE> <INDENT> if ( chunk.dependency == direction or (direction == False and chunk.is_space()) ): <NEW_LINE> <INDENT> tmp_bucket.append(chunk) <NEW_LINE> continue <NEW_LINE> <DEDENT> tmp_bucket.append(chunk) <NEW_LINE> if not direction: tmp_bucket = tmp_bucket[::-1] <NEW_LINE> new_word = ''.join([tmp_chunk.word for tmp_chunk in tmp_bucket]) <NEW_LINE> chunk.update_word(new_word) <NEW_LINE> result.append(chunk) <NEW_LINE> tmp_bucket = [] <NEW_LINE> <DEDENT> if tmp_bucket: result += tmp_bucket <NEW_LINE> self.chunks = result if direction else result[::-1] | Concatenates chunks based on each chunk's dependency.
Args:
direction: Direction of concatenation process. True for forward. (bool) | 625941c07cff6e4e811178d7 |
def write_chunk(self, chunkhash, data): <NEW_LINE> <INDENT> return self._backoff(lambda: self._write_chunk(chunkhash, data), Fail) | Wrap the private _write_chunk method with a backoff algorithm. | 625941c02ae34c7f2600d083 |
def annotate(text, x, y, ax=None, horizontalalignment="center", verticalalignment="center", ha=None, va=None, transform="axes", fontsize=9, color="k", facecolor="w", edgecolor='0.75', alpha=0.75, text_alpha=1, bbox=dict(), stroke = None, **kwargs, ): <NEW_LINE> <INDENT> if ax is None: <NEW_LINE> <INDENT> ax = plt.gca() <NEW_LINE> <DEDENT> horizontalalignment = ha or horizontalalignment <NEW_LINE> verticalalignment = va or verticalalignment <NEW_LINE> if transform == "axes": <NEW_LINE> <INDENT> transform = ax.transAxes <NEW_LINE> <DEDENT> elif transform == "data": <NEW_LINE> <INDENT> transform = ax.transData <NEW_LINE> <DEDENT> if bbox is None: <NEW_LINE> <INDENT> bbox1 = dict(facecolor='none', alpha=0,edgecolor='none') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bbox1 = dict(facecolor=facecolor, alpha=alpha,edgecolor=edgecolor) <NEW_LINE> bbox1.update(bbox) <NEW_LINE> <DEDENT> text = ax.text( x, y, text, horizontalalignment=horizontalalignment, verticalalignment=verticalalignment, transform=transform, color=color, fontsize=fontsize, bbox=bbox1, **kwargs, ) <NEW_LINE> if stroke is not None: <NEW_LINE> <INDENT> if type(stroke) == dict: <NEW_LINE> <INDENT> text.set_path_effects([withStroke(**stroke)]) <NEW_LINE> <DEDENT> elif isinstance(stroke,(list,tuple)): <NEW_LINE> <INDENT> text.set_path_effects([*stroke]) <NEW_LINE> <DEDENT> elif isinstnace(stroke,mpl.patheffects.AbstractPathEffect): <NEW_LINE> <INDENT> text.set_path_effects([stroke]) <NEW_LINE> <DEDENT> <DEDENT> return text | wrapper for Axes.text
Parameters
----------
text : str
text
x : number
x coordinate
y : number
x coordinate
ax : axes, optional
[description], by default None
horizontalalignment : str, optional
by default "center"
verticalalignment : str, optional
by default "center"
ha : alias for horizontalalignment
va : alias for verticalalignment
transform : str, optional
use 'axes' (ax.transAxes) or 'data' (ax.transData) to interpret x,y
fontsize : int, optional
by default 9
color : str, optional
text color, by default "k"
facecolor : str, optional
color of frame area, by default "w"
edgecolor : str, optional
color of frame edge, by default '0.75'
alpha : float, optional
transparency of frame area, by default 0.75
text_alpha : int, optional
transparency of text, by default 1
bbox : [type], optional
dictionary defining the bounding box or frame, by default dict()
stroke : (list, mpl.patheffects,dict), optional
most often should be dict with {'foregroud':"w", linewidth:3}
if using stroke, use should set bbox=None
Returns
-------
text
the annotation | 625941c0fff4ab517eb2f38b |
def __setitem__(self, key, value): <NEW_LINE> <INDENT> assert PRIMARY_KEY not in value or value[PRIMARY_KEY] == key <NEW_LINE> value = dict(value) <NEW_LINE> value[PRIMARY_KEY] = key <NEW_LINE> if key in self._store.keys() and value == self._store[key]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with self._context: <NEW_LINE> <INDENT> self._collection.find_one_and_replace( {PRIMARY_KEY: key}, value, upsert=True ) <NEW_LINE> <DEDENT> self._store[key] = datastruct.ImmutableDict(value) | store key-value to collection (lazy if value isn't changed) | 625941c056b00c62f0f145a9 |
def get_pixels(self, folder, img, img_index, size): <NEW_LINE> <INDENT> positions, _ = self.get_annotation(folder, img_index) <NEW_LINE> h, w = img.shape[0], img.shape[1] <NEW_LINE> proportion_h, proportion_w = size / h, size / w <NEW_LINE> pixels = np.zeros((size, size)) <NEW_LINE> for p in positions: <NEW_LINE> <INDENT> now_x, now_y = int(p[0] * proportion_w), int(p[1] * proportion_h) <NEW_LINE> if now_x >= size or now_y >= size: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pixels[now_y, now_x] += 1 <NEW_LINE> <DEDENT> <DEDENT> pixels = cv2.GaussianBlur(pixels, (15, 15), 0) <NEW_LINE> return pixels | 生成密度图,准备输入神经网络
:param folder 当前所在数据目录,该数据集目录较为复杂
:param img 原始图像
:param img_index 图片在当前目录下的图片序号,1开始
:param size 目标图大小,按照模型为img的1/4 | 625941c029b78933be1e5601 |
def __init__(self, msgbytes): <NEW_LINE> <INDENT> log.debug(" ") <NEW_LINE> super().__init__(msgbytes) <NEW_LINE> self.fatigue_level = None <NEW_LINE> while self.properties_iterator.has_next() == True: <NEW_LINE> <INDENT> hmprop = self.properties_iterator.next() <NEW_LINE> if hmprop.getproperty_identifier() == DriverFatigueState.DETECTED_FATIGUE_LEVEL: <NEW_LINE> <INDENT> log.debug(" DETECTED_FATIGUE_LEVEL") <NEW_LINE> if hmprop.getcomponent_valuebytes() is not None: <NEW_LINE> <INDENT> fatiguelevel_bytes = int.from_bytes(hmprop.getcomponent_valuebytes(), byteorder='big', signed=False) <NEW_LINE> self.fatigue_level = FatigueLevel(fatiguelevel_bytes) <NEW_LINE> log.debug(" DETECTED_FATIGUE_LEVEL: " + str(self.fatigue_level)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return | Parse the Detected fatique level messagebytes and construct the instance
:param bytes msgbytes: Driver Fatigue State in bytes | 625941c08a349b6b435e80c5 |
def collect_cases(fn: Callable[..., Iterator[Case]]) -> Callable[..., None]: <NEW_LINE> <INDENT> def test(*args: Any, **kwargs: Any) -> None: <NEW_LINE> <INDENT> cases = list(fn(*args, **kwargs)) <NEW_LINE> expected_errors = set( "{}.{}".format(TEST_MODULE_NAME, c.error) for c in cases if c.error is not None ) <NEW_LINE> output = run_stubtest( stub="\n\n".join(textwrap.dedent(c.stub.lstrip("\n")) for c in cases), runtime="\n\n".join(textwrap.dedent(c.runtime.lstrip("\n")) for c in cases), options=["--generate-whitelist"], ) <NEW_LINE> actual_errors = set(output.splitlines()) <NEW_LINE> assert actual_errors == expected_errors, output <NEW_LINE> <DEDENT> return test | Repeatedly invoking run_stubtest is slow, so use this decorator to combine cases.
We could also manually combine cases, but this allows us to keep the contrasting stub and
runtime definitions next to each other. | 625941c076d4e153a657ea81 |
def findRxCharacteristic(self): <NEW_LINE> <INDENT> self.rxFromRoombaCharacteristic = self._findCharacteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e") | Find characteristic which has UUID 6e400003-b5a3-f393-e0a9-e50e24dcca9e | 625941c023849d37ff7b2fe1 |
def _create_enrollment_to_refund(self, no_of_days_placed=10, enterprise_enrollment_exists=True): <NEW_LINE> <INDENT> date_placed = now() - timedelta(days=no_of_days_placed) <NEW_LINE> course = CourseFactory.create(display_name='test course', run="Testing_course", start=date_placed) <NEW_LINE> enrollment = CourseEnrollmentFactory( course_id=course.id, user=self.user, mode="verified", ) <NEW_LINE> CourseModeFactory.create(course_id=course.id, mode_slug='verified') <NEW_LINE> CourseEnrollmentAttribute.objects.create( enrollment=enrollment, name='date_placed', namespace='order', value=date_placed.strftime(ECOMMERCE_DATE_FORMAT) ) <NEW_LINE> CourseEnrollmentAttribute.objects.create( enrollment=enrollment, name='order_number', namespace='order', value='EDX-000000001' ) <NEW_LINE> if enterprise_enrollment_exists: <NEW_LINE> <INDENT> self._create_enterprise_enrollment(self.user.id, course.id) <NEW_LINE> <DEDENT> return enrollment | Create enrollment to refund. | 625941c038b623060ff0ad3f |
def get_connection_properties(self, database_connector_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.get_connection_properties_with_http_info(database_connector_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_connection_properties_with_http_info(database_connector_id, **kwargs) <NEW_LINE> return data | Get connection properties for database connector by ID # noqa: E501
A list of properties provided through the connection properties file. # 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_connection_properties(database_connector_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int database_connector_id: The ID of the database connector to retrieve connection properties (required)
:return: ConnectionPropertiesList
If the method is called asynchronously,
returns the request thread. | 625941c00c0af96317bb8139 |
def __init__(self, m, n=2,SEED=0): <NEW_LINE> <INDENT> if n > 2: <NEW_LINE> <INDENT> sys.exit("Initialization of Necklace: Currently only n < 3 is implemented") <NEW_LINE> <DEDENT> if n * m % 2 != 0: <NEW_LINE> <INDENT> sys.exit('Initialization of Necklace: The number of sites is not even. Please give even number of sites!') <NEW_LINE> <DEDENT> self.__m = m <NEW_LINE> self.__n = n <NEW_LINE> self.__lastPos1 = 0 <NEW_LINE> self.__lastPos2 = 0 <NEW_LINE> if self.__m % 2 == 0: <NEW_LINE> <INDENT> self.allEnergies = np.arange(2, self.__m * 2 + 1, 2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.allEnergies = np.arange(2, self.__m * 2 + 1, 1) <NEW_LINE> <DEDENT> self.dims_states = binom(int(self.__m*self.__n),int(self.__m*self.__n/2)) <NEW_LINE> self.dims_lumped = len(self.allEnergies) <NEW_LINE> self._ring = 0 <NEW_LINE> self._ext = 0 <NEW_LINE> self._ring_expanded = -1 <NEW_LINE> self._ext_expanded = -1 <NEW_LINE> self._expanded_bits = 0 <NEW_LINE> if SEED > 0: <NEW_LINE> <INDENT> random.seed = SEED <NEW_LINE> <DEDENT> self.shuffle_state() | Initializes the necklace model
:param m: Number of sites in the ring
:param n: Number of nodes in each fully connected graph on the ring | 625941c01d351010ab855a6e |
def wrap_in_ifs(node, ifs): <NEW_LINE> <INDENT> return reduce(lambda n, if_: ast.If(if_, [n], []), ifs, node) | Wrap comprehension content in all possibles if clauses.
Examples
--------
>> [i for i in range(2) if i < 3 if 0 < i]
Becomes
>> for i in range(2):
>> if i < 3:
>> if 0 < i:
>> ... the code from `node` ...
Note the nested ifs clauses. | 625941c050812a4eaa59c275 |
def _setvalue(self, schema, value): <NEW_LINE> <INDENT> pass | Fired when inner schema change of value.
:param Schema schema: inner schema.
:param value: new value. | 625941c04e4d5625662d432c |
def knock_cup(self, cup): <NEW_LINE> <INDENT> if cup.frogs: <NEW_LINE> <INDENT> for frog in cup.frogs: <NEW_LINE> <INDENT> frog.fall_from_cup(cup) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> if cup.contents == self.water_id and not self.water_drop.is_visible(): <NEW_LINE> <INDENT> self.water_drop.fall(cup.x, cup.y) <NEW_LINE> <DEDENT> elif cup.contents == self.sherry_id and not self.sherry_drop.is_visible(): <NEW_LINE> <INDENT> self.sherry_drop.fall(cup.x, cup.y) | Make a cup spill its contents (as when hit by a catapult pellet). A
cup may contain water, sherry, a frog, or nothing.
:param cup: The cup. | 625941c097e22403b379ceea |
def __init__(self, ai_settings, screen, real_ship = True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> if real_ship: <NEW_LINE> <INDENT> self.image = pygame.image.load('images/ship.bmp') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image = pygame.image.load('images/ship_score.bmp') <NEW_LINE> <DEDENT> self.rect = self.image.get_rect() <NEW_LINE> self.screen_rect = screen.get_rect() <NEW_LINE> self.rect.centerx = self.screen_rect.centerx <NEW_LINE> self.rect.bottom = self.screen_rect.bottom <NEW_LINE> self.center = float(self.rect.centerx) <NEW_LINE> self.moving_right = False <NEW_LINE> self.moving_left = False | Initialize the ship and set its starting position | 625941c03cc13d1c6d3c72cc |
def __init__(self, api_manager: APIManager, cls: Union[Type[EventType], Type[ObjectType]]): <NEW_LINE> <INDENT> self._class = cls <NEW_LINE> if self._class == EventType: <NEW_LINE> <INDENT> self._path = 'eventTypes' <NEW_LINE> self._entity_path = 'timeseries' <NEW_LINE> <DEDENT> elif self._class == ObjectType: <NEW_LINE> <INDENT> self._path = 'objectTypes' <NEW_LINE> self._entity_path = 'objectAttributes' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Supported types are EventType and ObjectType') <NEW_LINE> <DEDENT> self.api_manager = api_manager <NEW_LINE> self.api_version = "/api/v3" | Restricted updates operations specialized for following types:
- Object Types
- Event Types | 625941c0d53ae8145f87a1c5 |
def __repr__(self): <NEW_LINE> <INDENT> return "Specht representation of the symmetric group corresponding to %s" % self._partition | String representation of ``self``.
EXAMPLES::
sage: from sage.combinat.symmetric_group_representations import SpechtRepresentation
sage: SpechtRepresentation([2,1]).__repr__()
'Specht representation of the symmetric group corresponding to [2, 1]' | 625941c04527f215b584c3ab |
def __init__(self): <NEW_LINE> <INDENT> self.player_One = None <NEW_LINE> self.player_Two = None <NEW_LINE> self.player_One_attempt, self.player_Two_attempt = None, None <NEW_LINE> self.player_One_ships, self.player_Two_ships = 8, 8 <NEW_LINE> self.data_lst = list() | :param Game.player_One: First player field
:param Game.player_Two: Second player field
:param Game.player_One_attempt: First player attempt field
:param Game.player_Two_attempt: Second player attempt field
:param Game.player_One_ships: First player ships
:param Game.player_Two_ships: Second player attempt field
:param Game.data_lst: Сoordinates entered by users | 625941c023849d37ff7b2fe2 |
def open_rgby(path, id): <NEW_LINE> <INDENT> r <NEW_LINE> colors = ['red', 'green', 'blue', 'yellow'] <NEW_LINE> flags = cv2.IMREAD_GRAYSCALE <NEW_LINE> img = [] <NEW_LINE> for color in colors: <NEW_LINE> <INDENT> temp = cv2.imread(os.path.join(path, id+'_'+color+'.png'), flags) <NEW_LINE> temp = temp.astype(np.float32)/255 <NEW_LINE> img.append(temp) <NEW_LINE> <DEDENT> return np.stack(img, axis=-1) | Open RGBY Human Protein Image | 625941c0baa26c4b54cb1073 |
def test_minimize_tnc38(self): <NEW_LINE> <INDENT> x0, bnds = np.array([-3, -1, -3, -1]), [(-10, 10)]*4 <NEW_LINE> xopt = [1]*4 <NEW_LINE> x = optimize.minimize(self.f38, x0, method='TNC', jac=self.g38, bounds=bnds, options=self.opts) <NEW_LINE> assert_allclose(self.f38(x), self.f38(xopt), atol=1e-8) | Minimize, method=TNC, 38 | 625941c03617ad0b5ed67e4a |
def __init__(self, helper): <NEW_LINE> <INDENT> plugin.HuttonHelperPlugin.__init__(self, helper) <NEW_LINE> self.display = None <NEW_LINE> self.data = None <NEW_LINE> self.cmdr = None <NEW_LINE> self.lastfetch = datetime.datetime.now() <NEW_LINE> self.fetching = False | Initialise the ``ProgressPlugin``. | 625941c0be7bc26dc91cd556 |
@app.route('/', methods=['POST']) <NEW_LINE> def login_user(): <NEW_LINE> <INDENT> print('LOGIN') <NEW_LINE> email = request.form.get('login-email') <NEW_LINE> password = request.form.get('login-password') <NEW_LINE> user = crud.get_user_by_email(email) <NEW_LINE> print('USER') <NEW_LINE> if user.password == password: <NEW_LINE> <INDENT> print('user password') <NEW_LINE> session['user'] = user.email <NEW_LINE> flash('Logged in!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('no user') <NEW_LINE> flash('This email is not recognized in our system') <NEW_LINE> <DEDENT> return redirect('/menu') | Login User | 625941c0596a897236089a15 |
def unit(self): <NEW_LINE> <INDENT> return _DataModel.Sensor_unit(self) | unit(Sensor self) -> std::string const & | 625941c0cdde0d52a9e52f82 |
def isEmpty(self): <NEW_LINE> <INDENT> return len(self) == 0 | post: Returns boolean indicating whether or not the Stack has any elements | 625941c0d6c5a10208143f9a |
def get_positions(self) -> np.ndarray: <NEW_LINE> <INDENT> if self._positions is not None: <NEW_LINE> <INDENT> return self._positions <NEW_LINE> <DEDENT> self._positions = np.full((self._song_len, 2), -1) <NEW_LINE> hit_circle_frames, hit_circle_positions = self._hit_circle_positions() <NEW_LINE> slider_frames, slider_positions = self._slider_positions() <NEW_LINE> spinner_frames, spinner_positions = self._spinner_positions() <NEW_LINE> slider_frames = self._flatten(slider_frames) <NEW_LINE> slider_positions = self._flatten(slider_positions) <NEW_LINE> try: <NEW_LINE> <INDENT> self._positions[hit_circle_frames, :] = hit_circle_positions <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pdb.set_trace() <NEW_LINE> <DEDENT> self._positions[slider_frames] = slider_positions <NEW_LINE> self._fill_out_remaining_positions() <NEW_LINE> return self._positions | Returns
-------
self._positions: ndarray of shape (song_len, 2)
Currently spinner events are not included. | 625941c03317a56b86939bb0 |
def write(self, data, callback): <NEW_LINE> <INDENT> if len(self._queue) < self._limit: <NEW_LINE> <INDENT> self._queue.append((data, callback)) | Queue the given data, so that it's sent later.
@param data: The data to be queued.
@param callback: The callback to use when the data is flushed. | 625941c06fece00bbac2d68e |
def test_ignore_unknown_b(self): <NEW_LINE> <INDENT> given = [ {"t": "Str", "c": "A"}, {"t": "Space"}, {"t": "Plain", "c": []}, {"t": "Str", "c": "B"}, {"t": "Plain", "c": []}, ] <NEW_LINE> expected = [ {"t": "Str", "c": "A "}, {"t": "Plain", "c": []}, {"t": "Str", "c": "B"}, {"t": "Plain", "c": []}, ] <NEW_LINE> ast = self._run(ast=given) <NEW_LINE> self.assertEqual(ast, expected) | Ensure ignoring of an unknown element type (variant B). | 625941c0cc0a2c11143dcde2 |
def getCatalog(instance, field = 'UID'): <NEW_LINE> <INDENT> uid = self.UID() <NEW_LINE> if 'workflow_skiplist' in self.REQUEST and [x for x in self.REQUEST['workflow_skiplist'] if x.find(uid) > -1]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> at = getToolByName(instance, 'archetype_tool') <NEW_LINE> plone = instance.portal_url.getPortalObject() <NEW_LINE> catalog_name = instance.portal_type in at.catalog_map and at.catalog_map[instance.portal_type][0] or 'portal_catalog' <NEW_LINE> catalog = getToolByName(plone, catalog_name) <NEW_LINE> return catalog | Return the catalog which indexes objects of instance's type.
If an object is indexed by more than one catalog, the first match
will be returned. | 625941c050485f2cf553ccea |
def __init__(self, name_study, resource, *, restart=True, force_prepare=False, dropout=False, data_processor=None, network=None, optimizer=None): <NEW_LINE> <INDENT> self.name_study = name_study <NEW_LINE> self.resource = resource <NEW_LINE> self.restart = restart <NEW_LINE> self.dropout = dropout <NEW_LINE> self.data_processor = data_processor <NEW_LINE> self.network = network <NEW_LINE> self.optimizer = optimizer <NEW_LINE> self.is_gpu_supporting = self._detect_gpu() <NEW_LINE> logger.info(f"GPU: {self.is_gpu_supporting}") <NEW_LINE> self.read_model_dir = resource.get_model_dir <NEW_LINE> self.save_model_dir = resource.get_model_dir <NEW_LINE> self.read_model_path = "{}/{}".format(self.read_model_dir, name_study) <NEW_LINE> self.save_model_path = "{}/{}".format(self.save_model_dir, name_study) <NEW_LINE> logger.info(f"Read model path: {self.read_model_path}") <NEW_LINE> logger.info(f"Save model path: {self.save_model_path}") <NEW_LINE> self.ratio_test_train = .01 <NEW_LINE> self.n_monitor = 1 <NEW_LINE> self.data_processor.prepare(force_prepare=force_prepare) | Initialize Trainer object.
Args:
name_study: string
name of study, which is used to generate model directory.
resource: Resource
Resource Object.
restart: bool, optional [True]
If True restart the interrupted training. Else, start new
training.
dropout: bool, optional [False]
If True, apply dropout for the last hidden layer.
data_processor: DataProcessor, optpnal [None]
Data processor. Used prepare calculate from data.
network: NetworkObject, optional [None]
Network. Used for special settings like graph
optimizer: OptimizerObject, optional [None]
Optimizer. Used for training. | 625941c04c3428357757c27c |
def get_interface_informations(self, iface): <NEW_LINE> <INDENT> pass | Gets all useful informations from an iface
* name
* dotted name
* trimmed doc string
* base interfaces
* methods with signature and trimmed doc string
* attributes with trimemd doc string | 625941c02eb69b55b151c7fe |
def bisection_insert_0(entry, list, index_low=0, index_high=-2, offset_odd=1): <NEW_LINE> <INDENT> if (index_high==-2): <NEW_LINE> <INDENT> index_high = len(list)-1 <NEW_LINE> index_low = 0 <NEW_LINE> <DEDENT> index_bisector = (index_high+index_low+offset_odd) // 2 <NEW_LINE> while (index_high >= index_low): <NEW_LINE> <INDENT> if entry < list[index_bisector]: <NEW_LINE> <INDENT> index_high = index_bisector-1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index_low = index_bisector+1 <NEW_LINE> <DEDENT> index_bisector = (index_high+index_low+offset_odd) // 2 <NEW_LINE> <DEDENT> list.insert(index_low,entry) <NEW_LINE> return(index_low) | Original, not recursive
Returns the index where the entry was inserted | 625941c0f548e778e58cd4ce |
def revenue_predict_ind(data, reg): <NEW_LINE> <INDENT> df = data.copy().dropna(axis='columns') <NEW_LINE> cond = (df.END_DATE==2018)&(df.FISCAL_PERIOD==2) <NEW_LINE> df_tr, df_te = df[~cond].values, df[cond].values <NEW_LINE> tr_x, tr_y = df_tr[:,4:], df_tr[:,3:4] <NEW_LINE> te_x = df_te[:,4:] <NEW_LINE> if len(te_x)>0: <NEW_LINE> <INDENT> reg.fit(tr_x,tr_y) <NEW_LINE> return reg.predict(te_x)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.nan | XGBoost模型构建 | 625941c0de87d2750b85fce2 |
def create_cli(self, *a, **kw): <NEW_LINE> <INDENT> kw['renderer'] = Renderer(output=self.vt100_output) <NEW_LINE> return CommandLineInterface(self.eventloop, *a, **kw) | Create a `CommandLineInterface` instance. But use a
renderer that outputs over the telnet connection, and use
the eventloop of the telnet server.
All parameters are send to ``CommandLineInterface.__init__``. | 625941c04a966d76dd550f5f |
def open(self): <NEW_LINE> <INDENT> if not self._canvasOpen: <NEW_LINE> <INDENT> self._update( {'visible' : True } ) <NEW_LINE> self._canvasOpen = True <NEW_LINE> _graphicsManager._openCanvases.append(self) | Opens a graphic window (if not already open).
The window can be closed with a subsequent call to close(). | 625941c0507cdc57c6306c27 |
def compute_partial_loss(self, y, f): <NEW_LINE> <INDENT> return self.gdiff(f) | :param y:
:param f:
:return: | 625941c0d164cc6175782c9f |
def step(x): <NEW_LINE> <INDENT> f = 30. <NEW_LINE> for c in x: <NEW_LINE> <INDENT> if abs(c) <= 5.12: <NEW_LINE> <INDENT> f += floor(c) <NEW_LINE> <DEDENT> elif c > 5.12: <NEW_LINE> <INDENT> f += 30 * (c - 5.12) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f += 30 * (5.12 - c) <NEW_LINE> <DEDENT> <DEDENT> return f | De Jong's step function:
The third De Jong function, Equation (19) of [2]
minimum is f(x)=0.0 at xi=-5-n where n=[0.0,0.12] | 625941c09c8ee82313fbb6c6 |
def public_upload(request): <NEW_LINE> <INDENT> upload_success = False <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> document = Document.objects.get(id=request.POST.get("inputDocument", None)) <NEW_LINE> if document: <NEW_LINE> <INDENT> uploaded_image = request.FILES.get("inputFile", None) <NEW_LINE> if uploaded_image: <NEW_LINE> <INDENT> image = DocumentImage( document=document, image=uploaded_image, name=document.word, confirmed=False, ) <NEW_LINE> image.save() <NEW_LINE> upload_success = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> missing_images = Document.objects.values_list( "id", "word", "article", "training_sets" ).filter(document_image__isnull=True) <NEW_LINE> training_sets = ( TrainingSet.objects.values_list("id", "title") .filter(documents__document_image__isnull=True) .distinct() ) <NEW_LINE> disciplines = ( Discipline.objects.values_list("id", "title") .filter(training_sets__isnull=False) .filter(training_sets__documents__document_image__isnull=True) .distinct() ) <NEW_LINE> disc_sets_map = ( Discipline.objects.values_list("id", "training_sets__id") .filter(training_sets__isnull=False) .filter(training_sets__documents__document_image__isnull=True) .distinct() ) <NEW_LINE> new_map = {} <NEW_LINE> for (key, value) in disc_sets_map: <NEW_LINE> <INDENT> if key in new_map: <NEW_LINE> <INDENT> new_map[key].append(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_map[key] = [value] <NEW_LINE> <DEDENT> <DEDENT> context = { "documents": json.dumps(list(missing_images)), "disciplines": json.dumps(list(disciplines)), "disc_sets_map": json.dumps(new_map), "training_sets": json.dumps(list(training_sets)), "upload_success": upload_success, } <NEW_LINE> return render(request, "public_upload.html", context) | Public form to upload missing images
:param request: current user request
:type request: django.http.request
:return: rendered response
:rtype: HttpResponse | 625941c0f7d966606f6a9f53 |
def _map_to_genomic_coordinates(hgvs_variant, remapper): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chrom, pos, ref, alt = remapper.hgvs_to_vcf(hgvs_variant) <NEW_LINE> return pd.Series({'CHROM': chrom, 'POS': pos, 'ID': hgvs_variant, 'REF': ref, 'ALT': alt}) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return pd.Series({'CHROM': '.', 'POS': '.', 'ID': '.', 'REF': '.', 'ALT': '.'}) | Helper function to use with pandas.DataFrame.apply. Converts HGVS entries to VCF format.
Args:
hgvs_variant (str): HGVS formatted variant
remapper (leiden.remapping.VariantRemapper): VariantRemapper (accepted as parameter because creation is expensive)
Returns:
pandas.DataSeries: VCF representation of variant | 625941c0baa26c4b54cb1074 |
def vershik_kerov_logan_shepp(n): <NEW_LINE> <INDENT> if(n != int(n)): <NEW_LINE> <INDENT> raise ValueError( "n must be integer" ) <NEW_LINE> <DEDENT> return 2 * math.sqrt(n) | Returns asymptotic value of ℓn for large n.
For a permutation σ∈Sn, let ℓ(σ) denote the maximal length of an increasing subsequence in σ.
Define ℓn = (1/n!) * ∑(σ∈Sn) ℓ(σ),
the average value of ℓ(σ) for a σ chosen uniformly at random from Sn.
Parameters
----------
n : int
denotes n in vershik equation as stated above
return : float
returns float number denoting asymptotic value of ℓn. | 625941c0d268445f265b4dc0 |
def __init__(self, parent=None): <NEW_LINE> <INDENT> super().__init__(parent); <NEW_LINE> tabBar=EditableTabBar(parent); <NEW_LINE> self.setTabBar(tabBar); | Constructor
Sets the tabBar to an EditableTabBar. | 625941c010dbd63aa1bd2af8 |
def testSwig2Colinearize2D2(self): <NEW_LINE> <INDENT> coo=DataArrayDouble([(0,0),(0,0.5),(0,1),(1,1),(1,0),(0.5,0)]) <NEW_LINE> m=MEDCouplingUMesh("mesh",2) ; m.setCoords(coo) <NEW_LINE> m.allocateCells() ; m.insertNextCell(NORM_POLYGON,[0,1,2,3,4,5]) <NEW_LINE> m.checkCoherency2() <NEW_LINE> refPtr=m.getCoords().getHiddenCppPointer() <NEW_LINE> m.colinearize2D(1e-12) <NEW_LINE> m.checkCoherency2() <NEW_LINE> self.assertEqual(refPtr,m.getCoords().getHiddenCppPointer()) <NEW_LINE> self.assertTrue(m.getNodalConnectivity().isEqual(DataArrayInt([5,0,2,3,4]))) <NEW_LINE> self.assertTrue(m.getNodalConnectivityIndex().isEqual(DataArrayInt([0,5]))) <NEW_LINE> pass | simple non regression test but that has revealed a bug | 625941c03346ee7daa2b2cbc |
def test_docs_by_tag9(flask_client, user7): <NEW_LINE> <INDENT> response = flask_client.get("/to-read/tag/tag0", follow_redirects=True) <NEW_LINE> assert b"You don't have any to-read items." in response.data | docs_by_tag() displays appropriate error message to user. | 625941c0287bf620b61d39b7 |
def get_clickwrap_agreements(self, account_id, clickwrap_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.get_clickwrap_agreements_with_http_info(account_id, clickwrap_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_clickwrap_agreements_with_http_info(account_id, clickwrap_id, **kwargs) <NEW_LINE> return data | Gets the agreement responses for a clickwrap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_clickwrap_agreements(account_id, clickwrap_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str account_id: (required)
:param str clickwrap_id: (required)
:param str client_user_id:
:param str from_date:
:param str page_number:
:param str status:
:param str to_date:
:return: ClickwrapAgreementsResponse
If the method is called asynchronously,
returns the request thread. | 625941c0d486a94d0b98e097 |
def test_build_network_settings(self): <NEW_LINE> <INDENT> with patch('salt.modules.debian_ip._parse_network_settings', MagicMock(return_value={'networking': 'yes', 'hostname': 'Salt.saltstack.com', 'domainname': 'saltstack.com', 'search': 'test.saltstack.com'})), patch('salt.modules.debian_ip._write_file_network', MagicMock(return_value=True)): <NEW_LINE> <INDENT> with patch.dict(debian_ip.__grains__, {'osfullname': 'Ubuntu', 'osrelease': '14'}): <NEW_LINE> <INDENT> mock = MagicMock(return_value=True) <NEW_LINE> with patch.dict(debian_ip.__salt__, {'service.available': mock, 'service.disable': mock, 'service.enable': mock}): <NEW_LINE> <INDENT> self.assertEqual(debian_ip.build_network_settings(), ['NETWORKING=yes\n', 'HOSTNAME=Salt\n', 'DOMAIN=saltstack.com\n', 'SEARCH=test.saltstack.com\n']) <NEW_LINE> mock = MagicMock(side_effect=jinja2.exceptions.TemplateNotFound ('error')) <NEW_LINE> with patch.object(jinja2.Environment, 'get_template', mock): <NEW_LINE> <INDENT> self.assertEqual(debian_ip.build_network_settings(), '') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with patch.dict(debian_ip.__grains__, {'osfullname': 'Ubuntu', 'osrelease': '10'}): <NEW_LINE> <INDENT> mock = MagicMock(return_value=True) <NEW_LINE> with patch.dict(debian_ip.__salt__, {'service.available': mock, 'service.disable': mock, 'service.enable': mock}): <NEW_LINE> <INDENT> mock = MagicMock(side_effect=jinja2.exceptions.TemplateNotFound ('error')) <NEW_LINE> with patch.object(jinja2.Environment, 'get_template', mock): <NEW_LINE> <INDENT> self.assertEqual(debian_ip.build_network_settings(), '') <NEW_LINE> <DEDENT> with patch.object(debian_ip, '_read_temp', MagicMock(return_value=True)): <NEW_LINE> <INDENT> self.assertTrue(debian_ip.build_network_settings (test='True')) | Test if it build the global network script. | 625941c026238365f5f0edbd |
def _CreateParentsAndOpen(self, path): <NEW_LINE> <INDENT> directory = os.path.dirname(path) <NEW_LINE> if not os.path.exists(directory): <NEW_LINE> <INDENT> os.makedirs(directory) <NEW_LINE> <DEDENT> return open(path, 'w') | Opens a file for writing, recursively creating subdirs if needed. | 625941c08da39b475bd64ec3 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, NewWorksheetData): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941c082261d6c526ab3ee |
def fldiff(self, args): <NEW_LINE> <INDENT> opts = { 'tolerance': args.tolerance, 'ignore': not args.include, 'ignoreP': not args.includeP, 'use_yaml': not args.no_yaml, 'use_fl': not args.no_fl, 'debug': args.debug, } <NEW_LINE> yaml_test = { 'file': args.yaml_conf } <NEW_LINE> ref_name, test_name = args.ref_file, args.test_file <NEW_LINE> differ = Differ(yaml_test, **opts) <NEW_LINE> try: <NEW_LINE> <INDENT> fld_result = differ.diff(ref_name, test_name) <NEW_LINE> print(fld_result.dump_details()) <NEW_LINE> isok, _, _ = fld_result.passed_within_tols(0, 0.0, 0.0) <NEW_LINE> ecode = 0 if isok else 1 <NEW_LINE> exit(ecode) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print('Something went wrong with this test:\n{}\n'.format(str(e))) <NEW_LINE> exit(1) | diff subcommand, manual access to pymods.fldiff.Differ | 625941c063d6d428bbe44441 |
def create_connection(db_file=r"./database/sqlite.db"): <NEW_LINE> <INDENT> conn = None <NEW_LINE> try: <NEW_LINE> <INDENT> conn = sqlite3.connect(db_file) <NEW_LINE> return conn <NEW_LINE> <DEDENT> except Error as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> return conn | create a database connection to a SQLite database | 625941c05fcc89381b1e160f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.