code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def start(self): <NEW_LINE> <INDENT> self.__idcf_cloud_api.start_virtual_machine() <NEW_LINE> pass | this starts the server | 625941dc3317a56b86939f46 |
def write(self, basename="/tmp/resource_dump.xml"): <NEW_LINE> <INDENT> super(ResourceDump, self).write(basename) | Write out a ResourceDump document.
FIXME - should there be support for a tie to writing out
the Dump files themselves, complete with Resource Dump
Manifests? | 625941dc167d2b6e31218e89 |
def edges(self: Any) -> List[Set[str]]: <NEW_LINE> <INDENT> return self.__generate_edges__() | returns the edges of a graph | 625941dcf9cc0f698b1408ed |
def ask(prompt, retries=3, complaint='try again'): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> ri=raw_input(prompt) <NEW_LINE> if ri in ('a','b','c'): <NEW_LINE> <INDENT> print('abc') <NEW_LINE> return <NEW_LINE> <DEDENT> retries -= 1 <NEW_LINE> if retries == 0: <NEW_LINE> <INDENT> raise IOError('bad letters') ... | varargs function, if no ifs is reached then .__doc__ is printed | 625941dca8ecb033257d33c0 |
def _max(input, reduction_indices, keep_dims=None, name=None): <NEW_LINE> <INDENT> return _op_def_lib.apply_op("Max", input=input, reduction_indices=reduction_indices, keep_dims=keep_dims, name=name) | Computes the maximum of elements across dimensions of a tensor.
Reduces `input` along the dimensions given in `reduction_indices`. Unless
`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in
`reduction_indices`. If `keep_dims` is true, the reduced dimensions are
retained with length 1.
Args:
... | 625941dc7cff6e4e81117c79 |
def get_tokens(text: str, lowercase=False, stopword=False, preserve_line=True) -> Generator[str, Any, Any]: <NEW_LINE> <INDENT> if stopword: <NEW_LINE> <INDENT> for token in nltk.word_tokenize(text, preserve_line=preserve_line): <NEW_LINE> <INDENT> if token.lower() in STOPWORDS: <NEW_LINE> <INDENT> continue <NEW_LINE> ... | Get token generator from text.
:param text:
:param lowercase:
:param stopword:
:param preserve_line: keep the preserve the sentence and not sentence tokenize it.
:return: | 625941dcaad79263cf390d39 |
def get_detector_component(move_info, component): <NEW_LINE> <INDENT> component_selection = component <NEW_LINE> if component: <NEW_LINE> <INDENT> for detector_key in list(move_info.detectors.keys()): <NEW_LINE> <INDENT> is_name = component == move_info.detectors[detector_key].detector_name <NEW_LINE> is_name_short = c... | Gets the detector component on the workspace
:param move_info: a StateMove object.
:param component: A component name, ie a detector name or a short detector name as specified in the IPF.
:return: the key entry for detectors on the StateMove object which corresponds to the input component. | 625941dc8da39b475bd6526b |
def reset(self) -> None: <NEW_LINE> <INDENT> self.start = datetime.now() <NEW_LINE> self.votes: Dict[int, Vote] = {} <NEW_LINE> if self.loop: <NEW_LINE> <INDENT> self.bot.loop.create_task(self.stop_loop()) | Resets voting session. | 625941dc50812a4eaa59c613 |
def modify(self, data: dict, **kwargs) -> dict: <NEW_LINE> <INDENT> data.update(dict(consumer_key=self.__consumer_key, access_token=self.__access_token)) <NEW_LINE> resp = self.__session.post('https://getpocket.com/v3/send', json=data, **kwargs) <NEW_LINE> if resp.status_code != 200: <NEW_LINE> <INDENT> raise PocketErr... | Modifying a User's Pocket Data.
:param data: json to send in the body of the :class:`request.Session`.
:param \*\*kwargs: Optional arguments that ``request`` takes. | 625941dc07f4c71912b11779 |
def get_features(txt): <NEW_LINE> <INDENT> featureset = {} <NEW_LINE> for feature in words_a + words_b + others: <NEW_LINE> <INDENT> featureset['has('+feature+')'] = False <NEW_LINE> <DEDENT> for r, _ in find_all(txt): <NEW_LINE> <INDENT> featureset['has('+r+')'] = True <NEW_LINE> <DEDENT> return featureset | return a nltk featureset for `txt` | 625941dcbe383301e01b5775 |
def _resubscribe(self, soft=False): <NEW_LINE> <INDENT> if soft: <NEW_LINE> <INDENT> for s in self.subscribtions: <NEW_LINE> <INDENT> s['command'] = 'unsubscribe' <NEW_LINE> self.send(**s) <NEW_LINE> <DEDENT> <DEDENT> for s in self.subscribtions: <NEW_LINE> <INDENT> self.send(**s) | Resubscribes to all channels found in self.channel_configs.
:param soft: if True, unsubscribes first.
:return: None | 625941dc442bda511e8be709 |
def write_diff_file(self, object_metadata): <NEW_LINE> <INDENT> path, filename = os.path.split(os.path.join( self.paths['shelves'], object_metadata.keys()[0] )) <NEW_LINE> diff_file = '%s/%s.pitem' % (path, filename) <NEW_LINE> utils.write_json_file(diff_file, object_metadata) | write_diff_file(self, object_metadata)
Write json file contain metadata about a object. | 625941dc01c39578d7e75130 |
def _fetch_candles(params): <NEW_LINE> <INDENT> url = '?'.join((URL, parse.urlencode(sorted(params.items())))) <NEW_LINE> logging.info("Fetching '%s'", url) <NEW_LINE> response = net_utils.retrying_urlopen(url) <NEW_LINE> if response is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> data_string = response.re... | Fetch the given URL from OANDA and return a list of (utc-time, price).
Args:
params: A dict of URL params values.
Returns:
A sorted list of (time, price) points. | 625941dc596a897236089db2 |
def print_models(unprinted_designs, completed_models): <NEW_LINE> <INDENT> while unprinted_designs: <NEW_LINE> <INDENT> current_design = unprinted_designs.pop() <NEW_LINE> print("Printing model: " + current_design) <NEW_LINE> completed_models.append(current_design) | Simulates printing | 625941dc9c8ee82313fbba6a |
def maybe_operate_rowwise(func: F) -> F: <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def newfunc(values: np.ndarray, *, axis: int | None = None, **kwargs): <NEW_LINE> <INDENT> if ( axis == 1 and values.ndim == 2 and values.flags["C_CONTIGUOUS"] and (values.shape[1] / 1000) > values.shape[0] and values.dtype !... | NumPy operations on C-contiguous ndarrays with axis=1 can be
very slow if axis 1 >> axis 0.
Operate row-by-row and concatenate the results. | 625941dc3346ee7daa2b3062 |
@sio.on('votes', namespace='/polls') <NEW_LINE> def votes(votes): <NEW_LINE> <INDENT> for question, answer in session['votes'].items(): <NEW_LINE> <INDENT> tally.remove_vote(question, answer) <NEW_LINE> <DEDENT> for question, answer in votes.items(): <NEW_LINE> <INDENT> tally.add_vote(question, answer) <NEW_LINE> <DEDE... | Нові голоса | 625941dce64d504609d74b34 |
def make_defaults(self): <NEW_LINE> <INDENT> if not self.fields: <NEW_LINE> <INDENT> return empty_defaults <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fields = [] <NEW_LINE> end_fields = [] <NEW_LINE> for field in self.fields: <NEW_LINE> <INDENT> if isinstance(field, (tuple, list)): <NEW_LINE> <INDENT> name, dflt = f... | Make a namedtuple for extracting our wanted keys | 625941dcff9c53063f47c4e7 |
def clean_more_crud(file_to_clean, rm_tags, show_results = False): <NEW_LINE> <INDENT> html = lxml.html.fromstring(file_to_clean) <NEW_LINE> if show_results: <NEW_LINE> <INDENT> result = lxml.html.tostring(html) <NEW_LINE> print_result("BEFORE", result) <NEW_LINE> <DEDENT> for a in rm_tags: <NEW_LINE> <INDENT> for tag ... | returns result
This function cleans up extra attributes in file
if 3rd arg is true, it will print the input string
before and after cleaning
:param file_to_clean: name of file to clean
:param rm_tags: tags to be removed
:param show_results: show the results
:type to_clean: str
:type rm_tags: list
:type show_results... | 625941dc3c8af77a43ae3a97 |
def addWriter(self, writer): <NEW_LINE> <INDENT> fd = writer.fileno() <NEW_LINE> if fd not in self._writes: <NEW_LINE> <INDENT> self._selectables[fd] = writer <NEW_LINE> self._writes[fd] = 1 <NEW_LINE> self._updateRegistration(fd) | Add a FileDescriptor for notification of data available to write. | 625941dcf8510a7c17cf99f3 |
def push(self, *elements): <NEW_LINE> <INDENT> self.commands.extend(elements) | Push commands and coordinates onto the command stack.
:param `iterable` elements: *coordinates*, *length* and *commands* | 625941dc71ff763f4b549985 |
def load_collection(self): <NEW_LINE> <INDENT> start = self.args.root.value <NEW_LINE> loader = self.loader_class(start=start) <NEW_LINE> coll_name = self.args.collection.value <NEW_LINE> try: <NEW_LINE> <INDENT> coll = loader.load(coll_name) if coll_name else loader.load() <NEW_LINE> self.collection = coll <NEW_LINE> ... | Load a task collection based on parsed core args, or die trying. | 625941dcd58c6744b4257f53 |
def updateTree(items, inTree, headerTable, count): <NEW_LINE> <INDENT> curItem = items[0] <NEW_LINE> if curItem in inTree.children: <NEW_LINE> <INDENT> inTree.children[curItem].inc(count) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inTree.children[curItem] = treeNode(curItem, count, inTree) <NEW_LINE> if headerTable[... | 将一条新的事务更新进FP树中
:param items: 事务
:param inTree: FP树
:param headerTable: 头指针表
:param count: 事务出现的频率
:return: 无 | 625941dcbe383301e01b5776 |
def init_hub(self): <NEW_LINE> <INDENT> hub_args = dict( base_url=self.hub_prefix, routespec=self.hub_routespec, public_host=self.subdomain_host, certfile=self.internal_ssl_cert, keyfile=self.internal_ssl_key, cafile=self.internal_ssl_ca, ) <NEW_LINE> if self.hub_bind_url: <NEW_LINE> <INDENT> self.hub_bind_url = urlunp... | Load the Hub URL config | 625941dcd18da76e235327ce |
def test_is_cnf_clauses_of_single_operands(self): <NEW_LINE> <INDENT> self.assert_is_cnf(['op1', 'op2', 'and']) <NEW_LINE> self.assert_is_cnf(['A', 'B', 'C', 'D', 'and', 'and', 'and']) <NEW_LINE> self.assert_is_cnf(['A', 'B', 'not', 'C', 'and', 'and']) | Test several ANDed clauses of single operands is in CNF. | 625941dc283ffb24f3c55bf3 |
def __init__(self): <NEW_LINE> <INDENT> self.data = OrderedDict() | Creates ordered dict.
| 625941dc8e7ae83300e4b2c2 |
def text_to_paragraph(filePath): <NEW_LINE> <INDENT> f = codecs.open(filePath, "r", "utf-8") <NEW_LINE> paragraphs = f.read() <NEW_LINE> f.close() <NEW_LINE> return paragraphs.split("\n\n") | Returns a list containing the paragraphs
:param filePath: URL_PATH
:return: List[String] | 625941dc99fddb7c1c9de685 |
def test_data_path_should_return_a_string(self): <NEW_LINE> <INDENT> data_path = SpiderFootHelpers.dataPath() <NEW_LINE> self.assertIsInstance(data_path, str) | Test dataPath() | 625941dc6fb2d068a760f396 |
def render_plaintext_template(self, kwargs): <NEW_LINE> <INDENT> return self.render_template(self.plaintext_template, kwargs) | Render just the plaintext template and return it as a string. | 625941dccb5e8a47e48b7d9b |
def get_data(self, fields=None, status_type=None): <NEW_LINE> <INDENT> if status_type is None: <NEW_LINE> <INDENT> status_type = [x.name for x in self.status.data] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status_type = self._check_param_type(status_type) <NEW_LINE> <DEDENT> if fields is None: <NEW_LINE> <INDENT> r... | get a list of (type name,field,data) tuples available from the gpg run
@param fields: string or list of field name strings to search for
@param staus_type: string or list of class name strings to search for
@rtype list: of (type name,field,data) tuples | 625941dca79ad161976cc43b |
def basic_auth(username, password): <NEW_LINE> <INDENT> def enable_auth(*args, **kwargs): <NEW_LINE> <INDENT> kwargs['auth'] = (username, password) <NEW_LINE> return args, kwargs <NEW_LINE> <DEDENT> gh = Github() <NEW_LINE> gh.is_authenticated = True <NEW_LINE> gh._requests_pre_hook = enable_auth <NEW_LINE> return gh | Returns an authenticated Github object, via HTTP Basic. | 625941dc796e427e537b08bd |
def adjust_weight(self, lagrange, offset=13, spread=7): <NEW_LINE> <INDENT> exp_lag_log = np.exp((np.log(lagrange) + offset) / spread) <NEW_LINE> self._weight = self._weight_min + self._weight_delta / (exp_lag_log + 1) | Adjust the weight according to the Lagrange multiplier.
Once close to convergence the Lagrange multiplier will be close to 0, otherwise it will go
towards infinity.
We here adjust using the Fermi-function to hit the minimum/maximum weight with a
suitable spread | 625941dcab23a570cc25047a |
def dump_json(logger): <NEW_LINE> <INDENT> initial_domain_names = [] <NEW_LINE> for domain in initial_domains: <NEW_LINE> <INDENT> initial_domain_names.append(domain.name) <NEW_LINE> <DEDENT> logger.info('Initial Domains: %s' % json.dumps({'domains' : initial_domain_names})) | Dump active domains | 625941dc4f88993c3716c35a |
def get_organisations(self, **query_params): <NEW_LINE> <INDENT> return self.get_member().get_organisations(**query_params) | Get all organisations this member is part of. Return a list of
Organisation objects.
Returns:
list(Organisation): Return all organisations this member is
part of | 625941dcb5575c28eb68e2f8 |
def test_set_valid_field_values(self): <NEW_LINE> <INDENT> settings = Settings(2013, 'newhouse', True) <NEW_LINE> with open(settings.file_path, 'rb') as csvfile: <NEW_LINE> <INDENT> reader = csv.DictReader(csvfile, delimiter=',', skipinitialspace=True) <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> for rowname in ro... | Are we save the data correctly?
Assume we have only one entry in the file for testing | 625941dca8370b7717052b93 |
def resolve_one_round(self): <NEW_LINE> <INDENT> new_deps = self.find_new_dependencies() <NEW_LINE> self.spec_set.add_specs(new_deps) <NEW_LINE> return len(new_deps) > 0 | Resolves one level of the current spec set, by finding best matches
for the current spec set in the package manager and returning all
(new) requirements for those packages.
Returns whether the spec set was changed significantly by this round. | 625941dc7c178a314d6ef759 |
def revert(self, loadbalancer, *args, **kwargs): <NEW_LINE> <INDENT> LOG.warning("Reverting update loadbalancer in DB " "for loadbalancer id %s", loadbalancer.id) <NEW_LINE> self.task_utils.mark_loadbalancer_prov_status_error(loadbalancer.id) | Mark the loadbalancer ERROR since the update couldn't happen
:param loadbalancer: The load balancer that couldn't be updated
:returns: None | 625941dc8a349b6b435e8468 |
def get_jobs_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = [] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals() <NEW_LINE> for ... | get_jobs # noqa: E501
Get all jobs you have created # 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_jobs_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: list[JobsData]
... | 625941dc3539df3088e2e640 |
def get_item(self, name): <NEW_LINE> <INDENT> if not self.has_item(name): <NEW_LINE> <INDENT> raise TypeError(f'no item {name}') <NEW_LINE> <DEDENT> return Item(self._directory / name, self._readonly) | Get an item by name. | 625941dc30c21e258bdfa794 |
def find_or_create_project(self, name, description=""): <NEW_LINE> <INDENT> projects = [project for project in self.get_projects()["projects"] if project["name"] == name] <NEW_LINE> if len(projects) > 1: <NEW_LINE> <INDENT> cherrypy.log.error("slycat.web.client.__init__.py find_or_create_project", "More than one projec... | Return a project identified by name, or newly created.
Parameters
----------
name: string, required
The name of the project to return (or create).
description: string, optional
Description to use for the new project (if a new project is created).
Returns
-------
pid: string
Unique identifier of the matching (or... | 625941dc63b5f9789fde73db |
def testSessionEndEvent(self): <NEW_LINE> <INDENT> model = mparticle.models.session_end_event.SessionEndEvent() | Test SessionEndEvent | 625941dc851cf427c661a802 |
def sample(self, features, max_length=30): <NEW_LINE> <INDENT> N = features.shape[0] <NEW_LINE> captions = self._null * np.ones((N, max_length), dtype=np.int32) <NEW_LINE> W_proj, b_proj = self.params['W_proj'], self.params['b_proj'] <NEW_LINE> W_embed = self.params['W_embed'] <NEW_LINE> Wx, Wh, b = self.params['Wx'], ... | Run a test-time forward pass for the model, sampling captions for input
feature vectors.
At each timestep, we embed the current word, pass it and the previous hidden
state to the RNN to get the next hidden state, use the hidden state to get
scores for all vocab words, and choose the word with the highest score as
the ... | 625941dcd53ae8145f87a561 |
@click.group(name="set") <NEW_LINE> def set_(): <NEW_LINE> <INDENT> ctx = click.get_current_context() <NEW_LINE> if ctx.obj.quiet: <NEW_LINE> <INDENT> ctx.exit() | Set parameters | 625941dc91af0d3eaac9bd11 |
def get_rabbitmq_port(self): <NEW_LINE> <INDENT> f_config = open(self.config_path, "r") <NEW_LINE> rabbitmq_port = re.search(get_rabbitmq_port_re(), f_config.read()).group()[-4:] <NEW_LINE> f_config.close() <NEW_LINE> return rabbitmq_port | Returns the address on which the rabbitmq
server connects. It is localhost by default. | 625941dc4f6381625f114d31 |
def get_template_names(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> names = super(SingleDocumentTemplateResponseMixin, self).get_template_names() <NEW_LINE> <DEDENT> except ImproperlyConfigured: <NEW_LINE> <INDENT> names = [] <NEW_LINE> <DEDENT> if self.object and self.template_name_field: <NEW_LINE> <INDENT> na... | Return a list of template names to be used for the request. Must return
a list. May not be called if get_template is overridden. | 625941dc236d856c2ad44ad3 |
def all(self): <NEW_LINE> <INDENT> wordlist = [] <NEW_LINE> def search(node, word=''): <NEW_LINE> <INDENT> if '_F' in node: <NEW_LINE> <INDENT> wordlist.append(word) <NEW_LINE> <DEDENT> for char in sorted(node.keys()): <NEW_LINE> <INDENT> if char is not '_F': <NEW_LINE> <INDENT> search(node[char], word + char) <NEW_LIN... | Sorted list of all words in this trie. | 625941dc50485f2cf553d091 |
def __init__(self, jsondict=None): <NEW_LINE> <INDENT> self.cause = None <NEW_LINE> self.item = None <NEW_LINE> super(ClinicalImpressionFinding, self).__init__(jsondict) | Initialize all valid properties.
| 625941dc66673b3332b92387 |
def update_user(user_id, update_user): <NEW_LINE> <INDENT> authorization = connexion.request.headers['Authorization'] <NEW_LINE> if connexion.request.is_json: <NEW_LINE> <INDENT> update_user = UpdateUser.from_dict(connexion.request.get_json()) <NEW_LINE> <DEDENT> return controllers.users.update.update_user( auth_token=... | Update details of particular user
:param user_id: The id of the user to update
:type user_id: str
:param update_user:
:type update_user: dict | bytes
:rtype: Empty | 625941dc9f2886367277ab81 |
def boundsStr(bounds): <NEW_LINE> <INDENT> fmt_str = "_".join(['{:,4f}',]*4) <NEW_LINE> return fmt_str.format(*bounds).replace('.','p') | Returns a lat-lon id for use in filenames | 625941dcff9c53063f47c4e8 |
def get_resource(self, path): <NEW_LINE> <INDENT> response = self._http_request(path) <NEW_LINE> try: <NEW_LINE> <INDENT> return response.json() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise exception.ServiceException("Invalid service response.") | Getting the required information from the API. | 625941dc711fe17d8254265b |
def test_ground_diso(diso_annotation): <NEW_LINE> <INDENT> actual = grounding_utils.ground(copy.deepcopy(diso_annotation)) <NEW_LINE> cancer_xrefs = [{'namespace': constants.NAMESPACES['DISO'], 'id': 'DOID:162'}] <NEW_LINE> cystic_fibrosis_xrefs = [{'namespace': constants.NAMESPACES['DISO'], 'id': 'DOID:1485'}] <NEW_LI... | Asserts that `grounding_utils.ground()` returns the expected value for a simple example with
disease entities. | 625941dcb57a9660fec33b7e |
def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Messaging.V1.ExternalCampaignInstance>' | Provide a friendly representation
:returns: Machine friendly representation
:rtype: str | 625941dc8a349b6b435e8469 |
def __init__(self, which_set, base_path = '${PYLEARN2_DATA_PATH}/icml_2013_emotions', start = None, stop = None, preprocessor = None, fit_preprocessor = False, axes = ('b', 0, 1, 'c'), fit_test_preprocessor = False): <NEW_LINE> <INDENT> self.test_args = locals() <NEW_LINE> self.test_args['which_set'] = 'public_test' <N... | which_set: A string specifying which portion of the dataset
to load. Valid values are 'train' or 'public_test'
base_path: The directory containing the .csv files from kaggle.com.
This directory should be writable; if the .csv files haven't
already been converted to npy, this class will convert them
... | 625941dc4f88993c3716c35b |
def execute(self, request): <NEW_LINE> <INDENT> if IS_PYTHON3: <NEW_LINE> <INDENT> fut, work_id = Future(), next(self.counter) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fut, work_id = Future(), self.counter.next() <NEW_LINE> <DEDENT> self.input_queue.put(WorkRequest(request, work_id)) <NEW_LINE> self.futures[work_i... | Given a request, enqueue it to be processed
and then return a future linked to the response
of the call.
:param request: The request to execute
:returns: A future linked to the call's response | 625941dc507cdc57c6306fd7 |
def check_permissions(self, member, callback_function): <NEW_LINE> <INDENT> if hasattr(callback_function, 'spamalot'): <NEW_LINE> <INDENT> return self.SPAMABLE <NEW_LINE> <DEDENT> owner = self.require_owner(member) <NEW_LINE> admin = self.require_admin(member) <NEW_LINE> moderator = self.require_moderator(member) <NEW_... | Checks if the member has permission to get a response from the sepcified callback.
:param member: A discord member instance
:param callback_function: A handle to a module's callback method
:return: True if the member has permission, False if otherwise | 625941dc30dc7b7665901c59 |
def set_taps(self, *args, **kwargs): <NEW_LINE> <INDENT> return _filter_swig.fir_filter_fsf_set_taps(self, *args, **kwargs) | set_taps(fir_filter_fsf self, pmt_vector_float taps) | 625941dc566aa707497f485b |
def TotalDias(data1, data2): <NEW_LINE> <INDENT> dia1 = int(data1[0:2]) <NEW_LINE> mes1 = int(data1[3:5]) <NEW_LINE> ano1 = int(data1[6:10]) <NEW_LINE> dia2 = int(data2[0:2]) <NEW_LINE> mes2 = int(data2[3:5]) <NEW_LINE> ano2 = int(data2[6:10]) <NEW_LINE> diasSemMes = (30-dia1) + dia2 <NEW_LINE> diasComMes = (12-mes1)*3... | Funcao que retorna a quantidade de dias passados entre duas datas | 625941dc0fa83653e46572af |
def compare_genomes_lastal(ref_fasta, target_fasta, filter_alns=True, lastal_options=None, cleanup=True): <NEW_LINE> <INDENT> if lastal_options is None: <NEW_LINE> <INDENT> lastal_options = {} <NEW_LINE> <DEDENT> ref_fasta = os.path.abspath(ref_fasta) <NEW_LINE> ref_dir, ref_name = os.path.split(ref_fasta) <NEW_LINE> d... | Compare a refrence set of sequences to a target set os sequences using lastal alignment.
:param ref_fasta: Reference sequence set in fasta format.
:param target_fasta: Target sequence set in fasta format.
:param filter_alns: Filter alignments if True.
:param lastal_options: Options passed to lastal in a dictionary.
:p... | 625941dcd486a94d0b98e43d |
def UnifyLevels(baseLevel, addonLevel, windowSize, ): <NEW_LINE> <INDENT> if not len(addonLevel): <NEW_LINE> <INDENT> return baseLevel <NEW_LINE> <DEDENT> joinedLevel = [] <NEW_LINE> addon_idx = 0 <NEW_LINE> for base_elem in baseLevel: <NEW_LINE> <INDENT> while addon_idx < len(addonLevel): <NEW_LINE> <INDENT> addon_ele... | Unify several decomposition levels.
Merge the two lists of breakpoints, but drop addonLevel values that are too
close to baseLevel values.
Parameters:
baseLevel: const array of ints
addonLevel: const array of ints
windowSize: int
Output:
joinedLevel: array of ints
Source: HaarSeg.c | 625941dc956e5f7376d71162 |
def convert_time_to_utc(d): <NEW_LINE> <INDENT> d = datetime.datetime(1900, 1, 1, d.hour, d.minute, d.second, d.microsecond, d.tzinfo) <NEW_LINE> d -= d.utcoffset() <NEW_LINE> return d.time() | Convert datetime.time object to UTC | 625941dc8e71fb1e9831da9e |
def stiffness_matrix(vs, nq, quadfun=np.polynomial.legendre.leggauss, matrix_format="FULL", internal="DOK"): <NEW_LINE> <INDENT> (qst, wst) = quadfun(nq) <NEW_LINE> cum = {"DOK": lambda: dok_matrix((vs.n_dofs, vs.n_dofs)), "LIL": lambda: lil_matrix((vs.n_dofs, vs.n_dofs))}[ internal]() <NEW_LINE> for lcell in range(vs.... | A StiffnessMatrix assembler, computing the sparse matrix
$M_{ij} =\int_0^1 v'_i(x) v'_j(x) dx$
vs: A vector_space type object.
nq: Number of quadrature points used for each individual integration.
quadfun: a function that receives a number and returns a tuple of
numpy arrays with the values of quadrature p... | 625941dc99cbb53fe6792edc |
def processfile(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> remove(filename) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> stderr.write('Failed to delete backup file "' + filename + '": ' + str(e) + '\n') <NEW_LINE> return False | Deletes the specified file. | 625941dc4e4d5625662d46ca |
def test_data_non_displayroles(self): <NEW_LINE> <INDENT> model = ConcordanceModel() <NEW_LINE> model.set_corpus(self.corpus) <NEW_LINE> model.set_word("of") <NEW_LINE> ind00 = model.index(0, 0) <NEW_LINE> self.assertIsInstance(model.data(ind00, Qt.ForegroundRole), (QBrush, type(None))) <NEW_LINE> self.assertIsInstance... | Other possibly implemented roles return correct types | 625941dcd8ef3951e3243834 |
def get_traceback_html(self): <NEW_LINE> <INDENT> if issubclass(self.exc_type, TemplateDoesNotExist): <NEW_LINE> <INDENT> from django.template.loader import template_source_loaders <NEW_LINE> self.template_does_not_exist = True <NEW_LINE> self.loader_debug_info = [] <NEW_LINE> for loader in template_source_loaders: <NE... | Return HTML code for traceback. | 625941dc0c0af96317bb84de |
def loadRMGPyJob(inputFile, chemkinFile=None, speciesDict=None, generateImages=True, useChemkinNames=False): <NEW_LINE> <INDENT> from rmgpy.rmg.main import RMG <NEW_LINE> rmg = RMG(inputFile=inputFile) <NEW_LINE> rmg.loadInput(inputFile) <NEW_LINE> rmg.outputDirectory = os.path.abspath(os.path.dirname(inputFile)) <NEW_... | Load the results of an RMG-Py job generated from the given `inputFile`. | 625941dcd268445f265b5164 |
def ste_configuration_view(request): <NEW_LINE> <INDENT> error = '' <NEW_LINE> if not request.user.is_authenticated(): <NEW_LINE> <INDENT> return HttpResponseRedirect("/login") <NEW_LINE> <DEDENT> vendors = [] <NEW_LINE> stes = Antenna().STEs <NEW_LINE> antennas = {} <NEW_LINE> for antenna in Antenna.objects.all().orde... | View for STE configurations | 625941dc462c4b4f79d1d9c6 |
def __init__(self, optimizer, lr_lambda, *args, **kwargs): <NEW_LINE> <INDENT> super(LambdaLR, self).__init__(*args, **kwargs) <NEW_LINE> self._scheduler = lrs.LambdaLR(optimizer, lr_lambda) | Initialization for LambdaLR.
Parameters
----------
optimizer: torch.optim.Optimizer
Optimizer for the training net.
lr_lambda: function or list
A function which computes a multiplicative factor given an integer
parameter epoch, or a list of such functions, one for each group
in optimizer.param_groups. | 625941dca79ad161976cc43c |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.end is None: <NEW_LINE> <INDENT> self.end = genpy.Time() <NEW_LINE> <DEDENT> if self.moves is None: <NEW_LINE> <INDENT> self.m... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941dc21a7993f00bc7fea |
def create_app(self): <NEW_LINE> <INDENT> return app | Return the app. | 625941dc60cbc95b062c6839 |
def short_lived_handler(event, context): <NEW_LINE> <INDENT> if 'key' in event: <NEW_LINE> <INDENT> sessionKey, requestMeta = decrypt_encrypted_metadata(event) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sessionKey, requestMeta = None, event <NEW_LINE> <DEDENT> method = requestMeta['method'] <NEW_LINE> url = requestM... | Handle a single request and return it immediately | 625941dcd99f1b3c44c67880 |
def detrend(self, order=1, picks=None): <NEW_LINE> <INDENT> if picks is None: <NEW_LINE> <INDENT> picks = pick_types(self.info, meg=True, eeg=True, ref_meg=False, stim=False, eog=False, ecg=False, emg=False, exclude='bads') <NEW_LINE> <DEDENT> self.data[picks] = detrend(self.data[picks], order, axis=-1) | Detrend data
This function operates in-place.
Parameters
----------
order : int
Either 0 or 1, the order of the detrending. 0 is a constant
(DC) detrend, 1 is a linear detrend.
picks : None | array of int
If None only MEG and EEG channels are detrended. | 625941dc23849d37ff7b3383 |
def handle_empty_skill(item): <NEW_LINE> <INDENT> if len(item['specialize']) == 0: <NEW_LINE> <INDENT> item['specialize'] = 'Xem ở trang gốc' | Though the field is required, the site is "free-style" and cannot
easily determine where this part is, so skip it. | 625941dc5f7d997b87174d90 |
def gamekeys_handler(client, response): <NEW_LINE> <INDENT> data = parse_data(response) <NEW_LINE> if isinstance(data, list): <NEW_LINE> <INDENT> return [v['gamekey'] for v in data] <NEW_LINE> <DEDENT> authenticated_response_helper(response, data) <NEW_LINE> raise exceptions.HumbleResponseException( "Unexpected respons... | get_gamekeys response always returns JSON | 625941dc76d4e153a657ee28 |
def unsubscribe_to_type(self, thing, callback, path): <NEW_LINE> <INDENT> if path in self.subscription_map: <NEW_LINE> <INDENT> if thing in self.subscription_map[path]: <NEW_LINE> <INDENT> for subscription in self.subscription_map[path][thing]: <NEW_LINE> <INDENT> if subscription.callback == callback: <NEW_LINE> <INDEN... | Unsubscribe from a given type of objects that get put on the
blackboard | 625941dc45492302aab5e5bc |
def test_pynipv6network___init__(ipv6_networks_valid): <NEW_LINE> <INDENT> for netaddress in ipv6_networks_valid: <NEW_LINE> <INDENT> pynipv6network = pynetcal.PyNIPv6Network(netaddress) <NEW_LINE> expected_network = IPv6Network(netaddress) <NEW_LINE> expected_network_address = pynetcal.PyNIPv6Address( IPv6Network(neta... | Tests for the __init__() function | 625941dc8c3a8732951586b3 |
def test_no_uri_prefixes_if_no_plugins(self): <NEW_LINE> <INDENT> core = MimicCore(Clock(), []) <NEW_LINE> self.assertEqual(0, len(core.uri_prefixes)) <NEW_LINE> self.assertEqual([], list(core.entries_for_tenant('any_tenant', {}, 'http://mimic'))) | If there are no plugins provided to :class:`MimicCore`, there are no
uri prefixes or entries for the tenant. | 625941dc4e696a04525c9742 |
def _fitstart_poisson(self, x, fixed=None): <NEW_LINE> <INDENT> a = x.min() <NEW_LINE> eps = 0 <NEW_LINE> if fixed is None: <NEW_LINE> <INDENT> loc = a - eps <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if np.isnan(fixed[-1]): <NEW_LINE> <INDENT> loc = a - eps <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loc = fixed[... | maximum likelihood estimator as starting values for Poisson distribution
Parameters
----------
x : array
data for which the parameters are estimated
fixed : None or array_like
sequence of numbers and np.nan to indicate fixed parameters and parameters
to estimate
Returns
-------
est : tuple
preliminary... | 625941dc3cc13d1c6d3c766f |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, VolumeSnapshotPost): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941dc32920d7e50b284c9 |
def ex_delete_port_forwarding_rule(self, node, rule): <NEW_LINE> <INDENT> node.extra['port_forwarding_rules'].remove(rule) <NEW_LINE> node.public_ips.remove(rule.address) <NEW_LINE> res = self._async_request('deletePortForwardingRule', id=rule.id) <NEW_LINE> return res['success'] | Remove a Port forwarding rule.
@param node: Node used in the rule
@type node: L{CloudStackNode}
@param rule: Forwarding rule which should be used
@type rule: L{CloudStackPortForwardingRule}
@rtype: C{bool} | 625941dc435de62698dfdf43 |
def filter(self, pattern): <NEW_LINE> <INDENT> self.result = [row for row in self.result if fnmatch.fnmatch(row['name'], pattern)] | Filter result to rows with matching app instances | 625941dc50812a4eaa59c615 |
def test_vectorize_2021c(self): <NEW_LINE> <INDENT> cl, poly = self.init_point(28, 6, 29, 18, 10, 20) <NEW_LINE> self.assertEqual(cl, '2021') <NEW_LINE> self.assertEqual(len(poly), 2) <NEW_LINE> self.valid_poly(poly[0], [[13.64, 20, 20], [18.18, 20, 10], [20, 18.26, 10], [20, 13.91, 20], [13.64, 20, 20]]) <NEW_LINE> se... | Test the `2021c` case. | 625941dc7d847024c06be5b5 |
def test_in_with_exception( self, mock_sasl_client, mock_tsocket, ): <NEW_LINE> <INDENT> self.mock_transport.return_value.is_open.return_value = False <NEW_LINE> self.mock_transport.return_value.read = mock_read( self.connect_received_data) <NEW_LINE> mock_sasl_client.return_value.wrap = lambda data: data <NEW_LINE> mo... | test kerberos exception in with | 625941dc07f4c71912b1177a |
def share_server_get_all_by_host(context, host): <NEW_LINE> <INDENT> return IMPL.share_server_get_all_by_host(context, host) | Get all share servers related to particular host. | 625941dc94891a1f4081bda1 |
def __init__(self, parent=iface.mainWindow(), pluginM = None): <NEW_LINE> <INDENT> super(CedulaPadronDialog, self).__init__(parent, flags=Qt.WindowMinimizeButtonHint|Qt.WindowCloseButtonHint) <NEW_LINE> self.pluginM = pluginM <NEW_LINE> self.setupUi(self) | Constructor. | 625941dce5267d203edcdf90 |
def __init__(self, time_vector, particlesList,speed = 20,forever = True,dim = 1,show_trajectory = True): <NEW_LINE> <INDENT> self.forever = forever <NEW_LINE> self.particlesList = particlesList <NEW_LINE> self.time_vector = time_vector <NEW_LINE> self.stream = self.data_stream() <NEW_LINE> self.dim = dim <NEW_LINE> sel... | time_vector - list with time steps of simulation
particlesList - list with particles to plot
particle.motion = "moving" or "static"
particle.trajectory = [(x0,y0),(x1,y1),...,(xn,yn)] - list with coordinates of particle
speed - Delay between frames in milliseconds.
forever - whether or not to repeat simulation ... | 625941dc3539df3088e2e641 |
@pytest.mark.skipif(is_windows(), reason="Doesn't run on Windows yet.") <NEW_LINE> def test_html_with_style(): <NEW_LINE> <INDENT> f = _Capture() <NEW_LINE> html = HTML("<ansigreen>hello</ansigreen> <b>world</b>") <NEW_LINE> formatted_text = to_formatted_text(html, style="class:myhtml") <NEW_LINE> pt_print(formatted_te... | Text `print_formatted_text` with `HTML` wrapped in `to_formatted_text`. | 625941dcc432627299f04f3e |
def alpha_delta_to_skyvector(alpha_degrees, delta_degrees): <NEW_LINE> <INDENT> ra, dec= radians(alpha_degrees), radians(delta_degrees) <NEW_LINE> return ( cos(ra) * cos (dec), cos (dec) * sin (ra), sin (dec) ) | Given an alpha, delta (in degrees), returns the sky vector (sidereral coordinates) as a 3-tuple | 625941dcf7d966606f6aa2fe |
def binarySearch(array, target): <NEW_LINE> <INDENT> length = len(array) <NEW_LINE> halfLength = length // 2 <NEW_LINE> comparator = array[halfLength] <NEW_LINE> if target == comparator: <NEW_LINE> <INDENT> return halfLength <NEW_LINE> <DEDENT> elif target < comparator: <NEW_LINE> <INDENT> return binarySearch(array[:ha... | Searches for `target` within `array` using a binary search.
Assumes that the given array is sorted. | 625941dcd268445f265b5165 |
def create_named_conf(paths, realm, dnsdomain, dns_backend, logger): <NEW_LINE> <INDENT> from samba.provision import ProvisioningError <NEW_LINE> if dns_backend == "BIND9_FLATFILE": <NEW_LINE> <INDENT> setup_file(setup_path("named.conf"), paths.namedconf, { "DNSDOMAIN": dnsdomain, "REALM": realm, "ZONE_FILE": paths.dns... | Write out a file containing zone statements suitable for inclusion in a
named.conf file (including GSS-TSIG configuration).
:param paths: all paths
:param realm: Realm name
:param dnsdomain: DNS Domain name
:param dns_backend: DNS backend type
:param keytab_name: File name of DNS keytab file
:param logger: Logger obje... | 625941dcaad79263cf390d3c |
def setup(self, X, Y, kt): <NEW_LINE> <INDENT> self.beta = 1./kt <NEW_LINE> dX, dY = X-X.reshape(-1,1), Y-Y.reshape(-1,1) <NEW_LINE> self.R = np.sqrt(dX**2+dY**2) <NEW_LINE> self._spatial_rates() | Setup the model for the given DB arrangement
inputs:
X : matrix of x positions, angstroms
Y : matrix of y positions, angstroms
kt : thermal energy of surface, eV | 625941dc96565a6dacc8f9c1 |
def validate_existing_product(self, action, data): <NEW_LINE> <INDENT> self._validate(action, data) <NEW_LINE> project = data.get('existing_product') <NEW_LINE> try: <NEW_LINE> <INDENT> validate_target(self.context.bug, project) <NEW_LINE> <DEDENT> except IllegalTarget as e: <NEW_LINE> <INDENT> self.setFieldError('exis... | Check if the chosen project is not already affected by this bug. | 625941dc004d5f362079a628 |
def compute_paragraph_score(sample): <NEW_LINE> <INDENT> scores = [] <NEW_LINE> question = sample["segmented_question"] <NEW_LINE> for doc in sample['documents']: <NEW_LINE> <INDENT> doc['segmented_paragraphs_scores'] = [] <NEW_LINE> for p_idx, para_tokens in enumerate(doc['segmented_paragraphs']): <NEW_LINE> <INDENT> ... | For each paragraph, compute the f1 score compared with the question
Args:
sample: a sample in the dataset.
Returns:
None
Raises:
None | 625941dc851cf427c661a803 |
def afterish(content, separator=","): <NEW_LINE> <INDENT> numeric = is_numeric(content) <NEW_LINE> if numeric and separator in content: <NEW_LINE> <INDENT> pos = content.rfind(separator) + 1 <NEW_LINE> included = it.takewhile(lambda x: x.isdigit(), content[pos:]) <NEW_LINE> after = len(list(included)) <NEW_LINE> <DEDEN... | Calculates the number of digits after a given separator.
Args:
content (str): The string to parse.
separator (char): Character to start counting from (default: ',').
exclude (char): Character to ignore from the calculation (default: '').
Returns:
int: the number of digits that appear after the separat... | 625941dc76e4537e8c35196b |
def self(self): <NEW_LINE> <INDENT> return self.agent.http.get( lambda x: json.loads(x.body), '/v1/agent/self') | Returns configuration of the local agent and member information. | 625941dc1f037a2d8b9464f4 |
def assignParameters(self,solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rfree, PermGroFac,BoroCnstArt,aXtraGrid,pLvlGrid,vFuncBool,CubicBool): <NEW_LINE> <INDENT> ConsIndShockSetup.assignParameters(self,solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rfree, PermGroFac,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool) <NEW_LINE> s... | Assigns period parameters as attributes of self for use by other methods
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
IncomeDstn : [np.array]
A list containing three arrays of floats, representing a discrete
approximation to the income process bet... | 625941dc460517430c394475 |
def __init__(self, drawer, draw_type=None, file=None, image_base=None, image_heading_default=0, marker_type=None, **kwargs ): <NEW_LINE> <INDENT> if draw_type is None: <NEW_LINE> <INDENT> draw_type = super().DT_IMAGE <NEW_LINE> <DEDENT> super().__init__(drawer, draw_type=draw_type, **kwargs) <NEW_LINE> self.file = file... | Setup basic marker state
:drawer: drawing control
:file: image file, if one
:image_base: base image, if one
May be added later via set_image_base()
:marker_type: marker type (.e.g "letter")
:kwargs: basic DmMarker args | 625941dc3c8af77a43ae3a99 |
def read_tpr(tprfile=None): <NEW_LINE> <INDENT> if not isinstance(tprfile, TprFile): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tprfile = TprFile(os.fsencode(tprfile), mode='r') <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> tprfile = None <NEW_LINE> <DEDENT> <DEDENT> if tprfile is None: <NEW_LINE> <INDENT... | Get a simulation input object from a TPR run input file.
Arguments:
tprfile : TPR input object or filename
Returns:
simulation input object
The returned object may be inspected by the user. Simulation input parameters
may be extracted through the `parameters` attribute.
Example:
>>> sim_input = gmx.fil... | 625941dc91af0d3eaac9bd12 |
def count_active_neighbors( grid: Dict[Tuple[int, ...], str], point: Tuple[int, ...], dimensions: int = 3 ): <NEW_LINE> <INDENT> assert dimensions in (3, 4) <NEW_LINE> return sum( 1 for neighbor_point in generate_neighbors(point, dimensions=dimensions) if grid.get(neighbor_point, INACTIVE) == ACTIVE ) | Count the active neighbors of the given 3 or 4 dimensional point | 625941dc71ff763f4b549987 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941dcb7558d58953c5206 |
def pack(self): <NEW_LINE> <INDENT> buffer = [] <NEW_LINE> buffer.extend(PayloadAction.PayloadAction.pack(self)) <NEW_LINE> buffer.append(struct.pack(">f", self.Azimuth)) <NEW_LINE> buffer.append(struct.pack(">f", self.Elevation)) <NEW_LINE> buffer.append(struct.pack(">f", self.Rotation)) <NEW_LINE> return "".join(buff... | Packs the object data and returns a string that contains all of the serialized
members. | 625941dce76e3b2f99f3aafe |
def parse(self, input): <NEW_LINE> <INDENT> if hasattr(input, 'name'): <NEW_LINE> <INDENT> self.filename = input.name <NEW_LINE> <DEDENT> elif not getattr(self, 'filename', ''): <NEW_LINE> <INDENT> self.filename = '' <NEW_LINE> <DEDENT> if hasattr(input, "read"): <NEW_LINE> <INDENT> inisrc = input.read() <NEW_LINE> inp... | parse the given file or file source string | 625941dc8e71fb1e9831da9f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.