code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def qs_by_time(qs, current): <NEW_LINE> <INDENT> qs = qs.filter(timestamp__year=current.year, timestamp__month=current.month, timestamp__day=current.day).count() <NEW_LINE> return qs if qs > 0 else None | Filter action queryset on daily basis. Pass qs to filter and current
time to compare to. It returns number or None if count is 0. | 625941d57d847024c06be4c5 |
def __call__(self, uri, **kwargs): <NEW_LINE> <INDENT> if uri in self.store: <NEW_LINE> <INDENT> return self.store[uri] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = self.get_remote_json(uri, **kwargs) <NEW_LINE> if self.cache_results: <NEW_LINE> <INDENT> self.store[uri] = result <NEW_LINE> <DEDENT> return res... | Return the loaded JSON referred to by `uri`
:param uri: The URI of the JSON document to load
:param kwargs: Keyword arguments passed to :func:`json.loads` | 625941d5a17c0f6771cbe257 |
def do_task(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.luks.luks_version == "luks2": <NEW_LINE> <INDENT> blockdev.crypto.luks_resize(self.luks.map_name, self.luks.target_size.convert_to(self.unit), passphrase=self.luks._LUKS__passphrase, key_file=self.luks._key_file) <NEW_LINE> <DEDENT> else: <NEW_LINE... | Resizes the LUKS format. | 625941d59c8ee82313fbb97d |
def parse_backend(arrays: Sequence[ArrayType], backend: str) -> str: <NEW_LINE> <INDENT> if backend != "auto": <NEW_LINE> <INDENT> return backend <NEW_LINE> <DEDENT> backend = infer_backend(arrays[0]) <NEW_LINE> if not backends.has_tensordot(backend): <NEW_LINE> <INDENT> return "numpy" <NEW_LINE> <DEDENT> return backen... | Find out what backend we should use, dipatching based on the first
array if ``backend='auto'`` is specified. | 625941d5f548e778e58cd786 |
def __str__(self): <NEW_LINE> <INDENT> return "Expression of CPE language version {0}:\n{1}".format( self.VERSION, self.expression) | Returns a human-readable representation of CPE Language expression.
:returns: Representation of CPE Language expression as string
:rtype: string | 625941d5293b9510aa2c349c |
def decode_data(source, delimiter='\n'): <NEW_LINE> <INDENT> for keymarkerpair in keys.data(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> source_decoded = base64.b64decode(source) <NEW_LINE> values = decrypt(source_decoded, keymarkerpair[0]).split(delimiter) <NEW_LINE> if values[0] == keymarkerpair[1]: <NEW_LINE> <IN... | decode data
| 625941d555399d3f055888bc |
def str_skills_to_numbers(skills): <NEW_LINE> <INDENT> return [int(d.split(const.SEPARATOR_SKILL)[1]) for d in skills] | Converts string with skills read from a file to integers. List has format: [H, E, P]. | 625941d5a8370b7717052aa6 |
def plot(self, method='plot', **kwargs): <NEW_LINE> <INDENT> from ..plot import Plot <NEW_LINE> from ..plot.text import default_unit_label <NEW_LINE> if kwargs.get('xscale') == 'log' and self.x0.value == 0: <NEW_LINE> <INDENT> kwargs.setdefault('xlim', (self.dx.value, self.xspan[1])) <NEW_LINE> <DEDENT> plot = Plot(sel... | Plot the data for this series
Returns
-------
figure : `~matplotlib.figure.Figure`
the newly created figure, with populated Axes.
See also
--------
matplotlib.pyplot.figure
for documentation of keyword arguments used to create the
figure
matplotlib.figure.Figure.add_subplot
for documentation of keywor... | 625941d571ff763f4b549896 |
def set_attr_value(self, key, attr, value): <NEW_LINE> <INDENT> idx = self._keys[key] <NEW_LINE> self._attrs[attr][idx].set(value) | set the value of a given attribute for a given key
| 625941d5009cb60464c635b8 |
def get_transform_dest_array(output_size): <NEW_LINE> <INDENT> bottom_right = [output_size[0] - 1, output_size[1] - 1] <NEW_LINE> bottom_left = [0, output_size[1] - 1] <NEW_LINE> top_left = [0, 0] <NEW_LINE> top_right = [output_size[0] - 1, 0] <NEW_LINE> return np.array( [bottom_right, bottom_left, top_left, top_right]... | Returns a destination array of the desired size. This is also used to define the
order of points necessary for cv2.getPerspectiveTransform: the order can change, but
it must remain consistent between these two arrays.
:param output_size: The size to make the output image ((width, height) tuple)
:return: The destination... | 625941d515baa723493c417e |
def is_signed_token_revoked(self, signed_text): <NEW_LINE> <INDENT> revocation_list = self.token_revocation_list <NEW_LINE> revoked_tokens = revocation_list.get('revoked', []) <NEW_LINE> if not revoked_tokens: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> revoked_ids = (x['id'] for x in revoked_tokens) <NEW_LINE> toke... | Indicate whether the token appears in the revocation list. | 625941d501c39578d7e75043 |
def test_ldp_cut_thru_iperf3(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subprocess.check_output(['iperf3', '-v']) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> self.logger.error( "WARNING: Subprocess returned non-0 running 'iperf3 -v") <NEW_LINE> self.logger.error(" 'tes... | run LDP cut thru iperf3 test | 625941d5c432627299f04e4f |
def __init__(self, data_path, file_name): <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> self.data['version'] = config_data.BIND10_CONFIG_DATA_VERSION <NEW_LINE> if os.path.isabs(file_name): <NEW_LINE> <INDENT> self.db_filename = file_name <NEW_LINE> self.data_path = os.path.dirname(file_name) <NEW_LINE> <DEDENT> else: ... | Initialize the data for the configuration manager, and
set the version and path for the data store. Initializing
this does not yet read the database, a call to
read_from_file is needed for that.
In case the file_name is absolute, data_path is ignored
and the directory where the file_name lives is used instead. | 625941d5d486a94d0b98e34e |
@requires_cftime <NEW_LINE> @pytest.mark.parametrize( ("calendar", "freq"), zip(["gregorian", "proleptic_gregorian"], ["1D", "1M", "1Y"]) ) <NEW_LINE> def test_get_clean_interp_index_dt(cf_da, calendar, freq): <NEW_LINE> <INDENT> g = cf_da(calendar, freq=freq) <NEW_LINE> g["stime"] = xr.Variable(data=g.time.to_index().... | In the gregorian case, the index should be proportional to normal datetimes. | 625941d58e05c05ec3eea57e |
def logLik_from_mahalanobis(stim, mu_x, cov, k=None): <NEW_LINE> <INDENT> if k is None: <NEW_LINE> <INDENT> k = 0 <NEW_LINE> <DEDENT> stim = np.array(stim) <NEW_LINE> mu_x = np.array(mu_x) <NEW_LINE> inv_covmat = np.linalg.inv(cov) <NEW_LINE> s_minus_mu = stim - mu_x <NEW_LINE> log_p = k - np.dot(np.dot(s_minus_mu.T, i... | calculate the log likelihood of the current image given the presumed
'system state' mu_x and covariance matrix cov based on the mahalanobis
distance between image feature vector and vector representing the system
state | 625941d5b830903b967e9b11 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(WrenchMonitorLimit, self).__init__(*args, **kwds) <NEW_LINE> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.name is None: <NEW_LINE> <INDENT> self.name = [] <NEW... | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
header,name,force,torque,isFractio... | 625941d5ac7a0e7691ed42d1 |
def testTagUpdate(self): <NEW_LINE> <INDENT> pass | Test TagUpdate | 625941d567a9b606de4a80c0 |
def read_all(self): <NEW_LINE> <INDENT> if self.processor: <NEW_LINE> <INDENT> data = self.processor.finish() <NEW_LINE> <DEDENT> if data: <NEW_LINE> <INDENT> self.buffer = ''.join([self.buffer, data]) <NEW_LINE> <DEDENT> last_block = self.buffer <NEW_LINE> self.buffer = str() <NEW_LINE> print(">>>> Buffer last block: ... | Force process and retrieve all remaining data from buffer. | 625941d5cad5886f8bd271e1 |
def alter_and_get(self, function: typing.Any) -> Future[int]: <NEW_LINE> <INDENT> check_not_none(function, "Function cannot be None") <NEW_LINE> function_data = self._to_data(function) <NEW_LINE> codec = atomic_long_alter_codec <NEW_LINE> request = codec.encode_request(self._group_id, self._object_name, function_data, ... | Alters the currently stored value by applying a function on it and
gets the result.
Notes:
``function`` must be an instance of Hazelcast serializable type.
It must have a counterpart registered in the server-side that
implements the ``com.hazelcast.core.IFunction`` interface with
the actual logic of th... | 625941d563d6d428bbe446f8 |
def load_config(self): <NEW_LINE> <INDENT> self.config = config = ConfigParser() <NEW_LINE> self.build_config(config) <NEW_LINE> if len(config.sections()) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> filename = self.get_application_config() <NEW_LINE> if filename is None: <NEW_LINE> <INDENT> return config <NEW_... | (internal) This function is used for returning a ConfigParser with
the application configuration. It's doing 3 things:
#. Create an instance of a ConfigParser
#. Load the default configuration by calling
:meth:`build_config`, then
#. If exist, load the application configuration file, or create it
... | 625941d50c0af96317bb83f0 |
def remotes(cwd, user=None, ignore_retcode=False): <NEW_LINE> <INDENT> cwd = _expand_path(cwd, user) <NEW_LINE> command = ['git', 'remote', '--verbose'] <NEW_LINE> ret = {} <NEW_LINE> output = _git_run(command, cwd=cwd, runas=user, ignore_retcode=ignore_retcode)['stdout'] <NEW_LINE> for remote_line in output.splitlines... | Get fetch and push URLs for each remote in a git checkout
cwd
The path to the git checkout
user
User under which to run the git command. By default, the command is run
by the user under which the minion is running.
ignore_retcode : False
If ``True``, do not log an error to the minion log if the git c... | 625941d55e10d32532c5f12e |
def _get_objects(self, parent, rel, params=None): <NEW_LINE> <INDENT> if parent: <NEW_LINE> <INDENT> return self._follow_resource_link(parent, rel, params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( "Parent resource does not and it can not fetch collection by link relation %s." % rel.link_rel) | GET the link href of parent resource for system object
:param parent: parent resource
:param rel: link relation
:param params: URL parameters
:return: system objects | 625941d599cbb53fe6792dee |
def isEmpty(self): <NEW_LINE> <INDENT> return bool() | bool Plasma.DataEngine.isEmpty() | 625941d516aa5153ce36267f |
def _load_interface(self): <NEW_LINE> <INDENT> self.log.debug('Loading interface: ' + self.name) <NEW_LINE> if hasattr(self.module_import, 'Interface'): <NEW_LINE> <INDENT> self.log.debug('Loading {name} Interface'.format(name=self.name)) <NEW_LINE> self.interface_class = getattr(self.module_import, 'Interface') <NEW_L... | Attempt to load the Interface class | 625941d51f037a2d8b946406 |
def parse_csv_frbr(raw_rows): <NEW_LINE> <INDENT> expr_lst,item_lst,manf_lst,work_lst = [],[],[],[] <NEW_LINE> for i,row in enumerate(raw_rows): <NEW_LINE> <INDENT> row = row.replace('"','') <NEW_LINE> rec = row.split(",") <NEW_LINE> if len(rec) < 5: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> entity = rec[9] <NEW_LI... | Takes a list of csv fields, assigns values to four dicts for FRBR Level
entities of Work,Expression,Manifestation, and Item using regular
expressions.
:param raw_rows: String with common-separated fields
:rtype tuple: Returns a four element tuple with each element being a
list of fields for a level one e... | 625941d529b78933be1e58b1 |
def graficar(self, analitica = False): <NEW_LINE> <INDENT> def rAnalitica(self): <NEW_LINE> <INDENT> return (self.kr/self.gamma_r)*(1-np.exp(-self.gamma_r*self.t)) <NEW_LINE> <DEDENT> def pAnalitica(self): <NEW_LINE> <INDENT> coeff = (self.kr*self.kp)/(self.gamma_r*self.gamma_p) <NEW_LINE> second = (1-np.exp(-self.gamm... | Plots rt and pt | 625941d51b99ca400220acba |
def _test_add(data, fused_activation_function=None, quantized=False, qnn_op=None): <NEW_LINE> <INDENT> return _test_elemwise(math_ops.add, data, fused_activation_function, quantized, qnn_op) | One iteration of add | 625941d59f2886367277aa94 |
def get_absolute_url(self) -> str: <NEW_LINE> <INDENT> return reverse( "data:dataset_detail", kwargs={"study_name": self.study.name, "dataset_name": self.name}, ) | Returns a canonical URL for the model using the "study" and "name" fields | 625941d5236d856c2ad449e4 |
def mousePressEvent(self, event): <NEW_LINE> <INDENT> pass | void Plasma.WallpaperScript.mousePressEvent(QGraphicsSceneMouseEvent event) | 625941d5099cdd3c635f0e62 |
def init_app(self, app): <NEW_LINE> <INDENT> self.init = True <NEW_LINE> self._sessions = {} <NEW_LINE> self._init_sessions(app) <NEW_LINE> app.teardown_appcontext(self.exit_sessions) | :type app: flask.Flask | 625941d5d7e4931a7ee9e126 |
def do_removenetwork(self, line): <NEW_LINE> <INDENT> args = shlex.split(line) <NEW_LINE> if (len(args) == 0): <NEW_LINE> <INDENT> print("Usage:") <NEW_LINE> self.do_help('remove-network') <NEW_LINE> return <NEW_LINE> <DEDENT> if (len(args) < 1): <NEW_LINE> <INDENT> print("Please specify a network id") <NEW_LINE> retur... | remove-network <network-id>
Remove a provisioned network. | 625941d5d6c5a10208144254 |
def server_broadcast(msg, prefix=""): <NEW_LINE> <INDENT> for sock in clients: <NEW_LINE> <INDENT> sock.send(bytes(prefix, "utf8") + msg) | Server broadcast a message to all the clients. | 625941d5eab8aa0e5d26dd60 |
def clone(self): <NEW_LINE> <INDENT> return _robotsim.Geometry3D_clone(self) | clone(Geometry3D self) -> Geometry3D
Creates a standalone geometry from this geometry. | 625941d53617ad0b5ed680fe |
def _build_newsletter_section( changes: List[Change], section_attr: str, subsection_attr: Optional[str], ) -> Tuple[NewsletterSection, List[Change]]: <NEW_LINE> <INDENT> section = NewsletterSection( title=getattr(changes[0], section_attr), order=getattr(changes[0], f"{section_attr}_order"), ) <NEW_LINE> subsection_chan... | Create a newsletter section from the changes.
Ignore changes that are not part of CHANGE_TYPE_TEXT.
Args:
changes: The list of Change objects of the section.
section_attr: Change attribute name that represents the section.
subsection_attr: Change attribute name that represents the subsection.
Returns:
... | 625941d50c0af96317bb83f1 |
def get_method_documents(self, path): <NEW_LINE> <INDENT> cls_object = self.resource.__class__ <NEW_LINE> path = '/%s/' % path <NEW_LINE> try: <NEW_LINE> <INDENT> current_url = [url for url in self.resource.urls if path in url.regex.pattern][0] <NEW_LINE> method_name = current_url.name.replace('api_', '').strip() <NEW_... | Get document of method in Resource by url path
:param path: URL path in extra_action
:return:
Document of method | 625941d5627d3e7fe0d69059 |
def get_network(self, network_name): <NEW_LINE> <INDENT> network = self.get_obj(vimtype=vim.Network, name=network_name) <NEW_LINE> if not network: <NEW_LINE> <INDENT> raise NotFoundError <NEW_LINE> <DEDENT> return network | Fetch the network object from specified network name
Args:
network_name: The name of the network from Vmware
Returns: A object of vim.Network object | 625941d5507cdc57c6306ee6 |
def preview_page(self, request, object_id): <NEW_LINE> <INDENT> page = get_object_or_404(Page, id=object_id) <NEW_LINE> attrs = "?preview=1" <NEW_LINE> if request.REQUEST.get('public', None): <NEW_LINE> <INDENT> if not page.publisher_public_id: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> page = page.publisher... | Redirecting preview function based on draft_id
| 625941d5c4546d3d9de72c3d |
def distance_transform(img, kind=Distance.Cityblock): <NEW_LINE> <INDENT> if not is_binary(img): <NEW_LINE> <INDENT> logger.error("distance_transform: input should be binary") <NEW_LINE> return img <NEW_LINE> <DEDENT> row_num, col_num = img.shape <NEW_LINE> if kind == Distance.Cityblock: <NEW_LINE> <INDENT> temp0 = np.... | Perform distance transformation
:param img: binary image
:param kind: what kind of distance is chosen
:return: transformed image, un-normalized | 625941d5a8ecb033257d32d4 |
def unauthorized(self, message): <NEW_LINE> <INDENT> response = jsonify({"error": message}) <NEW_LINE> return make_response(response), self.unauthorized_status | When the equest has an invalid token | 625941d52eb69b55b151cab9 |
def legalize(filename): <NEW_LINE> <INDENT> state = 0 <NEW_LINE> result = [] <NEW_LINE> start_regexes = [re.compile(r"^" + x + r" {$") for x in BLACKLIST] <NEW_LINE> open_regex = re.compile(r"^.* {$") <NEW_LINE> close_regex = re.compile(r"^}") <NEW_LINE> with open(filename, "r") as src_file: <NEW_LINE> <INDENT> for lin... | Remove unnecessary stuff from a Clarisse config file.
We have to do this to clarisse.cfg file (or whatever the user chooses to
call it) so that it doesn't crash the rendernode. It seems that some of the
UI configuration causes the crash, especially when shipped from Windows.
The algorithm relies on the config file f... | 625941d5f7d966606f6aa20e |
def task_message_user(request, task, message, level=messages.SUCCESS): <NEW_LINE> <INDENT> task_url = task.flow_task.get_task_url(task, url_type='details', user=request.user) <NEW_LINE> message = 'Task <a href="{}">{}</a> {}'.format(task_url, task.pk, message) <NEW_LINE> messages.add_message(request, level, mark_safe(m... | Message to the user prefixed with task link. | 625941d5377c676e912723b0 |
def step(x, g): <NEW_LINE> <INDENT> return lambda a: g(fn(a, x)) | *** YOUR CODE HERE *** | 625941d53317a56b86939e5d |
def calculate_third_layer_arithmetic_mean(sl3, sl4, sl5, sl6, sl7, total_depth): <NEW_LINE> <INDENT> d1 = 0.1 <NEW_LINE> d3 = 0.5 <NEW_LINE> second_layer = total_depth - (d1 + d3) <NEW_LINE> second_layer_depth = d1 + second_layer <NEW_LINE> if second_layer_depth >= 0.1 and total_depth <= 1.0: <NEW_LINE> <INDENT> return... | sl3: 0.15m, sl4: 0.3m, sl5: 0.6m, sl6: 1m, sl7: 2m
takes in sl3-7 and returns arithmetic mean of whatever layers are included in the profile | 625941d524f1403a92600d6d |
def purge_versions(path, suffix, num_keep, reverse=False): <NEW_LINE> <INDENT> (base, ext) = os.path.splitext(path) <NEW_LINE> re_strip_version = re.compile('(.*)-%s(-[0-9]*)?' % suffix) <NEW_LINE> matched = re_strip_version.match(base) <NEW_LINE> if matched: <NEW_LINE> <INDENT> base = matched.group(1) <NEW_LINE> <DEDE... | Purge file versions created by get_versioned_path.
Purge specified quantity in normal or reverse sequence. | 625941d5d8ef3951e3243746 |
def __init__(self, name, uid, spec, file): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._uid = uid <NEW_LINE> self._spec = spec <NEW_LINE> self._file = file | Not usually called directly. Use get_device_config(s) | 625941d556b00c62f0f14862 |
def delete(self,key): <NEW_LINE> <INDENT> def record_deleted(node): <NEW_LINE> <INDENT> if node.val < key: <NEW_LINE> <INDENT> return self.INode(node.val, node.left, record_deleted(node.right)) <NEW_LINE> <DEDENT> if node.val > key: <NEW_LINE> <INDENT> return self.INode(node.val, record_deleted(node.left), node.right) ... | Delete key from the tree, creating a new version of the tree. If key does not exist in the current version of the tree, then do nothing and refrain from creating a new version. | 625941d5091ae35668667164 |
def _sentence_to_ids(sentence, vocab): <NEW_LINE> <INDENT> ids = [vocab.get(w, special_words.UNK) for w in sentence] <NEW_LINE> return ids | Helper for converting a sentence (list of words) to a list of ids. | 625941d5e5267d203edcdea3 |
@context_api.require_context <NEW_LINE> def vm_save(context, vm): <NEW_LINE> <INDENT> if vm is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> session = None <NEW_LINE> try: <NEW_LINE> <INDENT> session = nova_session.get_session() <NEW_LINE> epoch_time = get_current_epoch_ms() <NEW_LINE> vms = vm_get_by_ids(contex... | This API will create or update a Vm object and its associations to DB.
For the update to be working the VM object should have been
one returned by DB API. Else it will be considered as a insert.
Parameters:
vm - Vm type object to be saved
context - nova.context.RequestContext object | 625941d55510c4643540f5e9 |
def inspect_relax(self): <NEW_LINE> <INDENT> workchain = self.ctx.workchain_relax <NEW_LINE> if not workchain.is_finished_ok: <NEW_LINE> <INDENT> self.report( "PwRelaxWorkChain failed with exit status {}".format( workchain.exit_status ) ) <NEW_LINE> return self.exit_codes.ERROR_SUB_PROCESS_FAILED_RELAX <NEW_LINE> <DEDE... | Verify that the PwRelaxWorkChain finished successfully. | 625941d5851cf427c661a716 |
def setFactory(self, factory): <NEW_LINE> <INDENT> pass | void KXMLGUIClient.setFactory(KXMLGUIFactory factory) | 625941d5046cf37aa974cf4f |
def get_order(self, order_uuid, trade_time_limit): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> order_data = self.Bittrex.get_order(order_uuid) <NEW_LINE> while time.time() - start_time <= trade_time_limit and order_data["result"]["IsOpen"]: <NEW_LINE> <INDENT> time.sleep(10) <NEW_LINE> order_data = self.Bit... | Used to get an order from Bittrex by it's UUID.
First wait until the order is completed before retrieving it.
If the order is not completed within trade_time_limit seconds, cancel it.
:param order_uuid: The order's UUID
:type order_uuid: str
:param trade_time_limit: The time in seconds to wait fot the order before can... | 625941d556b00c62f0f14863 |
def empty_doc_vars(self): <NEW_LINE> <INDENT> self.doc_vars = {} | Empty doc_vars dictionary. | 625941d53c8af77a43ae39aa |
def saveControlForces(self, element): <NEW_LINE> <INDENT> self._controller.saveControlForces(element) <NEW_LINE> return | Once the state history is created, this method saves a state at a given time in a certain position of the state history.
:param element:
:return: | 625941d5bd1bec0571d90838 |
def test_vote_plus(self): <NEW_LINE> <INDENT> self.resource._request.register_uri( 'PUT', '/users/dotzero/vote') <NEW_LINE> response = self.resource.vote_plus('dotzero') <NEW_LINE> self.assertEqual(response['ok'], 1) <NEW_LINE> self.assertTrue('server_time' in response) | Test UserResource.vote_plus(login) method | 625941d56e29344779a6281a |
def retrieve_blog_site_data(dbinfo): <NEW_LINE> <INDENT> blogs = get_ranked_blogs(dbinfo, MAXIMUM_BLOG_COUNT) <NEW_LINE> for blog in blogs: <NEW_LINE> <INDENT> print(timestamp() + 'Blog: ' + str(blog)) <NEW_LINE> (blog_id, blog_link, blog_rank) = blog <NEW_LINE> html = retrieve_page(dbinfo, blog_link) <NEW_LINE> if htm... | Retrieve RSS feeds and blog postings from ranked blogs. | 625941d5711fe17d82542572 |
def run_corr(samples, corr): <NEW_LINE> <INDENT> from scipy.linalg import cholesky <NEW_LINE> c = cholesky(corr, lower=True) <NEW_LINE> samples_corr = np.dot(c, samples.T) <NEW_LINE> return samples_corr.T | Description:
A function which performs the Cholesky decomposition of the correlation matrix and correlates standard
normal samples_SRM.
Input:
:param corr: Correlation matrix
:type corr: ndarray
:param samples: Standard normal samples_SRM.
:type samples: ndarray
Output:
:return: samples... | 625941d526238365f5f0f079 |
@register.filter <NEW_LINE> def partition_horizontal(value, n): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> n = int(n) <NEW_LINE> value = list(value) <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> return [value] <NEW_LINE> <DEDENT> newlists = [list() for i in range(n)] <NEW_LINE> for i, val in... | Break a list into ``n`` peices, but "horizontally." That is,
``partition_horizontal(range(10), 3)`` gives::
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10]]
Clear as mud? | 625941d55fc7496912cc3b87 |
def record_progress(self, bytes, seconds): <NEW_LINE> <INDENT> if not self.__used: <NEW_LINE> <INDENT> self.__used = True <NEW_LINE> <DEDENT> self.__bytes_xfr += bytes <NEW_LINE> self.__seconds_xfr += seconds | Record time and size of a network operation to a
particular TransportRepoURI, represented by the RepoStats
object.
Place the number of bytes transferred in the bytes argument.
The time, in seconds, should be supplied in the
seconds argument. | 625941d5fb3f5b602dac389e |
def spiralOrder(self, matrix): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> while matrix and matrix[0]: <NEW_LINE> <INDENT> ans = ans + matrix[0] <NEW_LINE> matrix = matrix[1:] <NEW_LINE> if matrix and matrix[0]: <NEW_LINE> <INDENT> ans = ans + [x[-1] for x in matrix] <NEW_LINE> matrix = [x[: -1] for x in matrix] <NEW_LINE>... | :type matrix: List[List[int]]
:rtype: List[int] | 625941d5293b9510aa2c349d |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TransferPost): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941d51d351010ab855d24 |
def getNotifications(self): <NEW_LINE> <INDENT> return self.notifications | Returns a list with the instances of all notifications. | 625941d560cbc95b062c674c |
def test_complex_links_correct_with_mergers(self): <NEW_LINE> <INDENT> d1 = Data(x=[1, 2, 3], y=[2, 3, 4]) <NEW_LINE> d2 = Data(u=[2, 3, 4], v=[3, 4, 5]) <NEW_LINE> x = d1.id['x'] <NEW_LINE> z = d1.id['x'] + d1.id['y'] + 5 <NEW_LINE> d1.add_component_link(z, 'z') <NEW_LINE> dc = DataCollection([d1, d2]) <NEW_LINE> dc.a... | Regression test. multi-level links should work after mergers | 625941d5498bea3a759b9cb8 |
def predict(self): <NEW_LINE> <INDENT> logger.info('Predicting using rule based core') <NEW_LINE> predicted = {} <NEW_LINE> for i, evidence in enumerate(self.evidences): <NEW_LINE> <INDENT> match = self.match(evidence) <NEW_LINE> predicted[evidence] = match if match is not None else False <NEW_LINE> if self.verbosity >... | Using the provided rules, on the given order, applies them to each evidence
candidate, verifying if they match or not.
Returns a dict {evidence: True/False}, where the boolean label indicates if
the relation is present on that evidence or not. | 625941d5d486a94d0b98e34f |
def CCX(self, qubitA, qubitB, qubitC, **kwargs): <NEW_LINE> <INDENT> return self.add_gate(gate=Gate.CCX, qubits=(qubitA, qubitB, qubitC), **kwargs) | Add a CCX gate to ``self`` at specified qubits and time, updating ``self``.
The qubits to add gate to are always explicitly specified. The time
to add gate to may be explicitly specified in the **time** argumet (1st
priority), or a recipe for determining the time placement can be
specified using the **time_placement** ... | 625941d56fece00bbac2d949 |
def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, all=False): <NEW_LINE> <INDENT> cred = make_digest_acl_credential(username, password) <NEW_LINE> return make_acl("digest", cred, read=read, write=write, create=create, delete=delete, admin=admin, all=all) | Create a digest ACL for Zookeeper with the given permissions | 625941d5e8904600ed9f2138 |
def source_dynamo_read(source, destination, masteraccount, targetaccount): <NEW_LINE> <INDENT> aws_session = boto3.Session(profile_name=masteraccount) <NEW_LINE> dynamodb = aws_session.resource('dynamodb') <NEW_LINE> table = dynamodb.Table(source) <NEW_LINE> response = table.scan() <NEW_LINE> for item in response[u'Ite... | Read from the source table | 625941d515fb5d323cde0d1b |
def generate_limited_data(self): <NEW_LINE> <INDENT> self.load_train_data() <NEW_LINE> indices = np.random.permutation(self.train_data.shape[0]) <NEW_LINE> n_limited_data = int(self.ratio * self.train_data.shape[0]) <NEW_LINE> limited_idx = indices[0: n_limited_data] <NEW_LINE> print('Sample idx: %s' %limited_idx) <NEW... | This function generates a limited set of training data, according to the ratio
:return: | 625941d5adb09d7d5db6c998 |
def run(context, arguments = [], cwd = None): <NEW_LINE> <INDENT> context.stage("matsim.runtime.maven") <NEW_LINE> if cwd is None: <NEW_LINE> <INDENT> cwd = context.path() <NEW_LINE> <DEDENT> temp_path = "%s/__java_temp" % context.path() <NEW_LINE> if not os.path.exists(temp_path): <NEW_LINE> <INDENT> os.mkdir(temp_pat... | This function calls Maven. | 625941d557b8e32f524836a5 |
def _find_conversion_hops(cls: str, hop: Tuple[str, str]) -> List[Tuple[str, str]]: <NEW_LINE> <INDENT> start_scale, target_scale = hop <NEW_LINE> queue = [(start_scale, [])] <NEW_LINE> visited = set() <NEW_LINE> if start_scale == target_scale: <NEW_LINE> <INDENT> return [hop] <NEW_LINE> <DEDENT> while queue: <NEW_LINE... | Calculate the hops needed to convert between scales using breadth first search | 625941d5462c4b4f79d1d8d9 |
def expand_log(log): <NEW_LINE> <INDENT> s = {} <NEW_LINE> for k, v in iteritems(log): <NEW_LINE> <INDENT> if isinstance(v, list): <NEW_LINE> <INDENT> s[k] = [value[2] for value in v] <NEW_LINE> <DEDENT> <DEDENT> return s | Expand the log dictionary produced by sacred (#sacred).
Parameters
----------
log : dict
a log dict we want to expand
Returns
-------
s : dict
a expanded dict for easy use | 625941d51f5feb6acb0c4d57 |
def update_db_state(state, data): <NEW_LINE> <INDENT> for ro_key in ['created', 'state', 'client_id', 'user_id', 'userinfo']: <NEW_LINE> <INDENT> data.pop(ro_key, None) <NEW_LINE> <DEDENT> if data: <NEW_LINE> <INDENT> state.update(data) <NEW_LINE> current_app.yubico_states[state['state']] = state | :param state: State from db
:type state: dict
:param data: Incoming state data
:type data: dict | 625941d58e7ae83300e4b1d6 |
def onClose(self): <NEW_LINE> <INDENT> self._server._rss.close() <NEW_LINE> self._server._controller.close() | @summary: Event inform that stack is close
@see: rdp.RDPClientObserver.onClose | 625941d52eb69b55b151caba |
def Bfullmarginal(datapath, ironmap, oxygen1map, oxygen2map): <NEW_LINE> <INDENT> dispersion=Dispersion(oxygen1map=oxygen1map, oxygen2map=oxygen2map) <NEW_LINE> lambdanaughts=LambdaNaught(ironmap=ironmap, oxygen1map=oxygen1map,dispersion=dispersion) <NEW_LINE> alphas=Alpha(lambdanaught=lambdanaughts) <NEW_LINE> margina... | NAME: Bfullmarginal
PURPOSE: Returns the pdf for B for each pixel in the disk of the sun
INPUTS: datapath - The final directory in which the FITS files are located
ironmap - The array of indices of the iron line core.
oxygen1map - The array of indices of the first oxygen line co... | 625941d5283ffb24f3c55b09 |
def CreateTranscode(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("CreateTranscode", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.CreateTranscodeResponse() <NE... | This API is used to create a document transcoding task.
:param request: Request instance for CreateTranscode.
:type request: :class:`tencentcloud.tiw.v20190919.models.CreateTranscodeRequest`
:rtype: :class:`tencentcloud.tiw.v20190919.models.CreateTranscodeResponse` | 625941d526068e7796caeeeb |
def swap_columns(self, column_1, column_2): <NEW_LINE> <INDENT> self.__is_dirty__ = True <NEW_LINE> with cython_context(): <NEW_LINE> <INDENT> if self._is_vertex_frame(): <NEW_LINE> <INDENT> graph_proxy = self.__graph__.__proxy__.swap_vertex_fields(column_1, column_2) <NEW_LINE> self.__graph__.__proxy__ = graph_proxy <... | Swaps the columns with the given names.
Parameters
----------
column_1 : string
Name of column to swap
column_2 : string
Name of other column to swap | 625941d5925a0f43d254a081 |
def add_entry(text, journal_data): <NEW_LINE> <INDENT> journal_data.append(text) | de list journal_data wordt hier uitgebreid met een nieuwe entry welke in text staat
:param text: de nieuwe entry die moet worden toegevoegd
:param journal_data: de list waar de text aan toegevoegd moet worden
:return: niets | 625941d5fff4ab517eb2f646 |
def __init__(self, entity_id=None, synonyms=None, entity_type=None): <NEW_LINE> <INDENT> self._entity_id = None <NEW_LINE> self._synonyms = None <NEW_LINE> self._entity_type = None <NEW_LINE> self.discriminator = None <NEW_LINE> if entity_id is not None: <NEW_LINE> <INDENT> self.entity_id = entity_id <NEW_LINE> <DEDENT... | GnbrEntity - a model defined in Swagger | 625941d538b623060ff0aff7 |
def get(self, request:HttpRequest) -> JsonResponse: <NEW_LINE> <INDENT> if not access_check(request.user): <NEW_LINE> <INDENT> return JsonResponse([], safe=False) <NEW_LINE> <DEDENT> member_id = request.query_params.get('member_id') <NEW_LINE> if member_id is not None: <NEW_LINE> <INDENT> member_id = int(member_id) <NE... | List all available user groups.
---
parameters:
- name: member_id
description: Return only groups this user is member of.
type: integer
paramType: form
required: false | 625941d53cc13d1c6d3c7583 |
def get_text(self, start_row, start_col, stop_row, stop_col): <NEW_LINE> <INDENT> r, c = start_row, start_col <NEW_LINE> full = '' <NEW_LINE> clip = '' <NEW_LINE> if self.vpage.row[r-1].double[c-1] == 2: <NEW_LINE> <INDENT> c -= 1 <NEW_LINE> <DEDENT> if self.vpage.row[stop_row-1].double[stop_col-1] == 1: <NEW_LINE> <IN... | Retrieve a clip of the text between start and stop. | 625941d56fece00bbac2d94a |
def MigrationInfo(self, instance): <NEW_LINE> <INDENT> return self._ReadConfigFile(instance.name) | Get instance information to perform a migration.
@type instance: L{objects.Instance}
@param instance: instance to be migrated
@rtype: string
@return: content of the xen config file | 625941d57cff6e4e81117b8f |
def do_faster(): <NEW_LINE> <INDENT> global current_speed <NEW_LINE> if current_speed + 1 < len(speeds): <NEW_LINE> <INDENT> current_speed += 1 <NEW_LINE> slower_button.config(state=NORMAL) <NEW_LINE> <DEDENT> if current_speed + 1 >= len(speeds): <NEW_LINE> <INDENT> faster_button.config(state=DISABLED) | Button action: increase scan speed. | 625941d566656f66f7cbc3b5 |
def get_coverage_by_build_ids(build_ids): <NEW_LINE> <INDENT> if not build_ids: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> all_job_ids = db.session.query(Job.id).filter( Job.build_id.in_(build_ids) ) <NEW_LINE> return get_coverage_by_job_ids(all_job_ids) | Returns the coverage associated with some builds.
The dictionary maps file names to a string of the form 'UNCCCNCU', where U means
'uncovered', C means 'covered' and 'N' means 'no coverage info'. | 625941d5a17c0f6771cbe259 |
def __set__(self, obj, value): <NEW_LINE> <INDENT> if "PYTHON_APT_DEPRECATION_WARNINGS" in os.environ: <NEW_LINE> <INDENT> warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2) <NEW_LINE> <DEDENT> setattr(obj, self.attribute, value) | Issue a DeprecationWarning and set the requested value. | 625941d510dbd63aa1bd2dac |
def get_world_to_screen_mtx(self): <NEW_LINE> <INDENT> tran_mtx = Matrix.translate2d(-self.camera_pos) <NEW_LINE> rot_mtx = Matrix.rotate2d((0,0), -self.camera_rot) <NEW_LINE> zoom_mtx = Matrix.scale2d((0,0), (1./self.camera_size, 1./self.camera_size)) <NEW_LINE> offset_mtx = Matrix.translate2d(self.canvas_center) <NEW... | Apply the opposite transformations from those of the camera
1. Un-translate
2. Un-rotate
3. Un-zoom
4. un-offset | 625941d5a05bb46b383eca2b |
def datetime32(): <NEW_LINE> <INDENT> now = datetime.today() <NEW_LINE> exec_time1 = int(now.strftime('%y%m%d')) <NEW_LINE> exec_time2 = int(now.strftime('%H%M%S')) <NEW_LINE> logger.debug('time1: {}'.format(exec_time1)) <NEW_LINE> logger.debug('time2: {}'.format(exec_time2)) <NEW_LINE> return np.base_repr(exec_time1 *... | 時刻情報を元に衝突しにくい名前を自動で生成する(base_repr使用版)
[out] 生成された名前 | 625941d5046cf37aa974cf50 |
def set_message_type(self, Type): <NEW_LINE> <INDENT> self.message_type = Type <NEW_LINE> stream = self.get_stream() <NEW_LINE> if stream: <NEW_LINE> <INDENT> stream.set_message_type(Type) | Set input message type. | 625941d5d7e4931a7ee9e127 |
def get_nutrients_prediction(code): <NEW_LINE> <INDENT> product_info = requests.get("https://world.openfoodfacts.org/api/v0/product/"+str(code)+".json").json() <NEW_LINE> imgid = product_info["product"]["images"]["nutrition_fr"]["imgid"] <NEW_LINE> ocr_url = "https://static.openfoodfacts.org/images/products/" + split_b... | Return the nutrients prediction of a product using Robotoff API
@ input : code {string} "3228857000852"
@ output : {dictionnary} nutrients prediction | 625941d5091ae35668667165 |
def fileExport(self, event=None, htmlPath=None): <NEW_LINE> <INDENT> settingsHTMLpath = self.exp.settings.params['HTML path'].val <NEW_LINE> if htmlPath is None and self.exp.settings.params['HTML path']: <NEW_LINE> <INDENT> expPath = os.path.split(self.filename)[0] <NEW_LINE> htmlPath = os.path.join(expPath, settingsHT... | Exports the script as an HTML file (PsychoJS library)
| 625941d5d4950a0f3b08c557 |
def get_disc_iterator(self, splt): <NEW_LINE> <INDENT> return self.data['disc'][splt]['x'].get_iterator( shuffle=(splt == 'train'), return_indices=True, group_by_size=False ) | Build data iterator. | 625941d5287bf620b61d3c6c |
def as_string(self, params): <NEW_LINE> <INDENT> fn_name = f"{getattr(self._fn, '__name__', 'fn')}{id(self._fn)}" <NEW_LINE> params.setdefault(fn_name, self._fn) <NEW_LINE> str_call = ", ".join( itertools.chain( (stringify(x, params) for x in self._args), ( f"{k}: {stringify(v, params)}" for k, v in self._kwargs.items(... | Create a string which evaluates to the lazy array creation.
| 625941d57d847024c06be4c8 |
def __init__(self, x=None, prev=None, **kwargs): <NEW_LINE> <INDENT> pass | Construct preprocessor. Can use some data x, or chained with
another preprocessor. | 625941d530c21e258bdfa6a8 |
def read_csv(f): <NEW_LINE> <INDENT> return read_tsv(f, delimiter=",") | Take a csv filepath and return an array; e.g. [[],[],[]].
For example, a file containing:
1,2,3
4,5,6
7,8,9
would return the array: [['1','2','3'], ['4','5','6'], ['7','8','9']]
:param csv_filepath:
:return: csv_array | 625941d5a934411ee375189d |
def _get_weighted_candidates_cg(self, context, request_spec): <NEW_LINE> <INDENT> elevated = context.elevated() <NEW_LINE> shr_types = request_spec.get("share_types", None) <NEW_LINE> weighed_hosts = [] <NEW_LINE> for iteration_count, share_type in enumerate(shr_types): <NEW_LINE> <INDENT> temp_weighed_hosts = self._ge... | Finds hosts that support the consistency group.
Returns a list of hosts that meet the required specs,
ordered by their fitness. | 625941d5f8510a7c17cf9906 |
def _changed_path(self): <NEW_LINE> <INDENT> if self.control is not None: <NEW_LINE> <INDENT> self.load() | Called when the path to the file is changed. | 625941d5d486a94d0b98e350 |
def connect(self): <NEW_LINE> <INDENT> pass | Prepare Pingee to receive pings. | 625941d5b830903b967e9b13 |
def timestamp_components(seconds, enable_suppression=False): <NEW_LINE> <INDENT> days = seconds // 86400 <NEW_LINE> hours = seconds % 86400 // 3600 <NEW_LINE> minutes = seconds % 3600 // 60 <NEW_LINE> seconds = seconds % 60 <NEW_LINE> if enable_suppression: <NEW_LINE> <INDENT> return (days, hours, minutes, seconds)[com... | Takes a timestamp in seconds and returns a tuple of days, hours, minutes and seconds | 625941d5dd821e528d63b3b2 |
def convert_long_urls(text, hostname): <NEW_LINE> <INDENT> hostname_path_pattern = re.compile(r"(https?://)?" + r"(" + re.escape(hostname) + r")/" + r"(?=" + RESTRICTED_NONROOT_PATH + r"(?:\s|$))") <NEW_LINE> username_pattern = re.compile(r"(https?://)?" + r"(" + re.escape(hostname) + r")/user/" + r"(?=" + USERNAME + r... | This function removes the unnecessary part from urls which are copy&pasted
from the url field of the browser. | 625941d5656771135c3eba7a |
def adduser(username, password): <NEW_LINE> <INDENT> p = subprocess.Popen([ADDUSER, '-u', UID, '-s', SHELL, '-h', HOME, username], stdin=subprocess.PIPE) <NEW_LINE> p.communicate('{pw}\n{pw}\n'.format(pw=password)) <NEW_LINE> if not p.returncode == 0: <NEW_LINE> <INDENT> raise RuntimeError("Could not create account '{}... | Add a new system user and set its password | 625941d5379a373c97cfad50 |
def run(self): <NEW_LINE> <INDENT> openShutter = True <NEW_LINE> actuateXed = False <NEW_LINE> image_type = "FLAT" <NEW_LINE> meas_flux = self.measured_flux(self.wl) <NEW_LINE> self.logger.info("flat_pair_acq: measured flux =", meas_flux) <NEW_LINE> for seqno, tokens in enumerate(self.instructions): <NEW_LINE> <INDENT>... | Take the flat pair sequence, reading the target signal levels
from the configuration file. | 625941d5a79ad161976cc34f |
def on_key_press_event(self, event): <NEW_LINE> <INDENT> if event.keyval == gtk.keysyms.Escape: <NEW_LINE> <INDENT> self.popdown() <NEW_LINE> return True <NEW_LINE> <DEDENT> elif event.keyval in (gtk.keysyms.KP_Enter, gtk.keysyms.Return): <NEW_LINE> <INDENT> self.__insert_selected() <NEW_LINE> self.popdown() <NEW_LINE>... | Do key press handling while the popup is active.
Returns True if the key press is handled, False otherwise. | 625941d51f037a2d8b946407 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.