code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def calcula_stop_loss(preco_actual, preco_inicial): <NEW_LINE> <INDENT> tmp_stop_loss = float((preco_actual*4.0)/100) <NEW_LINE> stop_loss = float(preco_actual - tmp_stop_loss) <NEW_LINE> return stop_loss
Calcula o valor de um stop loss Sempre que o preco actual for superior em 3% ao preco anterior é colocado um stop-loss
625941c41f037a2d8b9461f2
def delete_user(self, id, realm): <NEW_LINE> <INDENT> path = "/{realm}/users/{id}".format( id=id, realm=realm ) <NEW_LINE> params = { } <NEW_LINE> headers = { } <NEW_LINE> return self.session.request( method="DELETE", endpoint=self.session._admurl(path), params=params, )
Delete the user (Users) Parameters ---------- id : string (Required, Path) User id realm : string (Required, Path) realm name (not id!)
625941c4dd821e528d63b19e
def diagonalize(self, H_NN, eps_n): <NEW_LINE> <INDENT> nbands = self.bd.nbands <NEW_LINE> mynbands = self.bd.mynbands <NEW_LINE> eps_N = np.empty(nbands) <NEW_LINE> self.timer.start('Diagonalize') <NEW_LINE> self.block_comm.broadcast(H_NN, 0) <NEW_LINE> self._diagonalize(H_NN, eps_N) <NEW_LINE> self.timer.stop('Diagon...
Serial diagonalizer must handle two cases: 1. Parallelization over domains only. 2. Simultaneous parallelization over domains and bands.
625941c4cdde0d52a9e53025
def is_str_type(val): <NEW_LINE> <INDENT> return isinstance(val, (bytes, unicode, np.string_, np.bytes_, np.unicode))
Return True if val is a string type
625941c4d53ae8145f87a266
def dequeue(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise PrioQueueError('in dequeue') <NEW_LINE> <DEDENT> elems = self._elems <NEW_LINE> e0 = elems[0] <NEW_LINE> e = elems.pop() <NEW_LINE> return e0
出队操作
625941c4a05bb46b383ec817
def main(): <NEW_LINE> <INDENT> x = 0.07*2*math.pi <NEW_LINE> vaspy.MakeInputs.all('.', kp_rx=0.18, kp_soc=0.15)
alt parameter
625941c4bf627c535bc131c2
@then("click '{ng_if_locator}' button element") <NEW_LINE> def step(context, ng_if_locator): <NEW_LINE> <INDENT> context.clickActions = ClickActions(context) <NEW_LINE> context.clickActions.click_ng_if_xpath(ng_if_locator)
Then click '{ng_if_locator}' button element
625941c4ff9c53063f47c1e8
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, JsonChangeAssetTypeRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c4d6c5a1020814403d
def testSupportQ(self): <NEW_LINE> <INDENT> source = dict(q=Q(a=1) | Q(b=2) & Q(c=3)) <NEW_LINE> content_type, encoding, result = serialization.dumps(source, 'x-rpc-json') <NEW_LINE> restored = serialization.loads(result, content_type, encoding) <NEW_LINE> expected = jsonpickle.encode(source) <NEW_LINE> result = jsonpi...
Encoder/Decoder support Django Q-object
625941c4be383301e01b547c
def __init__(self, cv, x, pps, colors, pos, speed, timer, angle=0.25): <NEW_LINE> <INDENT> super().__init__(cv) <NEW_LINE> self.y = 500 <NEW_LINE> if isinstance(x, list) and len(x) > 1: <NEW_LINE> <INDENT> self.x = x[0] <NEW_LINE> self.y = x[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.x = x <NEW_LINE> <DEDENT...
Shoots a rocket into the sky which then explodes. Arguments: cv {idontknow} -- the canvas upon which this wonderful display is painted x {int} -- the position of the rocketrocket pps {int} -- pixels per second (the speed of the particles) colors {str} -- the color of the particles pos {int}...
625941c4fb3f5b602dac3685
def fix_updr(self, updr:int, delta:int) -> int: <NEW_LINE> <INDENT> while delta != 0: <NEW_LINE> <INDENT> if delta < 0: <NEW_LINE> <INDENT> new_updr = max(0,updr+delta) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_updr = min(self.num_updr-1,updr+delta) <NEW_LINE> <DEDENT> if (self.avail_updr & (1<<new_updr)) != 0 ...
Move given up datarate by delta notches. Delta > 0 towards faster datarates. Used in ADR decisions in network server.
625941c4187af65679ca5112
def delete(self, keypress=None): <NEW_LINE> <INDENT> if len(self.values) < 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> entry = self.values[self.cursor_line] <NEW_LINE> really = npyscreen.notify_yes_no( 'Really delete the entry "{}"?'.format(entry['name']), form_color='CRITICAL' ) <NEW_LINE> if really: <NEW_...
Ask and delete entry.
625941c45f7d997b87174a8a
def add_cloudstack(self, url, api_key, secret_key): <NEW_LINE> <INDENT> parsed_url = urlparse(url) <NEW_LINE> hostname = parsed_url.hostname <NEW_LINE> deviceRoot = self._dmd.getDmdRoot("Devices") <NEW_LINE> device = deviceRoot.findDeviceByIdExact(hostname) <NEW_LINE> if device: <NEW_LINE> <INDENT> return False, _t("A ...
Handles adding a new CloudStack cloud to the system.
625941c401c39578d7e74e2f
def get_paginated_response(self, data): <NEW_LINE> <INDENT> return Response(OrderedDict([ ("page", self.page.number), ("num_pages", self.page.paginator.num_pages), ("count", self.page.paginator.count), ("next", self.get_next_link()), ("next_page_number", self.page.next_page_number() if self.page.has_next() else None), ...
Return response with some additional fields. :param data: data queryset. :type data: django.db.models.query.QuerySet. :return: extended django rest framework response. :rtype: rest_framework.response.Response.
625941c43eb6a72ae02ec4cd
def HuffEncode(freq_dict): <NEW_LINE> <INDENT> heap = [[wt, [sym, ""]] for sym, wt in freq_dict.items()] <NEW_LINE> heapify(heap) <NEW_LINE> while len(heap) > 1: <NEW_LINE> <INDENT> lo = heappop(heap) <NEW_LINE> hi = heappop(heap) <NEW_LINE> for pair in lo[1:]: <NEW_LINE> <INDENT> pair[1] = '0' + pair[1] <NEW_LINE> <DE...
Return a dictionary which maps keys from the input dictionary freq_dict to bitstrings using a Huffman code based on the frequencies of each key
625941c41d351010ab855b10
def register_errorhandlers(app): <NEW_LINE> <INDENT> def render_error(error): <NEW_LINE> <INDENT> error_code = getattr(error, 'code', 500) <NEW_LINE> return render_template("{0}.html".format(error_code)), error_code <NEW_LINE> <DEDENT> for errcode in [401, 403, 404, 500]: <NEW_LINE> <INDENT> app.errorhandler(errcode)(r...
Add errorhandlers to the app.
625941c4236d856c2ad447cc
@app.route('/count/movies', defaults={'go': Movie}) <NEW_LINE> @app.route('/count/people', defaults={'go': Person}) <NEW_LINE> def count_objects(go): <NEW_LINE> <INDENT> return jsonify({ 'primary_label': go.__primarylabel__, 'total': go.count_nodes(ogm.graph) })
Count the total number of nodes of this type
625941c4d10714528d5ffcd5
def test_file_positive() -> None: <NEW_LINE> <INDENT> collection = RulesCollection() <NEW_LINE> collection.register(BecomeUserWithoutBecomeRule()) <NEW_LINE> success = "examples/playbooks/become-user-without-become-success.yml" <NEW_LINE> good_runner = Runner(success, rules=collection) <NEW_LINE> assert [] == good_runn...
Positive test for partial-become.
625941c460cbc95b062c6537
def test_e_edit_inside_apply(self): <NEW_LINE> <INDENT> start_time = "2017-10-10" <NEW_LINE> eamount = "80000" <NEW_LINE> year_sales = "90" <NEW_LINE> lianbao_daikuan_yue = "0" <NEW_LINE> jiufen = "否" <NEW_LINE> inside.inside_apply(self.webdriver, self.loanno, self.fullname, self.loan_type, self.marry_status, self.bank...
编辑内部审批
625941c4f9cc0f698b1405f1
def __init__(self, version, sid): <NEW_LINE> <INDENT> super(AssistantContext, self).__init__(version) <NEW_LINE> self._solution = {'sid': sid, } <NEW_LINE> self._uri = '/Assistants/{sid}'.format(**self._solution) <NEW_LINE> self._field_types = None <NEW_LINE> self._tasks = None <NEW_LINE> self._model_builds = None <NEW...
Initialize the AssistantContext :param Version version: Version that contains the resource :param sid: A 34-character string that uniquely identifies this resource. :returns: twilio.rest.autopilot.v1.assistant.AssistantContext :rtype: twilio.rest.autopilot.v1.assistant.AssistantContext
625941c438b623060ff0ade2
def request_hints(): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for var in [ "SERVER_ADDR", "LOCAL_ADDR" ]: <NEW_LINE> <INDENT> value = request.environ.get(var, None) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> result["server"] = value <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> requ...
Return tuple of (hints, response). If hints is None, response is a response for the caller to return to the requester.
625941c430c21e258bdfa490
def __init__(self): <NEW_LINE> <INDENT> MaximaFunction.__init__(self, name)
Constructs an object that wraps a Maxima function. TESTS:: sage: spherical_hankel2(2,x) (-I*x^2 - 3*x + 3*I)*e^(-I*x)/x^3
625941c40c0af96317bb81dc
def _decrypt_data(self, session_data): <NEW_LINE> <INDENT> if self.encrypt_key: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> __, nonce_b64len = self.encrypt_nonce_size <NEW_LINE> nonce = session_data[:nonce_b64len] <NEW_LINE> encrypt_key = crypto.generateCryptoKeys(self.encrypt_key, self.validate_key + nonce, 1) <NEW_L...
Bas64, decipher, then un-serialize the data for the session dict
625941c44f6381625f114a30
def get_raw(self, use_cache=None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if use_cache is not None: <NEW_LINE> <INDENT> params["useCache"] = use_cache <NEW_LINE> <DEDENT> response = self.connection.api_call( "GET", ["deliveries", self.dataset_id, self.id, "raw"], params=params ) <NEW_LINE> resource_list = response....
Get the raw delivery data Args: use_cache (bool): Preference to set cached response Returns: list (:obj:`crux.models.Resource`): List of resources.
625941c46fb2d068a760f08f
def test_without_strip_whitespace(self): <NEW_LINE> <INDENT> strip = Strip(strip_whitespace=False) <NEW_LINE> result = strip(["a", "", " ", "b"]) <NEW_LINE> self.assertListEqual(result, ["a", " ", "b"])
Only empty items must be removed.
625941c4ab23a570cc250175
def testCreateGroups(self): <NEW_LINE> <INDENT> with sudo.SudoKeepAlive(): <NEW_LINE> <INDENT> with cgroups.SimpleContainChildren('example', sigterm_timeout=5): <NEW_LINE> <INDENT> parallel.RunTasksInProcessPool(self._CrosSdk, [[]] * 20, 10)
Run many cros_sdk processes in parallel to test for race conditions.
625941c4004d5f362079a328
def __init__(self, images, *, custom_classes=None, images_processed=None, warnings=None): <NEW_LINE> <INDENT> self.custom_classes = custom_classes <NEW_LINE> self.images_processed = images_processed <NEW_LINE> self.images = images <NEW_LINE> self.warnings = warnings
Initialize a ClassifiedImages object. :param list[ClassifiedImage] images: Classified images. :param int custom_classes: (optional) Number of custom classes identified in the images. :param int images_processed: (optional) Number of images processed for the API call. :param list[WarningInfo] warnings: (o...
625941c4be383301e01b547d
def test_set_is_poa(self): <NEW_LINE> <INDENT> article_xml_file = "pb369-jats.xml" <NEW_LINE> file_path = TEST_DATA_PATH + article_xml_file <NEW_LINE> config_section = "pb" <NEW_LINE> articles = generate.build_articles_for_pubmed( article_xmls=[file_path], config_section=config_section ) <NEW_LINE> articles[0].is_poa =...
test a method to make a non-eLife article aheadofprint by setting is_poa
625941c45fcc89381b1e16b2
def find_best_split(data): <NEW_LINE> <INDENT> best_gain = 0 <NEW_LINE> best_question = None <NEW_LINE> current_uncertainty = gini_impurity(data['label']) <NEW_LINE> n_features = list(data.columns) <NEW_LINE> n_features.remove('label') <NEW_LINE> for col in n_features: <NEW_LINE> <INDENT> values = list(data[col].value_...
Find the best question to ask by iterating over every feature / value and calculating the information gain.
625941c4046cf37aa974cd3d
def removeFirst(e, L): <NEW_LINE> <INDENT> if L == []: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> elif L == '': <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> elif L[0] == e: <NEW_LINE> <INDENT> return L[1:] <NEW_LINE> <DEDENT> elif isinstance(L, list) == True: <NEW_LINE> <INDENT> return [L[0]] + removeFirst(...
Returns a list identical to list L without the first top-level instance of e. input e: an element input L: a list
625941c431939e2706e4ce60
def set_html_resources_prefix(self, prefix): <NEW_LINE> <INDENT> self.html_resources_prefix = prefix + '-'
Sets the prefix for the resources filename. example: set_resources_prefix('jbds')
625941c47c178a314d6ef451
def shear(value: float = 0.0, mirror: bool = False, proportional: int = 'DISABLED', proportional_edit_falloff: int = 'SMOOTH', proportional_size: float = 1.0, snap: bool = False, snap_target: int = 'CLOSEST', snap_point: float = (0.0, 0.0, 0.0), snap_align: bool = False, snap_normal: float = (0.0, 0.0, 0.0), gpencil_st...
Shear selected items along the horizontal screen axis :param value: Offset :type value: float :param mirror: Mirror Editing :type mirror: bool :param proportional: Proportional EditingDISABLED Disable, Proportional Editing disabled.ENABLED Enable, Proportional Editing enabled.PROJECTED Projected (2D), Proportional ...
625941c58c3a8732951583ad
@fixture <NEW_LINE> def post(request, entity): <NEW_LINE> <INDENT> schema = 'https://tent.io/types/post/status/v0.1.0' <NEW_LINE> post = Post(entity=entity, schema=schema) <NEW_LINE> post.new_version( content={ 'text': "Hello world", 'coordinates': [0, 0], }, mention=[]) <NEW_LINE> post.new_version( content={ 'text': "...
A post with multiple versions
625941c4379a373c97cfab38
def match_dict_regexp(d, r): <NEW_LINE> <INDENT> for pattern, elem in d.items(): <NEW_LINE> <INDENT> result = re.match(pattern, r) <NEW_LINE> if result: <NEW_LINE> <INDENT> return elem, result <NEW_LINE> <DEDENT> <DEDENT> return None, None
The same as d[r] but uses regex match. Return (d[r] and match_result) Return None in case no match found.
625941c5b830903b967e9901
def circle_shift(data, random_state=None): <NEW_LINE> <INDENT> random_state = check_random_state(random_state) <NEW_LINE> data = np.array(data) <NEW_LINE> if len(data.shape) == 1: <NEW_LINE> <INDENT> shift = random_state.choice(np.arange(len(data)), replace=False) <NEW_LINE> shifted = np.concatenate((data[-shift:], dat...
Circle shift data for each feature Args: data: time series (1D or 2D). If 2D, then must be observations by features random_state: (int, None, or np.random.RandomState) Initial random seed (default: None) Returns: shifted data
625941c5097d151d1a222e4f
def get_price(self): <NEW_LINE> <INDENT> return self.unit_price
Returns the price for this item (provided for extensibility).
625941c59f2886367277a883
def base_context(request): <NEW_LINE> <INDENT> return { 'SITE_NAME': settings.SITE_NAME, 'SITE_SUB_NAME': settings.SITE_SUB_NAME, }
Base Settings to Context
625941c571ff763f4b54967d
def createUniqueFragmentsTable(self,color=None,unique_fragments=None,average_unique=None): <NEW_LINE> <INDENT> vTableHtml = [] <NEW_LINE> self.tableDefinition(vectorHtml=vTableHtml,color=color) <NEW_LINE> vTableHtml.append(" <TR>\n") <NEW_LINE> vTableHtml.append(" <TH scope=\"col\">Concept</TH> <TH scope=\"col\">V...
Create Unique and Fragments Statistics Table color - Table color, could be green or blue unique_fragments - Fragments that were considere as unique average_unique - Average unique fragments returns vector of HTML tags
625941c556ac1b37e62641c7
def p_boolean_bracket(p): <NEW_LINE> <INDENT> p[0] = "(" + str(p[2]) + ")"
boolean : LPAREN boolean RPAREN
625941c58da39b475bd64f66
def masked_max_pooling(data_tensor, mask, dim): <NEW_LINE> <INDENT> if dim < 0: <NEW_LINE> <INDENT> dim = len(data_tensor.shape) + dim <NEW_LINE> <DEDENT> mask = mask.view(list(mask.shape) + [1] * (len(data_tensor.shape) - len(mask.shape))) <NEW_LINE> data_tensor = data_tensor.masked_fill(mask == 0, -1e9) <NEW_LINE> ma...
Performs masked max-pooling across the specified dimension of a Tensor. :param data_tensor: ND Tensor. :param mask: Tensor containing a binary mask that can be broad-casted to the shape of data_tensor. :param dim: Int that corresponds to the dimension. :return: (N-1)D Tensor containing the result of the max-pooling op...
625941c585dfad0860c3ae4f
@rule(Regex(r'[a-zA-Z_][a-zA-Z0-9_]*')) <NEW_LINE> def identifier(value): <NEW_LINE> <INDENT> return value
An identifier.
625941c563f4b57ef0001112
def remove_strand_ambiguous_snp(a1, a2, strand_ambiguous_alleles): <NEW_LINE> <INDENT> a1a2 = a1 + a2 <NEW_LINE> if strand_ambiguous_alleles[a1a2]: <NEW_LINE> <INDENT> return(False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return(True)
remove snps where strand cannot be determined
625941c50a50d4780f666e86
def _linear(args, output_size, bias, bias_start=0.0, scope=None): <NEW_LINE> <INDENT> if args is None or (nest.is_sequence(args) and not args): <NEW_LINE> <INDENT> raise ValueError("`args` must be specified") <NEW_LINE> <DEDENT> if not nest.is_sequence(args): <NEW_LINE> <INDENT> args = [args] <NEW_LINE> <DEDENT> total_...
Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. Args: args: a 2D Tensor or a list of 2D, batch x n, Tensors. output_size: int, second dimension of W[i]. bias: boolean, whether to add a bias term or not. bias_start: starting value to initialize the bias; 0 by default. scope: VariableSco...
625941c563b5f9789fde70da
def lambda_handler(event, context): <NEW_LINE> <INDENT> print('-------------------------') <NEW_LINE> bucketing_decision = None <NEW_LINE> querystring_params = event["queryStringParameters"] or {} <NEW_LINE> user_ip_address = event['requestContext']['identity']['sourceIp'] <NEW_LINE> user_id = querystring...
Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code.
625941c5c432627299f04c39
def _get(self): <NEW_LINE> <INDENT> character = self.look_ahead <NEW_LINE> self.look_ahead = None <NEW_LINE> if character == None: <NEW_LINE> <INDENT> character = self.input_file.read(1) <NEW_LINE> <DEDENT> if character >= " " or character == "\n": <NEW_LINE> <INDENT> return character <NEW_LINE> <DEDENT> if character =...
return the next character from stdin. Watch out for lookahead. If the character is a control character, translate it to a space or linefeed.
625941c55510c4643540f3dd
def shoot(self, beam_x, beam_y, charged=False): <NEW_LINE> <INDENT> if not charged: <NEW_LINE> <INDENT> b = PlayerWeapon(beam_x, beam_y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> b = PlayerWeaponCharged(beam_x, beam_y) <NEW_LINE> b.charging = True <NEW_LINE> self.charged_beam = b <NEW_LINE> <DEDENT> return b
Arguments: beam_x (int): x coordinate of where beam will be drawn beam_y (int): y coordinate of where beam will be drawn charged (bool): True/False depending on whether it is a charged beam or not Returns: A newly created beam object
625941c5ab23a570cc250176
def print_node_edge(graph, graph_name): <NEW_LINE> <INDENT> print("{0} number_of_nodes : {1}".format(graph_name, graph.number_of_nodes())) <NEW_LINE> print("{0} number_of_edges : {1}".format(graph_name, graph.number_of_edges()))
Graph의 node와 edge를 보여준다
625941c58da39b475bd64f67
def psimso_cv_reference_index(self, psimso_id): <NEW_LINE> <INDENT> if not hasattr(self, 'psimso_index_dict'): <NEW_LINE> <INDENT> self.psimso_index_dict = dict([(ref[2], i) for (i, ref) in enumerate(self.all_cv_references()) if ref[1] == 'MS']) <NEW_LINE> <DEDENT> return self.psimso_index_dict[psimso_id]
Takes in a Proteomics Standards Initiative Mass Spectrometry Ontology identifier (psimso_id) and returns the HDF5 CV reference index for that identifier.
625941c59c8ee82313fbb769
def get_vms(self, root=None): <NEW_LINE> <INDENT> raw_vms = self._get_all_objs([vim.VirtualMachine], root) <NEW_LINE> return sorted(raw_vms, key=lambda vm: vm.summary.config.name)
Returns all vms
625941c5796e427e537b05b9
def generate_java(src, out, jpackage_name=None): <NEW_LINE> <INDENT> package = compile(src) <NEW_LINE> java.generate(package, out, jpackage_name=jpackage_name)
Generates java files.
625941c5e1aae11d1e749caa
def g_connect(versions): <NEW_LINE> <INDENT> def decorator(method): <NEW_LINE> <INDENT> def wrapped(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self._available_api_versions: <NEW_LINE> <INDENT> display.vvvv("Initial connection to galaxy_server: %s" % self.api_server) <NEW_LINE> n_url = self.api_server <NEW_LINE>...
Wrapper to lazily initialize connection info to Galaxy and verify the API versions required are available on the endpoint. :param versions: A list of API versions that the function supports.
625941c5d10714528d5ffcd6
def index_impl(self): <NEW_LINE> <INDENT> runs = self._multiplexer.Runs() <NEW_LINE> result = {run: {} for run in runs} <NEW_LINE> mapping = self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME) <NEW_LINE> for (run, tag_to_content) in six.iteritems(mapping): <NEW_LINE> <INDENT> for (tag, content) in six.iteri...
Return {runName: {tagName: {displayName: ..., description: ...}}}.
625941c567a9b606de4a7eb0
def remove(self, grid): <NEW_LINE> <INDENT> if self._action == INSERT: <NEW_LINE> <INDENT> grid.remove_row(self.row) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> grid.insert_row(self.row)
Revert the action.
625941c5046cf37aa974cd3e
def floating_ip_added_dist(self, fip, fip_cidr): <NEW_LINE> <INDENT> if fip.get(lib_constants.DVR_SNAT_BOUND): <NEW_LINE> <INDENT> return self.add_centralized_floatingip(fip, fip_cidr) <NEW_LINE> <DEDENT> if not self._check_if_floatingip_bound_to_host(fip): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if (self.agent_...
Add floating IP to respective namespace based on agent mode.
625941c507d97122c417887d
def p_square_block(p): <NEW_LINE> <INDENT> child1 = create_leaf('SQUARE_BEGIN', p[1]) <NEW_LINE> child2 = create_leaf('SQUARE_END', p[3]) <NEW_LINE> p[0] = Node('square_block', [child1, p[2],child2], p[2].type, None,None,None,None)
square_block : SQUARE_BEGIN type SQUARE_END
625941c57b180e01f3dc47f5
def lambda_handler(event, context): <NEW_LINE> <INDENT> raw_kpl_records = event['records'] <NEW_LINE> output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records] <NEW_LINE> success_count = sum(1 for record in output if record['result'] == 'Ok') <NEW_LINE> failure_count = sum(1 for record in output if re...
A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.
625941c5627d3e7fe0d68e44
def balanced_accuracy_multiclass(y_true, y_pred): <NEW_LINE> <INDENT> perclass_balanced_accuracy = np.zeros(np.unique(y_true).shape[0]) <NEW_LINE> for i, class_ in enumerate(np.unique(y_true)): <NEW_LINE> <INDENT> y_true_class = (y_true == class_).astype(int) <NEW_LINE> y_pred_class = (y_pred == class_).astype(int) <NE...
Return a balanced accuracy, supporting also multiclass learning. This is computed averaging the balanced accuracy for each class. Here https://github.com/scikit-learn/scikit-learn/issues/6747 there is an issue on how to implement this in sklearn.
625941c58e71fb1e9831d79f
def test_get_index_sort_disk_format_asc(self): <NEW_LINE> <INDENT> UUID3 = _gen_uuid() <NEW_LINE> extra_fixture = {'id': UUID3, 'status': 'active', 'is_public': True, 'disk_format': 'ami', 'container_format': 'ami', 'name': 'asdf', 'size': 19, 'checksum': None} <NEW_LINE> db_api.image_create(self.context, extra_fixture...
Tests that the /images registry API returns list of public images sorted alphabetically by disk_format in ascending order.
625941c5a79ad161976cc13a
def _flush_buffer(self, post_ws_control=Token.WS_NONE): <NEW_LINE> <INDENT> text = "" <NEW_LINE> if self._buffer: <NEW_LINE> <INDENT> text = "".join(self._buffer) <NEW_LINE> if self._autostrip == self.AUTOSTRIP_STRIP: <NEW_LINE> <INDENT> text = text.strip() <NEW_LINE> <DEDENT> elif self._autostrip == self.AUTOSTRIP_TRI...
Flush the buffer to output.
625941c53346ee7daa2b2d60
def add_blackhole_interfaces(offset, total_interfaces, interface_list): <NEW_LINE> <INDENT> if total_interfaces == len(interface_list): <NEW_LINE> <INDENT> return interface_list <NEW_LINE> <DEDENT> updated_interface_list = [] <NEW_LINE> for i in range(offset, total_interfaces + offset): <NEW_LINE> <INDENT> for interfac...
Adds blackhole interfaces to host data by inserting a dict of blackhole config in the correct interface index position. :param offset: Interface numbering offset. :param total_interfaces: Total number of interfaces. :param interface_list: List of interface dicts to update. :return: New list of interface dicts.
625941c5fff4ab517eb2f430
def test_template(self): <NEW_LINE> <INDENT> self.assertTemplateUsed(self.response, 'index.html')
Should get index.html template
625941c5656771135c3eb862
def __init__(self, secret, path, plotall=True): <NEW_LINE> <INDENT> self.gc = pygsheets.authorize(outh_file=secret, outh_nonlocal=True, no_cache=True) <NEW_LINE> self.path = os.path.dirname(path) <NEW_LINE> self.plotall = plotall
Configure object. Args: secret (str): path to secret file path (str): folder where plot are saved. Name of plot is same as name of datafile. plotall (bool): If True, filename given when calling object is interpreted as prefix. Otherwise it is exact name of file and only this plot ...
625941c5c432627299f04c3a
def get_tags(self): <NEW_LINE> <INDENT> return self.__tags
Returns the list of tags.
625941c50383005118ecf5d9
def act(self, state): <NEW_LINE> <INDENT> if self.MODE == 'test': <NEW_LINE> <INDENT> return self.sess.run(self.actions, {self.states: state[np.newaxis, :]})[0] <NEW_LINE> <DEDENT> elif self.MODE == 'train': <NEW_LINE> <INDENT> if self.config['COUNTER'] < self.config['MEMORY_CAPACITY']: <NEW_LINE> <INDENT> if self.conf...
When the current state is inputted to this function, the current state is fed into the rl agent andthe action is outputted. This function takes into consideration the concept of exploration and exploitation. Args: state (arr): the state parameter defined in the Simulator class. Returns: Either a randomly...
625941c599cbb53fe6792bdc
def _getFilePathFromId(self, jobStoreFileID): <NEW_LINE> <INDENT> absPath = os.path.join(self.jobStoreDir, jobStoreFileID) <NEW_LINE> return absPath
:param str jobStoreFileID: The ID of a file :rtype : string, string is the absolute path that that file should appear at on disk, under either self.jobsDir if it is to be cleaned up with a job, or self.filesDir otherwise.
625941c53d592f4c4ed1d067
def initGui(self): <NEW_LINE> <INDENT> icon_path = ':/plugins/VectorDistributionExtractionPerFile/icon.png' <NEW_LINE> self.add_action( icon_path, text=self.tr(u'Write the distribution of one or several vector layers/files in each feature of an area vector layer/file'), callback=self.run, parent=self.iface.mainWindow()...
Create the menu entries and toolbar icons inside the QGIS GUI.
625941c53317a56b86939c51
def reshape_to_long_for_output(df): <NEW_LINE> <INDENT> del df['file_name'] <NEW_LINE> del df['link'] <NEW_LINE> del df['source'] <NEW_LINE> del df['version'] <NEW_LINE> del df['description'] <NEW_LINE> df = df.set_index(['year', 'code', 'ressources', 'institution', 'file_title']) <NEW_LINE> df = df.unstack(level = 'ye...
Unmelts the data, using the years as variables (columns). Parameters ---------- df : DataFrame DataFrame generated by get_comptes_nationaux_data(year) and/or look_many(df, my_selection) Example -------- >>> from ipp_macro_series_parser.comptes_nationaux.cn_parser_main import get_comptes_nationaux_data >>> from ip...
625941c5cc40096d61595946
def shbkDiff(self): <NEW_LINE> <INDENT> return currencyDiff(self.data, lexiconList()[7])
生活百科类接口 :return:
625941c550812a4eaa59c318
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE...
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941c53eb6a72ae02ec4ce
def ExportSetPlane(self,pPlane): <NEW_LINE> <INDENT> pass
ExportSetPlane(self: DelegateFake,pPlane: dotPlane_t) -> (int,dotPlane_t)
625941c5004d5f362079a329
def perm_test(labels, response_vars, stat_func, n): <NEW_LINE> <INDENT> unique_label_counts = labels.value_counts() <NEW_LINE> label_0 = unique_label_counts.index[0] <NEW_LINE> label_1 = unique_label_counts.index[1] <NEW_LINE> label_0_count = unique_label_counts[0] <NEW_LINE> label_1_count = unique_label_counts[1] <NEW...
Labels: Series with two labels, Response_vars series in same order as labels stat_func is a function that takes in two series and returns a statistic, n is permutation numnber
625941c5dc8b845886cb5529
def write2grp(genomeSizeDict, fwd=None, rev=None, prefix=None, toInteger=True): <NEW_LINE> <INDENT> if (fwd and (not rev)) or (rev and (not fwd)): <NEW_LINE> <INDENT> if fwd: <NEW_LINE> <INDENT> header = "# BASE fwd_grp\n# colour 0:255:0\n" <NEW_LINE> wig = fwd <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> header = "# ...
convert wig to grp file
625941c5f8510a7c17cf96f1
def emit(self, record): <NEW_LINE> <INDENT> write_api = self.client.write_api(write_options=SYNCHRONOUS) <NEW_LINE> data = self.get_point(record) <NEW_LINE> write_api.write(self.bucket, self.org, data)
Emit a record. Send the record to the Web server as line protocol
625941c5adb09d7d5db6c786
def search_advanced(self): <NEW_LINE> <INDENT> self.form = my_forms.AdvancedSearchForm(self.request.GET) <NEW_LINE> if self.form.is_valid(): <NEW_LINE> <INDENT> and_list = [] <NEW_LINE> if 'search_name' in self.request.GET: <NEW_LINE> <INDENT> name = self.request.GET['search_name'].strip() <NEW_LINE> if len(name) > 0: ...
Constructs a raw PyMongo query dictionary from the get data, joining the filters for each feild together with an $and operator. Sets self.search_list to the models.Experiments queried by this dictionary :return:
625941c5a219f33f34628961
def _swipe_right(board, tile=0): <NEW_LINE> <INDENT> return _reverse(_swipe_left(_reverse(board), tile))
Perform what happens at board level when you swipe right Based on _swipe_left
625941c5d7e4931a7ee9df12
def list_by_resource_group( self, resource_group_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Mi...
Returns all the resources of a particular type belonging to a resource group. :param resource_group_name: The name of the resource group within the user's subscription. :type resource_group_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alo...
625941c54d74a7450ccd41b9
def _make_dict_rec(self, name_list, rec): <NEW_LINE> <INDENT> r = {} <NEW_LINE> for i in range(0, len(name_list)): <NEW_LINE> <INDENT> r[name_list[i]] = rec[i] <NEW_LINE> <DEDENT> return r
辞書型のレコードを作成 @param name_list カラム名一覧 @param rec レコードの配列
625941c5cc0a2c11143dce86
def _GetCredentials(): <NEW_LINE> <INDENT> return service_account.Credentials.from_service_account_file( KEY_FILE, scopes=_SCOPES)
Steps through Service Account OAuth 2.0 flow to retrieve credentials.
625941c557b8e32f5248348f
def OneDScan(init, final, steps): <NEW_LINE> <INDENT> if len(init) != len(final): <NEW_LINE> <INDENT> raise RuntimeError("init and final must have the same length") <NEW_LINE> <DEDENT> Answer = [] <NEW_LINE> for j in range(len(init)): <NEW_LINE> <INDENT> Answer.append(np.linspace(init[j], final[j], steps)) <NEW_LINE> <...
Return a list of N equally spaced values between initial and final. This method works with lists of numbers Parameters ---------- init : list List of numbers to be interpolated final : np.ndarray or list List of final numbers, must have same shape as "init" steps : int Number of interpolation steps Return...
625941c544b2445a3393208c
def get_archives(self, offset=None, count=None, session_id=None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if offset is not None: <NEW_LINE> <INDENT> params["offset"] = offset <NEW_LINE> <DEDENT> if count is not None: <NEW_LINE> <INDENT> params["count"] = count <NEW_LINE> <DEDENT> if session_id is not None: <NEW_LINE...
Returns an ArchiveList, which is an array of archives that are completed and in-progress, for your API key. :param int: offset Optional. The index offset of the first archive. 0 is offset of the most recently started archive. 1 is the offset of the archive that started prior to the most recent archive. If you do n...
625941c5287bf620b61d3a5a
def reset(self): <NEW_LINE> <INDENT> self.digital_write(self.reset_pin, GPIO.LOW) <NEW_LINE> self.delay_ms(200) <NEW_LINE> self.digital_write(self.reset_pin, GPIO.HIGH) <NEW_LINE> self.delay_ms(200)
@brief: module reset. often used to awaken the module in deep sleep,
625941c550812a4eaa59c319
@patch("pyphi.compute.distance._ces_distance_simple") <NEW_LINE> @patch("pyphi.compute.distance._ces_distance_emd") <NEW_LINE> def test_ces_distance_uses_simple_vs_emd(mock_emd_distance, mock_simple_distance, s): <NEW_LINE> <INDENT> mock_emd_distance.return_value = float() <NEW_LINE> mock_simple_distance.return_value =...
Quick check that we use the correct CES distance function. If the two CESs differ only in that some concepts have moved to the null concept and all other concepts are the same then we use the simple CES distance. Otherwise, use the EMD.
625941c55e10d32532c5ef1c
def parse_link_descriptor(self, descriptor): <NEW_LINE> <INDENT> optional_attributes = {} <NEW_LINE> link_components = descriptor.split(":{", 1) <NEW_LINE> device = link_components[0] <NEW_LINE> if (len(link_components) == 2 and link_components[1].endswith("}")): <NEW_LINE> <INDENT> some_json = "{" + link_components[1]...
parse e.g. 'udpin:127.0.0.1:9877:{"foo":"bar"}' into python structure ("udpin:127.0.0.1:9877", {"foo":"bar"})
625941c5e8904600ed9f1f20
def write_log(r_info, r_settings, f_name): <NEW_LINE> <INDENT> if r_info['code'] == '404': <NEW_LINE> <INDENT> stats['urls checked'] += 1 <NEW_LINE> can_write = True <NEW_LINE> <DEDENT> elif r_info['err'] == '1' and r_settings['report_errors']: <NEW_LINE> <INDENT> stats['errors'] += 1 <NEW_LINE> can_write = True <NEW_L...
Logs selected data to the 404 report
625941c5711fe17d82542364
def remove_duplicates_without_buffer(self, k): <NEW_LINE> <INDENT> current =self.head <NEW_LINE> while current is not None: <NEW_LINE> <INDENT> runner = current <NEW_LINE> while runner.next is not None: <NEW_LINE> <INDENT> if runner.next.data == current.data: <NEW_LINE> <INDENT> runner.next = runner.next.next <NEW_LINE...
O(n^2) :return:
625941c591af0d3eaac9ba0d
def plot_junction(eptm, edge_index, coords=["x", "y"]): <NEW_LINE> <INDENT> v10, v11 = eptm.edge_df.loc[edge_index, ["srce", "trgt"]] <NEW_LINE> fig, ax = plt.subplots() <NEW_LINE> ax.scatter(*eptm.vert_df.loc[[v10, v11], coords].values.T, marker="+", s=300) <NEW_LINE> v10_out = set(eptm.edge_df[eptm.edge_df["srce"] ==...
Plots local graph around a junction, for debugging purposes.
625941c5498bea3a759b9aa5
def makeJPsi2eMu(name, myconfig): <NEW_LINE> <INDENT> JPsi2eMu = CombineParticles( DecayDescriptors = ["[J/psi(1S) -> e+ mu-]cc","[J/psi(1S) -> e+ mu+]cc"], DaughtersCuts = { "mu+" : "(MIPCHI2DV(PRIMARY)> {min_MIPCHI2DV}) & (TRCHI2DOF < {max_TRCHI2DV}) & (TRGHOSTPROB< {max_TRGHOSTPROB})".format(**myconfig) , "e+" : "(...
Please contact Johannes Albrecht if you think of prescaling this line! Arguments: name : name of the Selection.
625941c5507cdc57c6306ccd
def summarise_stat(stat): <NEW_LINE> <INDENT> pet_names = [ "sweet pea", "human", "fellow", "angel", "colleague", "boiii", "friend", "individual", "person", "muffin", "amiga/amigo", "inspiration", "acquaintance", ] <NEW_LINE> ratio = stat["good_days"] / stat["total_days"] <NEW_LINE> return ( f'{stat["name"]} my {random...
Return an English paragraph summarising the monthly stat for a user
625941c5a05bb46b383ec819
def confirm_sell(self, keys, current_time): <NEW_LINE> <INDENT> dialogue = ['Are you sure?'] <NEW_LINE> choices = ['Yes', 'No'] <NEW_LINE> self.dialogue_box = self.make_dialogue_box(dialogue, 0) <NEW_LINE> self.selection_box = self.make_selection_box(choices) <NEW_LINE> self.selection_arrow.rect.topleft = self.two_arro...
Confirm player wants to sell item.
625941c5d7e4931a7ee9df13
def max_filter(img, filter_dim): <NEW_LINE> <INDENT> img_h, img_w=img.shape <NEW_LINE> for i in range(img_h-filter_dim+1): <NEW_LINE> <INDENT> for j in range(img_w-filter_dim+1): <NEW_LINE> <INDENT> max_value=0 <NEW_LINE> for i_i in range(filter_dim): <NEW_LINE> <INDENT> for j_j in range(filter_dim): <NEW_LINE> <INDENT...
this function sets the pixel value as the max value of the pixels around.
625941c5187af65679ca5114
def stationLocation(self, *args): <NEW_LINE> <INDENT> return _Client.Inventory_stationLocation(self, *args)
stationLocation(self, string networkCode, string stationCode, Time arg2) -> StationLocation
625941c538b623060ff0ade3
def get_predictor(self, n): <NEW_LINE> <INDENT> l = len(self.predictors) <NEW_LINE> if n >= l: <NEW_LINE> <INDENT> logger.warn("n > #towers, will assign predictor to GPU by round-robin") <NEW_LINE> <DEDENT> return [self.predictors[k % l] for k in range(n)]
Returns: PredictorBase: the nth predictor on the nth tower.
625941c58c0ade5d55d3e9af
def hangman(secretWord): <NEW_LINE> <INDENT> print('Welcome to the game Hangman!') <NEW_LINE> print('I am thinking of a word that is', len(secretWord), 'letters long') <NEW_LINE> guesses = 8 <NEW_LINE> lettersGuessed = [] <NEW_LINE> win = False <NEW_LINE> while guesses > 0: <NEW_LINE> <INDENT> print('-----------') <NEW...
secretWord: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secretWord contains. * Ask the user to supply one guess (i.e. letter) per round. * The user should receive feedback immediately after each guess about whet...
625941c5d10714528d5ffcd7
def train(self, xs, ys): <NEW_LINE> <INDENT> memory, src_masks = self.encode(xs) <NEW_LINE> logits, y = self.decode(ys, memory, src_masks) <NEW_LINE> ce = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y) <NEW_LINE> loss = tf.reduce_mean(ce) <NEW_LINE> global_step = tf.train.get_or_create_global_step(...
Returns loss: scalar. train_op: training operation global_step: scalar. summaries: training summary node
625941c5d164cc6175782d43
def transaction(self): <NEW_LINE> <INDENT> if dnfpluginsextras.is_erasing(self.base.transaction, "tracer"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.base.conf.installroot != "/": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not len(self.base.transaction): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT...
Call after successful transaction See https://rpm-software-management.github.io/dnf/api_transaction.html
625941c5956e5f7376d70e64
def _cancel_team_workflow(self, team_submission_uuid, comments, requesting_user_id=None): <NEW_LINE> <INDENT> from openassessment.workflow import team_api as team_workflow_api <NEW_LINE> try: <NEW_LINE> <INDENT> if requesting_user_id is None: <NEW_LINE> <INDENT> requesting_user_id = self.get_student_item_dict()["studen...
Internal helper method to cancel a team workflow using the team workflow API. If requesting_user is not provided, we will use the user to which this xblock is currently bound.
625941c50a366e3fb873e80f
def _make_dir(self): <NEW_LINE> <INDENT> hyper_name = self.uid + "_" + self.args.model_name <NEW_LINE> out_dir = "./{}/{}/{}/{}".format( self.args.log_dir, self.args.dataset, self.args.model_name, self.uid ) <NEW_LINE> try: <NEW_LINE> <INDENT> os.makedirs(out_dir) <NEW_LINE> <DEDENT> except OSError as exc: <NEW_LINE> <...
Make out directory for log file and saving models
625941c5baa26c4b54cb1117
def use_template(self, name, values): <NEW_LINE> <INDENT> self._intf._get_entry_point() <NEW_LINE> bundle = self.get_template(name, True) % values <NEW_LINE> _query = query_from_xml(bundle) <NEW_LINE> bundle = build_search_document(_query['row'], _query['columns'], _query['constraints'] ) <NEW_LINE> content = self._int...
Performs a search query using a previously saved template. Parameters ---------- name: string Name of the template. values: dict Values to put in the template, get the valid keys using the get_template method. Examples -------- >>> interface.manage.search.use_template(name, {'subject_id':'ID...
625941c54f88993c3716c05e
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, JDBCAutoDiscoveryMethod): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c5ab23a570cc250177
def StudentIsExist(self, sno): <NEW_LINE> <INDENT> flag = self._DBHelper.fetchone( "select * from main.students where sno=%s" % sno) <NEW_LINE> if flag: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
查询是否存在当前个人学号信息,存在为True 不存在返回False
625941c5b830903b967e9902