code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def pop(self): <NEW_LINE> <INDENT> self.min_values.pop(-1) <NEW_LINE> return self.stack.pop(-1)
:rtype: nothing
625941be097d151d1a222d80
def readS32LE(self, register): <NEW_LINE> <INDENT> return unpack("<l",self._bus.readfrom_mem(self._address, register, 4))[0]
Read a signed 32-bit value from the specified register, in little endian byte order.
625941be63f4b57ef0001044
def semiperimeter(side1, side2, side3): <NEW_LINE> <INDENT> return perimeter(side1, side2, side3) / 2
(number, number, nummber) -> float Return the semiperimeter of a triangle with sides of length side1, side2, side3. >>>semiperimter(3, 4, 5) 6.0 >>>semiperimeter(10.5, 6, 9.3) 12.9
625941beec188e330fd5a6c8
def search_customer(customer_id): <NEW_LINE> <INDENT> found_customer_dict = {} <NEW_LINE> try: <NEW_LINE> <INDENT> found_customer = Customer.get(Customer.customer_id == customer_id) <NEW_LINE> if found_customer: <NEW_LINE> <INDENT> found_customer_dict = {'first_name': found_customer.first_name, 'last_name': found_customer.last_name, 'email_address': found_customer.email_address, 'phone_number': found_customer.phone_number } <NEW_LINE> <DEDENT> logging.info(f'customer exist and {found_customer_dict}') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.info(f'Customer not found and see how the database protects our data and look the error, \n {e}') <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> logger.info(f'Finally database closes ') <NEW_LINE> <DEDENT> return found_customer_dict
This function will return a dictionary object with first name, last name, email address and phone number of a customer or an empty dictionary object if no customer was found. :param customer_id: :return: dictionary object with name, lastname, email address and phone number of a customer
625941bed268445f265b4d93
def _combineFrame(self, other, func, axis='items'): <NEW_LINE> <INDENT> wide = self.toWide() <NEW_LINE> result = wide._combineFrame(other, func, axis=axis) <NEW_LINE> return result.toLong()
Arithmetic op Parameters ---------- other : DataFrame func : function axis : int / string Returns ------- y : LongPanel
625941be956e5f7376d70d93
def _value_from_raw_attribute_value(raw_attribute_value): <NEW_LINE> <INDENT> value_match = ATTRIBUTE_VALUE_RE.match(raw_attribute_value) <NEW_LINE> if not value_match: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> group_dict = value_match.groupdict() <NEW_LINE> for k, v in group_dict.items(): <NEW_LINE> <INDENT> if v is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if k == 'resolution': <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> elif k == 'enumerated': <NEW_LINE> <INDENT> return AttributeListEnum(v) <NEW_LINE> <DEDENT> elif k == 'hexcidecimal': <NEW_LINE> <INDENT> return int(group_dict['hex_value'], base=16) <NEW_LINE> <DEDENT> elif k == 'floating_point': <NEW_LINE> <INDENT> return float(v) <NEW_LINE> <DEDENT> elif k == 'decimal': <NEW_LINE> <INDENT> return int(v) <NEW_LINE> <DEDENT> elif k == 'string': <NEW_LINE> <INDENT> string_value = group_dict['string_value'] <NEW_LINE> return string_value <NEW_LINE> <DEDENT> <DEDENT> return None
Takes in a raw AttributeValue and returns an appopritate Python type. If there is a problem decoding the value, None is returned.
625941be2c8b7c6e89b356e6
def set_all_lights_floor_off(self, floor): <NEW_LINE> <INDENT> self.__master_communicator.do_command(master_api.basic_action(), {"action_type" : master_api.BA_LIGHTS_OFF_FLOOR, "action_number" : floor}) <NEW_LINE> return dict()
Turn all lights on a given floor off. :returns: empty dict.
625941bebde94217f3682d18
def render_value(self): <NEW_LINE> <INDENT> return self.field.getAccessor(self.context)()
Compute the rendering of the display value. To override for each different type of ATFieldRenderer.
625941bec4546d3d9de72956
def SaveDocument(self, saveAsPath): <NEW_LINE> <INDENT> return super(IApplication, self).SaveDocument(saveAsPath)
Method IApplication.SaveDocument INPUT saveAsPath : BSTR
625941be15fb5d323cde0a30
def merge_data(gunlawCounts_perStateYearDict, massshootingCounts_perStateYearDict): <NEW_LINE> <INDENT> count_xy = [] <NEW_LINE> for key in gunlawCounts_perStateYearDict: <NEW_LINE> <INDENT> count_xy.append([gunlawCounts_perStateYearDict[key], massshootingCounts_perStateYearDict[key]]) <NEW_LINE> <DEDENT> return np.array(count_xy)
Merges two dictionarys into one by state_year key, value from two dictionarys become a list of counts. The first is gun law counts and the second is mass shooting counts
625941be4a966d76dd550f31
def test_dequeue_head_is_tail_with_one_node(): <NEW_LINE> <INDENT> from queue import Queue <NEW_LINE> queue = Queue() <NEW_LINE> queue.enqueue(25) <NEW_LINE> queue.enqueue(20) <NEW_LINE> queue.dequeue() <NEW_LINE> assert queue._dll.tail == queue._dll.head
Test if head and tail are the same.
625941be8a43f66fc4b53f8c
def parse_trnascan(trnascan_file, identifiers): <NEW_LINE> <INDENT> data = file_io.read_file(trnascan_file) <NEW_LINE> lines = data.split("\n") <NEW_LINE> header = True <NEW_LINE> meta = {"file": trnascan_file} <NEW_LINE> results = defaultdict(list) <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if header: <NEW_LINE> <INDENT> row = re.split(" +", line) <NEW_LINE> if len(row) > 1: <NEW_LINE> <INDENT> if row[1].startswith("v."): <NEW_LINE> <INDENT> meta.update({"version": row[1]}) <NEW_LINE> <DEDENT> elif row[1] == "Mode:": <NEW_LINE> <INDENT> meta.update({"mode": row[2]}) <NEW_LINE> meta.update({"field_id": "trnascan_%s" % row[2].lower()}) <NEW_LINE> <DEDENT> elif row[1].startswith("------"): <NEW_LINE> <INDENT> header = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> row = re.split(r" +|\t", line) <NEW_LINE> if len(row) == 9: <NEW_LINE> <INDENT> results[row[0]].append([row[4], row[5]]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not identifiers.validate_list(list(results.keys())): <NEW_LINE> <INDENT> raise UserWarning( "Contig names in the tRNAScan file did not match dataset identifiers." ) <NEW_LINE> <DEDENT> values = [results[id] if id in results else [] for id in identifiers.values] <NEW_LINE> trnascan_field = MultiArray( meta["field_id"], values=values, meta=meta, headers=("tRNA_type", "Anticodon"), parents=["children"], ) <NEW_LINE> return trnascan_field
Parse tRNAscan results into a MultiArray.
625941be8e71fb1e9831d6cf
def __get_blob_direct(self, base_tree, filename): <NEW_LINE> <INDENT> for blob in base_tree.blobs: <NEW_LINE> <INDENT> if blob.name == filename: <NEW_LINE> <INDENT> return blob <NEW_LINE> <DEDENT> <DEDENT> return None
Return the tree of the given file (blob). This does not walk down the directory structure. It just checks the current hierarchy.
625941be30bbd722463cbce8
def html_list_to_english(L, with_period=False): <NEW_LINE> <INDENT> if len(L) == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> elif len(L) == 1: <NEW_LINE> <INDENT> res = L <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = [] <NEW_LINE> for el in L[:-1]: <NEW_LINE> <INDENT> res.append(el) <NEW_LINE> res.append(", ") <NEW_LINE> <DEDENT> if res: <NEW_LINE> <INDENT> res.pop() <NEW_LINE> <DEDENT> res.append(" and ") <NEW_LINE> res.append(L[-1]) <NEW_LINE> <DEDENT> if with_period: <NEW_LINE> <INDENT> res.append('.') <NEW_LINE> <DEDENT> return res
Convert a list into a string separated by commas and "and"
625941be6fece00bbac2d661
def test_hidden(): <NEW_LINE> <INDENT> assert len(filter_hidden(users[:])) is 2 <NEW_LINE> assert len(filter_hidden(devices[:])) is 1
Should filter out hidden entities :return:
625941be090684286d50ec07
def resolve_links(self): <NEW_LINE> <INDENT> for alias, target in list(self.links.items()): <NEW_LINE> <INDENT> if isinstance(target, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> target = self.formation[target] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> del self.links[alias] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.links[alias] = target <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(target, ContainerInstance): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid link value {}".format(repr(target)))
Resolves any links that are still names to instances from the formation
625941be91af0d3eaac9b93a
def read_data(self, subdatablock): <NEW_LINE> <INDENT> beams = self.header['Beams'] <NEW_LINE> data = np.frombuffer(subdatablock, dtype=Data7018.data_dtype) <NEW_LINE> self.mag = data['Amp'].astype('f') <NEW_LINE> self.mag.shape = (-1, beams) <NEW_LINE> self.phase = data['Phs'].astype('f') <NEW_LINE> self.phase.shape = (-1, beams)
Read the data into a numpy array.
625941be498bea3a759b99d4
def __init__(self, action: Action): <NEW_LINE> <INDENT> PgNode.__init__(self) <NEW_LINE> self.action = action <NEW_LINE> self.prenodes = self.precond_s_nodes() <NEW_LINE> self.effnodes = self.effect_s_nodes() <NEW_LINE> self.is_persistent = self.prenodes == self.effnodes <NEW_LINE> self.__hash = None
A-level Planning Graph node constructor :param action: Action. a ground action, i.e. this action cannot contain any variables Instance variables calculated: An A-level will always have an S-level as its parent and an S-level as its child. The preconditions and effects will become the parents and children of the A-level node. However, when this node is created, it is not yet connected to the graph. prenodes: set of *possible* parent S-nodes effnodes: set of *possible* child S-nodes is_persistent: bool True if this is a persistence action, i.e. a no-op action Instance variables inherited from PgNode. All are initially empty: parents: set of nodes connected to this node in previous S level; children: set of nodes connected to this node in next S level; mutex: set of sibling A-nodes that node has mutual exclusion with;
625941be7047854f462a1331
def get_token(self): <NEW_LINE> <INDENT> if not self._token_q.empty(): <NEW_LINE> <INDENT> self.token = self._token_q.get(False) <NEW_LINE> <DEDENT> return self.token
Get current token (if any)
625941bed6c5a10208143f6d
@cachier() <NEW_LINE> def _test_single_file_speed(int_1, int_2): <NEW_LINE> <INDENT> return [random() for _ in range(1000000)]
Add the two given ints.
625941bef7d966606f6a9f26
def tearDown(self): <NEW_LINE> <INDENT> del self.shoplist
delete object
625941becdde0d52a9e52f55
def init(self, parent): <NEW_LINE> <INDENT> TextEditor.init(self, parent) <NEW_LINE> self.evaluate = self.factory.evaluate <NEW_LINE> self.sync_value(self.factory.evaluate_name, 'evaluate', 'from')
Finishes initializing the editor by creating the underlying toolkit widget.
625941be63b5f9789fde7009
def expose(func=None, alias=None): <NEW_LINE> <INDENT> def expose_(func): <NEW_LINE> <INDENT> func.exposed = True <NEW_LINE> if alias is not None: <NEW_LINE> <INDENT> if isinstance(alias, basestring): <NEW_LINE> <INDENT> parents[alias.replace(".", "_")] = func <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for a in alias: <NEW_LINE> <INDENT> parents[a.replace(".", "_")] = func <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return func <NEW_LINE> <DEDENT> import sys, types <NEW_LINE> if isinstance(func, (types.FunctionType, types.MethodType)): <NEW_LINE> <INDENT> if alias is None: <NEW_LINE> <INDENT> func.exposed = True <NEW_LINE> return func <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parents = sys._getframe(1).f_locals <NEW_LINE> return expose_(func) <NEW_LINE> <DEDENT> <DEDENT> elif func is None: <NEW_LINE> <INDENT> if alias is None: <NEW_LINE> <INDENT> parents = sys._getframe(1).f_locals <NEW_LINE> return expose_ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parents = sys._getframe(1).f_locals <NEW_LINE> return expose_ <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> parents = sys._getframe(1).f_locals <NEW_LINE> alias = func <NEW_LINE> return expose_
Expose the function, optionally providing an alias or set of aliases.
625941be3617ad0b5ed67e1d
def remove_old_graphs(self): <NEW_LINE> <INDENT> print("\t:: Removing old graphs") <NEW_LINE> for file in os.listdir(self.path): <NEW_LINE> <INDENT> os.remove(self.path + "/" + file)
This function removes the old graphics from the graphs directory.
625941be85dfad0860c3ad7e
def read_telemetrystatus(path_name): <NEW_LINE> <INDENT> data=pd.read_csv(path_name) <NEW_LINE> for i in range(len(data['vessel (use underscores)'])): <NEW_LINE> <INDENT> if data['vessel (use underscores)'].isnull()[i]: <NEW_LINE> <INDENT> data_line_number=i <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> telemetrystatus_df=pd.read_csv(path_name,nrows=data_line_number) <NEW_LINE> as_list=telemetrystatus_df.columns.tolist() <NEW_LINE> idex=as_list.index('vessel (use underscores)') <NEW_LINE> as_list[idex]='Boat' <NEW_LINE> telemetrystatus_df.columns=as_list <NEW_LINE> for i in range(len(telemetrystatus_df)): <NEW_LINE> <INDENT> telemetrystatus_df['Boat'][i]=telemetrystatus_df['Boat'][i].replace("'","") <NEW_LINE> if not telemetrystatus_df['Lowell-SN'].isnull()[i]: <NEW_LINE> <INDENT> telemetrystatus_df['Lowell-SN'][i]=telemetrystatus_df['Lowell-SN'][i].replace(',',',') <NEW_LINE> <DEDENT> if not telemetrystatus_df['logger_change'].isnull()[i]: <NEW_LINE> <INDENT> telemetrystatus_df['logger_change'][i]=telemetrystatus_df['logger_change'][i].replace(',',',') <NEW_LINE> <DEDENT> <DEDENT> return telemetrystatus_df
read the telementry_status, then return the useful data input: path_name: thestring that include telemetry status file path and name.
625941be07f4c71912b113a5
def lat_lng(coordinates): <NEW_LINE> <INDENT> if coordinates != (0, 0): <NEW_LINE> <INDENT> lat = round(coordinates[0],5) <NEW_LINE> lng = round(coordinates[1],5) <NEW_LINE> return (lat,lng) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (0,0)
Add error of ~100m to lat_lng coordinates by removing dec. points Arg: Tuple of lat_lng outputted from nominatim geolocation Returns: Tuple of floats with truncated lat_lng
625941be24f1403a92600a8d
def downstream_thread(self): <NEW_LINE> <INDENT> actual_stream = self.connection.streams[self.downstream_id] <NEW_LINE> while not self.thread_stop_event.is_set(): <NEW_LINE> <INDENT> if len(actual_stream.data) > 1: <NEW_LINE> <INDENT> new_data, actual_stream.data = read_from_downstream(self.downstream_boundary, actual_stream.data) <NEW_LINE> if len(new_data) > 0: <NEW_LINE> <INDENT> message = parse_data(new_data, self.downstream_boundary) <NEW_LINE> self.process_response_handle(message) <NEW_LINE> <DEDENT> <DEDENT> time.sleep(0.5)
Downstream channel thread, which continuously monitors the stream for new data. Data is automatically parsed when an entire message is recieved.
625941be91af0d3eaac9b93b
def p_expr_ident(self, p): <NEW_LINE> <INDENT> p[0] = self._new_name(p, p[1])
ident : IDENT
625941be4f6381625f114962
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if not kwargs.get('no_django', False): <NEW_LINE> <INDENT> kwargs['lookup'] = edxmako.LOOKUP['main'] <NEW_LINE> <DEDENT> super(Template, self).__init__(*args, **kwargs)
Overrides base __init__ to provide django variable overrides
625941be4f6381625f114961
def signup_administrator(request): <NEW_LINE> <INDENT> registered = False <NEW_LINE> organization_list = get_organizations_ordered_by_name() <NEW_LINE> if organization_list: <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> user_form = UserForm(request.POST, prefix="usr") <NEW_LINE> administrator_form = AdministratorForm(request.POST, prefix="admin") <NEW_LINE> if user_form.is_valid() and administrator_form.is_valid(): <NEW_LINE> <INDENT> user = user_form.save() <NEW_LINE> user.set_password(user.password) <NEW_LINE> user.save() <NEW_LINE> administrator = administrator_form.save(commit=False) <NEW_LINE> administrator.user = user <NEW_LINE> organization_id = request.POST.get('organization_name') <NEW_LINE> organization = get_organization_by_id(organization_id) <NEW_LINE> if organization: <NEW_LINE> <INDENT> administrator.organization = organization <NEW_LINE> <DEDENT> administrator.save() <NEW_LINE> registered = True <NEW_LINE> messages.success(request, 'You have successfully registered!') <NEW_LINE> return HttpResponseRedirect(reverse('home:index')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(user_form.errors, administrator_form.errors) <NEW_LINE> return render(request, 'registration/signup_administrator.html', {'user_form': user_form, 'administrator_form': administrator_form, 'registered': registered, 'organization_list': organization_list, }) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> user_form = UserForm(prefix="usr") <NEW_LINE> administrator_form = AdministratorForm(prefix="admin") <NEW_LINE> <DEDENT> return render(request, 'registration/signup_administrator.html', {'user_form': user_form, 'administrator_form': administrator_form, 'registered': registered, 'organization_list': organization_list, }) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return render(request, 'organization/add_organizations.html')
This method is responsible for diplaying the register user view Register Admin or volunteer is judged on the basis of users access rights. Only if user is registered and logged in and registered as an admin user, he/she is allowed to register others as an admin user
625941be1b99ca400220a9d5
def xor_integers_in_bounds(n_neg, n_pos): <NEW_LINE> <INDENT> points = np.mgrid[n_neg:n_pos, n_neg:n_pos] <NEW_LINE> x = points[0].flatten() <NEW_LINE> y = points[1].flatten() <NEW_LINE> return x, y, np.bitwise_xor(x, y)
All points in 2-dimensional range x = [n_neg, n_pos-1] and y = [n_neg, n_pos-1] are selected from specified range. Bitwise xor is applied pointwise and the results returned. Args: n_neg: The negative bound n_pos: The positive bound Returns: x: The x coords in range [n_neg, n_pos] y: The y coords in range [n_neg, n_pos] pointwise bitwise xor
625941be0fa83653e4656ee1
@sensitive_post_parameters() <NEW_LINE> @csrf_protect <NEW_LINE> @never_cache <NEW_LINE> def login(request, gym, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=GymAuthForm, current_app=None, extra_context=None): <NEW_LINE> <INDENT> gym = get_object_or_404(Gym, slug=gym) <NEW_LINE> redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> form = authentication_form(request, data=request.POST, gym=gym) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> if not is_safe_url(url=redirect_to, host=request.get_host()): <NEW_LINE> <INDENT> redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) <NEW_LINE> <DEDENT> auth_login(request, form.get_user()) <NEW_LINE> return HttpResponseRedirect(redirect_to) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> form = authentication_form(request) <NEW_LINE> <DEDENT> current_site = get_current_site(request) <NEW_LINE> context = { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, 'gym': gym, } <NEW_LINE> if extra_context is not None: <NEW_LINE> <INDENT> context.update(extra_context) <NEW_LINE> <DEDENT> return TemplateResponse(request, template_name, context, current_app=current_app)
Displays the login form and handles the login action.
625941be377c676e912720ce
def GetRMSChange(self): <NEW_LINE> <INDENT> return _itkScalarChanAndVeseDenseLevelSetImageFilterPython.itkScalarChanAndVeseDenseLevelSetImageFilterID3ID3ID3_Superclass_Superclass_GetRMSChange(self)
GetRMSChange(self) -> double
625941beb545ff76a8913d3b
def test_aliveness3(self): <NEW_LINE> <INDENT> t = stackless.tasklet(runtask)() <NEW_LINE> t.set_ignore_nesting(1) <NEW_LINE> self.assert_(t.alive) <NEW_LINE> self.assert_(t.scheduled) <NEW_LINE> self.assertEquals(t.recursion_depth, 0) <NEW_LINE> softSwitching = is_soft() <NEW_LINE> res = stackless.run(100) <NEW_LINE> self.assertEquals(t, res) <NEW_LINE> self.assert_(t.alive) <NEW_LINE> self.assert_(t.paused) <NEW_LINE> self.assertFalse(t.scheduled) <NEW_LINE> self.assertEquals(t.recursion_depth, softSwitching and 1 or 2) <NEW_LINE> dumped = pickle.dumps(t) <NEW_LINE> t_new = pickle.loads(dumped) <NEW_LINE> t.remove() <NEW_LINE> t = t_new <NEW_LINE> del t_new <NEW_LINE> t.insert() <NEW_LINE> self.assert_(t.alive) <NEW_LINE> self.assertFalse(t.paused) <NEW_LINE> self.assert_(t.scheduled) <NEW_LINE> self.assertEquals(t.recursion_depth, 1) <NEW_LINE> if is_soft(): <NEW_LINE> <INDENT> stackless.run() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t.kill() <NEW_LINE> <DEDENT> self.assertFalse(t.alive) <NEW_LINE> self.assertFalse(t.scheduled) <NEW_LINE> self.assertEquals(t.recursion_depth, 0)
Same as 1, but with a pickled run(slightly) tasklet.
625941bebaa26c4b54cb1047
def __new__(cls, *args, **kargs): <NEW_LINE> <INDENT> if not cls.instance: <NEW_LINE> <INDENT> cls.instance = dict.__new__(cls, *args, **kargs) <NEW_LINE> <DEDENT> return cls.instance
Maintain only a single instance of this object @return: instance of this class
625941be16aa5153ce36239d
def findFrequentTreeSum(self, root): <NEW_LINE> <INDENT> dict = {} <NEW_LINE> result = [] <NEW_LINE> def search(node): <NEW_LINE> <INDENT> if not node: <NEW_LINE> <INDENT> return "0" <NEW_LINE> <DEDENT> treeSum = node.val + int(search(node.left)) + int(search(node.right)) <NEW_LINE> if treeSum in dict: <NEW_LINE> <INDENT> if dict[treeSum] == 1: <NEW_LINE> <INDENT> result.append(treeSum) <NEW_LINE> dict[treeSum] = 2 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> dict[treeSum] = 1 <NEW_LINE> <DEDENT> return treeSum <NEW_LINE> <DEDENT> search(root) <NEW_LINE> return result
:type root: TreeNode :rtype: List[int]
625941be1f037a2d8b946124
def stop_instance(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.stop_instance_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.stop_instance_with_http_info(id, **kwargs) <NEW_LINE> return data
Stops the given VDU. Stops the VDU with the given ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.stop_instance(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: ID of VDU (required) :return: None If the method is called asynchronously, returns the request thread.
625941be96565a6dacc8f5f1
def query_reports_by_user_id(user_id): <NEW_LINE> <INDENT> jobs = query_jobs_by_user_id(user_id) <NEW_LINE> job_ids = map(lambda x: x['id'], jobs) <NEW_LINE> result = query_reports_by_job_ids(job_ids) <NEW_LINE> return result
just like the function name :param user_id: id of the user :return: all of reports for a specific user
625941be38b623060ff0ad14
def consCode_number(token): <NEW_LINE> <INDENT> return HIDId('ConsCode', token.value, token.locale)
Consumer Control HID Code lookup
625941be566aa707497f4492
def btnStopClicked(self): <NEW_LINE> <INDENT> Map.elHght_72, Map.elWdth_72 = width_stop <NEW_LINE> Map.elHght_54, Map.elWdth_54 = width_stop <NEW_LINE> Map.elHght_32, Map.elWdth_32 = width_stop <NEW_LINE> Map.elHght_11, Map.elWdth_11 = width_stop <NEW_LINE> Map.elHght_3, Map.elWdth_3 = width_stop <NEW_LINE> Map.elHght_2, Map.elWdth_2 = width_stop <NEW_LINE> Map.elCntH, Map.elCntW = width_stop <NEW_LINE> print("Button Stop pressed")
Function for button Stop Changes size of bluetooth zone to 0
625941bec432627299f04b69
def boolize(data): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if REX_BOOL_TRUE.match(data): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if REX_BOOL_FALSE.match(data): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> raise ValueError('Cannot convert input option "%s" to bool' % data)
Conver input values from string to bool if possible :param data: input data from argparse :type data: str :return: converted boolean value, or None if not specified :rtype: bool or None :raises ValueError: if conversion failed
625941be21bff66bcd68487a
def _set_fitting_scale(self, available_width, available_height): <NEW_LINE> <INDENT> if self._source_surface is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> matrix = self._get_rotated_matrix() <NEW_LINE> source_width, source_height, _, _ = self._get_surface_extents(matrix, self._source_surface) <NEW_LINE> try: <NEW_LINE> <INDENT> aspect_ratio = source_width / source_height <NEW_LINE> available_aspect_ratio = available_width / available_height <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> self._set_scale(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if aspect_ratio > available_aspect_ratio: <NEW_LINE> <INDENT> self._set_scale(available_width / source_width) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._set_scale(available_height / source_height)
set the scale to a value that makes the image fit exactly into available_width and available_height
625941be8c3a8732951582dd
def extract_labels(filename, num_images): <NEW_LINE> <INDENT> print('Extracting', filename) <NEW_LINE> with gzip.open(filename) as bytestream: <NEW_LINE> <INDENT> bytestream.read(8) <NEW_LINE> buf = bytestream.read(1 * num_images) <NEW_LINE> labels = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.int64) <NEW_LINE> <DEDENT> return dense_to_one_hot(labels, 10)
Extract the labels into a vector of int64 label IDs.
625941be07d97122c41787ab
def cmd(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> cmd, modules = super(RunbotBuild, self).cmd(cr, uid, ids, context=context) <NEW_LINE> for build in self.browse(cr, uid, ids, context=context): <NEW_LINE> <INDENT> if build.lang and build.job == 'job_30_run': <NEW_LINE> <INDENT> cmd.append("--load-language=%s" % (build.lang)) <NEW_LINE> <DEDENT> <DEDENT> return cmd, modules
Return a list describing the command to start the build
625941bee64d504609d74765
def __get__(self, instance, owner): <NEW_LINE> <INDENT> return functools.partial(self.__call__, instance)
Fix problems with instance methods
625941be379a373c97cfaa69
def check_pool_sources(xmlstr): <NEW_LINE> <INDENT> source_val = {} <NEW_LINE> source_cmp = {} <NEW_LINE> doc = minidom.parseString(xmlstr) <NEW_LINE> for diskTag in doc.getElementsByTagName("source"): <NEW_LINE> <INDENT> name_element = diskTag.getElementsByTagName("name")[0] <NEW_LINE> textnode = name_element.childNodes[0] <NEW_LINE> name_val = textnode.data <NEW_LINE> num = len(diskTag.getElementsByTagName("device")) <NEW_LINE> for i in range(0, num): <NEW_LINE> <INDENT> device_element = diskTag.getElementsByTagName("device")[i] <NEW_LINE> attr = device_element.getAttributeNode('path') <NEW_LINE> path_val = attr.nodeValue <NEW_LINE> source_val.update({path_val: name_val, }) <NEW_LINE> <DEDENT> <DEDENT> logger.debug("pool source info dict is: %s" % source_val) <NEW_LINE> cmd = "pvs -q --noheadings -o pv_name,vg_name | awk -F' ' '{print $1}'" <NEW_LINE> ret, path_list = utils.exec_cmd(cmd, shell=True) <NEW_LINE> cmd = "pvs -q --noheadings -o pv_name,vg_name | awk -F' ' '{print $2}'" <NEW_LINE> ret, name_list = utils.exec_cmd(cmd, shell=True) <NEW_LINE> for i in range(len(path_list)): <NEW_LINE> <INDENT> source_cmp.update({path_list[i]: name_list[i]}) <NEW_LINE> <DEDENT> logger.debug("pvs command output dict is: %s" % source_cmp) <NEW_LINE> for key in source_cmp.copy(): <NEW_LINE> <INDENT> if not key.startswith('/dev/') and not key.startswith('[unknown]'): <NEW_LINE> <INDENT> logger.debug("del %s: %s" % (key, source_cmp[key])) <NEW_LINE> del source_cmp[key] <NEW_LINE> <DEDENT> <DEDENT> if source_val == source_cmp: <NEW_LINE> <INDENT> logger.info("source dict match with pvs command output") <NEW_LINE> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error("source dict did not match with pvs command output") <NEW_LINE> return 1
check the logical sources with command: pvs --noheadings -o pv_name,vg_name
625941be63d6d428bbe44415
def go_home(self, bag): <NEW_LINE> <INDENT> if 'position' in bag.stick: <NEW_LINE> <INDENT> dist_home = vector.length(vector.from_to(bag.stick.position, self.HOME_POSITION)) <NEW_LINE> bag.stick.dest_position = self.HOME_POSITION <NEW_LINE> bag.stick.dest_direction = (0, 0) <NEW_LINE> bag.stick.dest_velocity = 0 <NEW_LINE> bag.stick.dest_time = time.time() + dist_home / self.STICK_MAX_SPEED
Starts to move the stick to its home position. :param bag: The parameter bag. :return:
625941be009cb60464c632d9
def vi_c(ind): <NEW_LINE> <INDENT> u = fixed['edges'][ind,0] <NEW_LINE> v = fixed['edges'][ind,1] <NEW_LINE> logp = [] <NEW_LINE> for k in state['cluster_ids']: <NEW_LINE> <INDENT> psi_alpha = psi(vi['h_alpha'][k]) <NEW_LINE> psi_a_k_u = psi(vi['h_a'][k][u]) <NEW_LINE> psi_a_k_un = psi(sum(vi['h_a'][k])) <NEW_LINE> psi_a_k_v = psi(vi['h_b'][k][v]) <NEW_LINE> psi_a_k_vn = psi(sum(vi['h_b'][k])) <NEW_LINE> logpk = psi_alpha + psi_a_k_u - psi_a_k_un + psi_a_k_v - psi_a_k_vn <NEW_LINE> logp += [logpk] <NEW_LINE> <DEDENT> logp = logp - max(logp) <NEW_LINE> p = np.exp(logp) <NEW_LINE> return p / sum(p)
update c_hat given an edge :return:
625941be82261d6c526ab3c1
def assert_returns_menu_item_for_input(self, mock_input_val, expected): <NEW_LINE> <INDENT> with mock_inputs([mock_input_val]): <NEW_LINE> <INDENT> item = menu.get_selected_menu_item() <NEW_LINE> self.assertEqual(item, expected)
:param mock_input_val: What should be returned on the next call to input() :param expected: What we expect menu.get_selected_menu_item() to return for the mock_input_val
625941be15baa723493c3e99
def __load(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.__filename, 'r') as file: <NEW_LINE> <INDENT> lines = file.readlines() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> args = line.split(',') <NEW_LINE> if len(args) == 3: <NEW_LINE> <INDENT> tema = Tema(int(args[0]), args[1], args[2].split('\n')[0]) <NEW_LINE> self.__teme.append(tema) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError("File error")
incarcare teme din fisier
625941be1f5feb6acb0c4a79
def loadItems(self, tree_widget): <NEW_LINE> <INDENT> self.top_items = {} <NEW_LINE> for name in ["Contacts", "Molecules", "Surface Blocks", "Recently Used"]: <NEW_LINE> <INDENT> top_item = QtGui.QTreeWidgetItem(tree_widget) <NEW_LINE> top_item.setText(0, name) <NEW_LINE> top_item.setFlags(top_item.flags() & ~QtCore.Qt.ItemIsDragEnabled & ~QtCore.Qt.ItemIsSelectable) <NEW_LINE> self.top_items[name] = top_item <NEW_LINE> <DEDENT> self.loadContacts() <NEW_LINE> self.loadMolecules() <NEW_LINE> self.loadSurfaceBlocks()
Load all the items to the tree_widget
625941be55399d3f055885d8
def active_offset(self, value=None, validate=False): <NEW_LINE> <INDENT> return self.offset( self.internals["activeimage"]["direction"], self.internals["activeimage"]["season"], self.internals["activeimage"]["frame"], self.internals["activeimage"]["layer"], value, validate, )
Set or get the full offset coordinates for the active image
625941beaad79263cf390963
def __initiate_and_get_trainer(self): <NEW_LINE> <INDENT> return trainers.BackpropTrainer(self.network_module, dataset=self.dataset, momentum=self.momentum, learningrate=self.learning_rate, verbose=self.verbose, weightdecay=self.weight_decay)
Building the back propagation trainer @dataset : The data on which the network is going to train from @momentum : @learning rate : The rate at which the error is going to be reduced (J(theta) getting converged) @verbose : @weightdecay : :return:
625941be97e22403b379cebe
def load_lin(str_filename, int_quanta_fmt): <NEW_LINE> <INDENT> lst_lines = [] <NEW_LINE> with open(str_filename, 'r') as f: <NEW_LINE> <INDENT> for i, str_line in enumerate(f): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj = LinConverter.str2line(str_line, int_quanta_fmt) <NEW_LINE> lst_lines.append(obj) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print('Warning: skipping bad line %i' % (i + 1)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return lst_lines
Read from .cat
625941bebaa26c4b54cb1048
def divided_difference_table(self): <NEW_LINE> <INDENT> if self.check_input() == True: <NEW_LINE> <INDENT> n = self.n <NEW_LINE> x = self.x <NEW_LINE> y = self.y <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> for j in range(n - i): <NEW_LINE> <INDENT> y[j][i] = (y[j + 1][i - 1] - y[j][i - 1]) / (x[i + j] - x[j]) <NEW_LINE> <DEDENT> <DEDENT> self.y = y <NEW_LINE> return "Divided difference table successfully calculated" <NEW_LINE> <DEDENT> return "Error occurred during divide difference table calculation"
Calculate the divided difference table from given set of n values of x and f(x) [y] and stores it in a 2d list i.e. it calculates `[x0,x1], [x0,x1,x2], ...` Returns ------- String Literal
625941befb3f5b602dac35b6
def _divide_with_ceil(a, b): <NEW_LINE> <INDENT> if a % b: <NEW_LINE> <INDENT> return (a // b) + 1 <NEW_LINE> <DEDENT> return a // b
Returns 'a' divided by 'b', with any remainder rounded up.
625941bec4546d3d9de72957
def GetLambda(self): <NEW_LINE> <INDENT> return _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.itkMeanReciprocalSquareDifferenceImageToImageMetricIUS2IUS2_GetLambda(self)
GetLambda(self) -> double
625941bef8510a7c17cf9621
def left_top_coords_of_box(box_x, box_y): <NEW_LINE> <INDENT> left = box_x * (BOX_SIZE + GAP_SIZE) + X_MARGIN <NEW_LINE> top = box_y * (BOX_SIZE + GAP_SIZE) + Y_MARGIN <NEW_LINE> return left, top
Convert board coordinates to pixel coordinates.
625941be167d2b6e31218abc
def shutdown(self): <NEW_LINE> <INDENT> pass
Perform necessary actions to shutdown the ``Exchange`` instance.
625941be5fdd1c0f98dc0158
def ReturnCompleteDatetime(view, date, time='', tz=None): <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> if date=='*': <NEW_LINE> <INDENT> startDelta = timedelta(days=random.randint(0, 300)) <NEW_LINE> closeToNow = datetime(now.year, now.month, now.day) <NEW_LINE> tmp = closeToNow + startDelta <NEW_LINE> <DEDENT> elif not date=='': <NEW_LINE> <INDENT> d = string.split(date,'/') <NEW_LINE> if len(d[2])==2: <NEW_LINE> <INDENT> d[2] = '20'+d[2] <NEW_LINE> <DEDENT> tmp = datetime(month=string.atoi(d[0]),day=string.atoi(d[1]),year=string.atoi(d[2])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tmp = now <NEW_LINE> <DEDENT> if time=='*': <NEW_LINE> <INDENT> result = datetime(year=tmp.year,month=tmp.month,day=tmp.day,hour=random.randint(0, 12),minute=random.randint(0, 59)) <NEW_LINE> <DEDENT> elif not time=='': <NEW_LINE> <INDENT> t = string.split(time,':') <NEW_LINE> if len(t)==2: <NEW_LINE> <INDENT> if t[1][-2:] == 'PM' and not t[0]=='12': <NEW_LINE> <INDENT> h = string.atoi(t[0]) + 12 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> h = string.atoi(t[0]) <NEW_LINE> <DEDENT> result = datetime(year=tmp.year,month=tmp.month,day=tmp.day,hour=h,minute=string.atoi(t[1])) <NEW_LINE> <DEDENT> elif len(t)==3: <NEW_LINE> <INDENT> if t[2][-2:] == 'PM' and not t[0]=='12': <NEW_LINE> <INDENT> h = string.atoi(t[0]) + 12 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> h = string.atoi(t[0]) <NEW_LINE> <DEDENT> result = datetime(year=tmp.year,month=tmp.month,day=tmp.day,hour=h,minute=string.atoi(t[1])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = datetime(year=tmp.year,month=tmp.month,day=tmp.day,hour=now.hour,minute=now.minute) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result = datetime(year=tmp.year,month=tmp.month,day=tmp.day,hour=now.hour,minute=now.minute) <NEW_LINE> <DEDENT> if tz=='*': <NEW_LINE> <INDENT> tzinfo = view.tzinfo.getInstance(random.choice(TIMEZONES)) <NEW_LINE> <DEDENT> elif tz in TIMEZONES: <NEW_LINE> <INDENT> tzinfo = view.tzinfo.getInstance(tz) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tzinfo = view.tzinfo.default <NEW_LINE> <DEDENT> result = datetime(year=result.year,month=result.month,day=result.day,hour=result.hour,minute=result.minute,tzinfo=tzinfo) <NEW_LINE> return result
Return a datetime corresponding to the parameters
625941bed4950a0f3b08c277
def apt_get_installed(self): <NEW_LINE> <INDENT> if self._installed_pkgs is None: <NEW_LINE> <INDENT> self._installed_pkgs = [] <NEW_LINE> for p in self._cache_ubuntu: <NEW_LINE> <INDENT> if p.is_installed: <NEW_LINE> <INDENT> self._installed_pkgs.append(p.name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self._installed_pkgs
get all the installed packages. :return: list of installed list :rtype: list
625941be30bbd722463cbce9
def three_hours_forecast(self, name): <NEW_LINE> <INDENT> assert type(name) is str, "'name' must be a str" <NEW_LINE> json_data = self._httpclient.call_API(THREE_HOURS_FORECAST_URL, {'q': name, 'lang': self._language}) <NEW_LINE> forecast = self._parsers['forecast'].parse_JSON(json_data) <NEW_LINE> if forecast is not None: <NEW_LINE> <INDENT> forecast.set_interval("3h") <NEW_LINE> return forecaster.Forecaster(forecast) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Queries the OWM web API for three hours weather forecast for the specified location (eg: "London,uk"). A *Forecaster* object is returned, containing a *Forecast* instance covering a global streak of five days: this instance encapsulates *Weather* objects, with a time interval of three hours one from each other :param name: the location's toponym :type name: str :returns: a *Forecaster* instance or ``None`` if forecast data is not available for the specified location :raises: *ParseResponseException* when OWM web API responses' data cannot be parsed, *APICallException* when OWM web API can not be reached
625941be3c8af77a43ae36c4
def test_nogrouperror_on_deleting_group(self): <NEW_LINE> <INDENT> self.vv_return['status'] = 'ERROR' <NEW_LINE> self.vv_return['deleting'] = True <NEW_LINE> self.verified_view.return_value = defer.succeed(self.vv_return) <NEW_LINE> d = self.group.view_manifest(with_policies=False, get_deleting=False) <NEW_LINE> self.failureResultOf(d, NoSuchScalingGroupError)
Viewing manifest with `get_deleting=False` on a deleting group raises NoSuchScalingGroupError
625941be63f4b57ef0001045
def test_overridden_ip_exceptions(self): <NEW_LINE> <INDENT> url = '/locked/view/with/ip_exception1/' <NEW_LINE> response = self.client.post(url, REMOTE_ADDR='192.168.0.100', follow=True) <NEW_LINE> self.assertTemplateUsed(response, 'lockdown/form.html') <NEW_LINE> url = '/locked/view/with/ip_exception1/' <NEW_LINE> response = self.client.post(url, REMOTE_ADDR='192.168.0.1', follow=True) <NEW_LINE> self.assertTemplateNotUsed(response, 'lockdown/form.html') <NEW_LINE> self.assertEqual(response.content, self.locked_contents)
Test that locking works with overwritten remote_addr exceptions.
625941becad5886f8bd26f00
def conf_from_file(filepath): <NEW_LINE> <INDENT> abspath = os.path.abspath(os.path.expanduser(filepath)) <NEW_LINE> conf_dict = {} <NEW_LINE> if not os.path.isfile(abspath): <NEW_LINE> <INDENT> raise RuntimeError('`%s` is not a file.' % abspath) <NEW_LINE> <DEDENT> with open(abspath, 'rb') as f: <NEW_LINE> <INDENT> compiled = compile(f.read(), abspath, 'exec') <NEW_LINE> <DEDENT> absname, _ = os.path.splitext(abspath) <NEW_LINE> basepath, module_name = absname.rsplit(os.sep, 1) <NEW_LINE> if sys.version_info >= (3, 3): <NEW_LINE> <INDENT> SourceFileLoader(module_name, abspath).load_module(module_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> imp.load_module( module_name, *imp.find_module(module_name, [basepath]) ) <NEW_LINE> <DEDENT> exec(compiled, globals(), conf_dict) <NEW_LINE> conf_dict['__file__'] = abspath <NEW_LINE> return conf_from_dict(conf_dict)
Creates a configuration dictionary from a file. :param filepath: The path to the file.
625941bed10714528d5ffc06
def shift_logs(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(f_log.format(MAX_LOGS)) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for x in reversed(range(2, MAX_LOGS+1)): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.rename(f_log.format(x-1), f_log.format(x)) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass
If the primary log exceeds a certain size (MAX_LOG) then the log is shelved and a new log is created. The maximum number of log files is defined by MAX_LOGS. After the max number of logs have been produced the oldest log will be deleted before each shelving action.
625941be3317a56b86939b85
def get_interpolated_gap(self, tol=0.001, abs_tol=False, spin=None): <NEW_LINE> <INDENT> tdos = self.y if len(self.ydim) == 1 else np.sum(self.y, axis=1) <NEW_LINE> if not abs_tol: <NEW_LINE> <INDENT> tol = tol * tdos.sum() / tdos.shape[0] <NEW_LINE> <DEDENT> energies = self.x <NEW_LINE> below_fermi = [i for i in range(len(energies)) if energies[i] < self.efermi and tdos[i] > tol] <NEW_LINE> above_fermi = [i for i in range(len(energies)) if energies[i] > self.efermi and tdos[i] > tol] <NEW_LINE> vbm_start = max(below_fermi) <NEW_LINE> cbm_start = min(above_fermi) <NEW_LINE> if vbm_start == cbm_start: <NEW_LINE> <INDENT> return 0.0, self.efermi, self.efermi <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> terminal_dens = tdos[vbm_start:vbm_start + 2][::-1] <NEW_LINE> terminal_energies = energies[vbm_start:vbm_start + 2][::-1] <NEW_LINE> start = get_linear_interpolated_value(terminal_dens, terminal_energies, tol) <NEW_LINE> terminal_dens = tdos[cbm_start - 1:cbm_start + 1] <NEW_LINE> terminal_energies = energies[cbm_start - 1:cbm_start + 1] <NEW_LINE> end = get_linear_interpolated_value(terminal_dens, terminal_energies, tol) <NEW_LINE> return end - start, end, start
Expects a DOS object and finds the gap Args: tol: tolerance in occupations for determining the gap abs_tol: Set to True for an absolute tolerance and False for a relative one. spin: Possible values are None - finds the gap in the summed densities, Up - finds the gap in the up spin channel, Down - finds the gap in the down spin channel. Returns: (gap, cbm, vbm): Tuple of floats in eV corresponding to the gap, cbm and vbm.
625941bee5267d203edcdbc6
def __init__(self): <NEW_LINE> <INDENT> self.root = self.Node() <NEW_LINE> self.size = 0
Initialize your data structure here.
625941be97e22403b379cebf
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not other.url == self.url: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
identify whether the other one represents a connection to a backend
625941bea79ad161976cc06b
def issubclass_strict(kls, parent_kls): <NEW_LINE> <INDENT> assert inspect.isclass(parent_kls) <NEW_LINE> return ( inspect.isclass(kls) and issubclass(kls, parent_kls) and kls is not parent_kls )
Indique si ``kls`` est une classe descendante de ``parent_kls``.
625941be956e5f7376d70d94
def list_object_store_access_keys_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = ['names', 'filter', 'sort', 'start', 'limit', 'token'] <NEW_LINE> all_params.append('callback') <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 key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method list_object_store_access_keys" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> query_params = [] <NEW_LINE> if 'names' in params: <NEW_LINE> <INDENT> query_params.append(('names', params['names'])) <NEW_LINE> collection_formats['names'] = 'csv' <NEW_LINE> <DEDENT> if 'filter' in params: <NEW_LINE> <INDENT> query_params.append(('filter', params['filter'])) <NEW_LINE> <DEDENT> if 'sort' in params: <NEW_LINE> <INDENT> query_params.append(('sort', params['sort'])) <NEW_LINE> <DEDENT> if 'start' in params: <NEW_LINE> <INDENT> query_params.append(('start', params['start'])) <NEW_LINE> <DEDENT> if 'limit' in params: <NEW_LINE> <INDENT> query_params.append(('limit', params['limit'])) <NEW_LINE> <DEDENT> if 'token' in params: <NEW_LINE> <INDENT> query_params.append(('token', params['token'])) <NEW_LINE> <DEDENT> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client. select_header_accept(['application/json']) <NEW_LINE> header_params['Content-Type'] = self.api_client. select_header_content_type(['application/json']) <NEW_LINE> auth_settings = ['AuthTokenHeader'] <NEW_LINE> return self.api_client.call_api('/1.6/object-store-access-keys', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ObjectStoreAccessKeyResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
List object store access keys This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.list_object_store_access_keys_with_http_info(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :param str filter: The filter to be used for query. :param str sort: Sort the response by the specified fields (in descending order if '-' is appended to the field name). :param int start: The offset of the first resource to return from a collection. :param int limit: limit, should be >= 0 :param str token: An opaque token used to iterate over a collection. The token to use on the next request is returned in the `continuation_token` field of the result. :return: ObjectStoreAccessKeyResponse If the method is called asynchronously, returns the request thread.
625941be5f7d997b871749bb
def __init__(self, width, height): <NEW_LINE> <INDENT> self.height = height <NEW_LINE> self.width = width <NEW_LINE> self.dirty_rooms = [[x, y] for x in range(width) for y in range(height)] <NEW_LINE> self.clean_rooms = []
Initializes a rectangular room with the specified width and height. Initially, no tiles in the room have been cleaned. width: an integer > 0 height: an integer > 0
625941be4527f215b584c380
def test_update_non_maintainer(self): <NEW_LINE> <INDENT> patch = create_patch() <NEW_LINE> state = create_state() <NEW_LINE> user = create_user() <NEW_LINE> self.client.force_authenticate(user=user) <NEW_LINE> resp = self.client.patch(self.api_url(patch.id), {'state': state.name}) <NEW_LINE> self.assertEqual(status.HTTP_403_FORBIDDEN, resp.status_code)
Update patch as non-maintainer. Ensure updates can be performed by maintainers.
625941be8e71fb1e9831d6d0
def rgb2gray(videodata): <NEW_LINE> <INDENT> videodata = vshape(videodata) <NEW_LINE> T, M, N, C = videodata.shape <NEW_LINE> if C == 1: <NEW_LINE> <INDENT> return videodata <NEW_LINE> <DEDENT> elif C == 3: <NEW_LINE> <INDENT> videodata = videodata[:, :, :, 0]*0.2989 + videodata[:, :, :, 1]*0.5870 + videodata[:, :, :, 2]*0.1140 <NEW_LINE> return vshape(videodata) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplemented
Computes the grayscale video. Computes the grayscale video from the input video returning the standardized shape (T, M, N, C), where T is number of frames, M is height, N is width, and C is number of channels (here always 1). Parameters ---------- videodata : ndarray Input data of shape (T, M, N, C), (T, M, N), (M, N, C), or (M, N), where T is number of frames, M is height, N is width, and C is number of channels. Returns ------- videodataout : ndarray Standardized grayscaled version of videodata, shape (T, M, N, 1)
625941bea17c0f6771cbdf79
def __timerecords(self,dt): <NEW_LINE> <INDENT> d, t = dt <NEW_LINE> nsteps=int(timediff((self.start_date,self.start_time),(d,t))/self.time_step) <NEW_LINE> nk=self.__layerrecords(self.nlayers+1) <NEW_LINE> return nsteps*nk
routine returns the number of records to increment from the data start byte to find the first time
625941be627d3e7fe0d68d74
def L_align(X1, X2): <NEW_LINE> <INDENT> data = X1.join(X2, how = 'outer', sort = True) <NEW_LINE> data = data.interpolate('index', limit_area ='inside') <NEW_LINE> data = data.loc[data.iloc[:,0].dropna().index.intersection(data.iloc[:,-1].dropna().index)] <NEW_LINE> data = data[~data.index.isin(X2.index.intersection(data.index))] <NEW_LINE> return data
Low Level Align, align two pandas timeseries (time as index) :param X1: dataframe :param X2: dataframe :return: aligned dataframe based on indices
625941be66673b3332b91fb7
def p_cond_without_not(self, p): <NEW_LINE> <INDENT> cond_without_not = p[1] <NEW_LINE> span = (p.lexpos(1), p.lexpos(1)) <NEW_LINE> if self.build_tree: <NEW_LINE> <INDENT> cond = { 'type': cond_without_not, 'span': span, } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cond = (getattr(self.karel, cond_without_not), span) <NEW_LINE> <DEDENT> p[0] = cond
cond_without_not : FRONT_IS_CLEAR | LEFT_IS_CLEAR | RIGHT_IS_CLEAR | MARKERS_PRESENT | NO_MARKERS_PRESENT
625941bea05bb46b383ec74a
def numElements(self): <NEW_LINE> <INDENT> self.__assertIsValid() <NEW_LINE> return internals.blpapi_Element_numElements(self.__handle)
Return the number of elements in this Element. Return the number of elements contained by this element. The number of elements is 0 if 'isComplex()' returns False, and no greater than 1 if the Datatype is CHOICE; if the DataType is SEQUENCE this may return any number (including 0).
625941be63f4b57ef0001046
def test_invalid_signature(self): <NEW_LINE> <INDENT> node, other = self.create_nodes(2) <NEW_LINE> other.send_identity(node) <NEW_LINE> message = node.create_full_sync_text('Should drop') <NEW_LINE> packet = node.encode_message(message) <NEW_LINE> invalid_packet = packet[:-node.my_member.signature_length] + 'I' * node.my_member.signature_length <NEW_LINE> self.assertNotEqual(packet, invalid_packet) <NEW_LINE> other.give_packet(invalid_packet, node) <NEW_LINE> self.assertEqual(other.fetch_messages([u"full-sync-text", ]), [])
NODE sends a message containing an invalid signature to OTHER. OTHER should drop it
625941be656771135c3eb792
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(FRClientGoal, self).__init__(*args, **kwds) <NEW_LINE> if self.order_id is None: <NEW_LINE> <INDENT> self.order_id = 0 <NEW_LINE> <DEDENT> if self.order_argument is None: <NEW_LINE> <INDENT> self.order_argument = '' <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.order_id = 0 <NEW_LINE> self.order_argument = ''
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: order_id,order_argument :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields.
625941be73bcbd0ca4b2bf9d
def __init__(self, handler, main_window=None): <NEW_LINE> <INDENT> gtk.Menu.__init__(self) <NEW_LINE> self.handler = handler <NEW_LINE> StatusMenu = extension.get_default('menu status') <NEW_LINE> self.status = gtk.ImageMenuItem(_('Status')) <NEW_LINE> self.status.set_image(gtk.image_new_from_stock(gtk.STOCK_CONVERT, gtk.ICON_SIZE_MENU)) <NEW_LINE> self.status_menu = StatusMenu(handler.on_status_selected) <NEW_LINE> self.status.set_submenu(self.status_menu) <NEW_LINE> self.list = gtk.ImageMenuItem(_('Contacts')) <NEW_LINE> self.list.set_image(utils.safe_gtk_image_load(gui.theme.image_theme.chat)) <NEW_LINE> self.list_contacts = ContactsMenu(handler, main_window) <NEW_LINE> self.list.set_submenu(self.list_contacts) <NEW_LINE> self.hide_show_mainwindow = gtk.MenuItem(_('Hide/Show emesene')) <NEW_LINE> self.hide_show_mainwindow.connect('activate', lambda *args: self.handler.on_hide_show_mainwindow(main_window)) <NEW_LINE> self.disconnect = gtk.ImageMenuItem(gtk.STOCK_DISCONNECT) <NEW_LINE> self.disconnect.connect('activate', lambda *args: self.handler.on_disconnect_selected()) <NEW_LINE> self.quit = gtk.ImageMenuItem(gtk.STOCK_QUIT) <NEW_LINE> self.quit.connect('activate', lambda *args: self.handler.on_quit_selected()) <NEW_LINE> self.append(self.hide_show_mainwindow) <NEW_LINE> self.append(self.status) <NEW_LINE> self.append(self.list) <NEW_LINE> self.append(self.disconnect) <NEW_LINE> self.append(gtk.SeparatorMenuItem()) <NEW_LINE> self.append(self.quit)
constructor handler -- a e3common.Handler.TrayIconHandler object
625941be21a7993f00bc7c11
def test_update_no_self(self): <NEW_LINE> <INDENT> Square_test = Square(5, 9) <NEW_LINE> with self.assertRaises(TypeError) as excep: <NEW_LINE> <INDENT> Square.update() <NEW_LINE> <DEDENT> message = "update() missing 1 required positional argument: 'self'" <NEW_LINE> self.assertEqual(str(excep.exception), message) <NEW_LINE> dic = Square_test.__dict__.copy() <NEW_LINE> Square_test.update() <NEW_LINE> self.assertEqual(Square_test.__dict__, dic)
Test update without self
625941bed18da76e235323f9
@app.permission('authenticated') <NEW_LINE> def permission_authenticated(account=None): <NEW_LINE> <INDENT> if g.account and g.account.id: <NEW_LINE> <INDENT> if account and account.id: <NEW_LINE> <INDENT> return g.account.id == account.id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False
Check whether the account session is authenticated. If an account argument is provided - check whether the account is the current session account @param <Account>account (optional) @return bool @example Call as app.access('authenticated'), app.access('authenticated', account=account)
625941be7047854f462a1332
def can_do(self, interpreted, message): <NEW_LINE> <INDENT> if len(interpreted) < 2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> word = interpreted[1] <NEW_LINE> for word in interpreted: <NEW_LINE> <INDENT> if word[1] == ":news:": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Tells if the class can process the message. @param interpreted interpreted message @param message message @return true if the class can process the message
625941be76e4537e8c351597
def embed_sentences(self, sentences: Union[List[str], str], lang: Union[str, List[str]]) -> np.ndarray: <NEW_LINE> <INDENT> sentences = [sentences] if isinstance(sentences, str) else sentences <NEW_LINE> lang = [lang] * len(sentences) if isinstance(lang, str) else lang <NEW_LINE> if len(sentences) != len(lang): <NEW_LINE> <INDENT> raise ValueError( 'lang: invalid length: the number of language codes does not match the number of sentences' ) <NEW_LINE> <DEDENT> with sre_performance_patch(): <NEW_LINE> <INDENT> sentence_tokens = [ self._get_tokenizer(sentence_lang).tokenize(sentence) for sentence, sentence_lang in zip(sentences, lang) ] <NEW_LINE> bpe_encoded = [ self.bpe.encode_tokens(tokens) for tokens in sentence_tokens ] <NEW_LINE> return self.bpeSentenceEmbedding.embed_bpe_sentences(bpe_encoded)
Computes the LASER embeddings of provided sentences using the tokenizer for the specified language. Args: sentences (str or List[str]): the sentences to compute the embeddings from. lang (str or List[str]): the language code(s) (ISO 639-1) used to tokenize the sentences (either as a string - same code for every sentence - or as a list of strings - one code per sentence). Returns: np.ndarray: A N * 1024 NumPy array containing the embeddings, N being the number of sentences provided.
625941be711fe17d82542297
def inverse(self, x): <NEW_LINE> <INDENT> x2, y1 = x[0], x[1] <NEW_LINE> if self.stride == 2: <NEW_LINE> <INDENT> x2 = self.psi.inverse(x2) <NEW_LINE> <DEDENT> Fx2 = - self.bottleneck_block(x2) <NEW_LINE> x1 = Fx2 + y1 <NEW_LINE> if self.stride == 2: <NEW_LINE> <INDENT> x1 = self.psi.inverse(x1) <NEW_LINE> <DEDENT> if self.pad != 0 and self.stride == 1: <NEW_LINE> <INDENT> x = merge(x1, x2) <NEW_LINE> x = self.inj_pad.inverse(x) <NEW_LINE> x1, x2 = split(x) <NEW_LINE> x = (x1, x2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = (x1, x2) <NEW_LINE> <DEDENT> return x
bijective or injecitve block inverse
625941bed10714528d5ffc07
def get_point_data(self): <NEW_LINE> <INDENT> return self.dataframe_dict
This returns the dictionary so that you can use it.
625941bed486a94d0b98e06b
def setUp(self): <NEW_LINE> <INDENT> self.path_to_job_ids = os.path.join(os.path.dirname(__file__), 'test_inputs', 'test_job_ids') <NEW_LINE> self.parse_job_id = parse_file.ParseJobID().parse_file
Setup a path to job ids and a parse jod id variable for easier writing/parsing.
625941be4428ac0f6e5ba718
def list( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.NetworkSecurityGroupListResult"]: <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2020-08-01" <NEW_LINE> accept = "application/json" <NEW_LINE> def prepare_request(next_link=None): <NEW_LINE> <INDENT> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> if not next_link: <NEW_LINE> <INDENT> url = self.list.metadata['url'] <NEW_LINE> path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = next_link <NEW_LINE> query_parameters = {} <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> <DEDENT> return request <NEW_LINE> <DEDENT> async def extract_data(pipeline_response): <NEW_LINE> <INDENT> deserialized = self._deserialize('NetworkSecurityGroupListResult', pipeline_response) <NEW_LINE> list_of_elem = deserialized.value <NEW_LINE> if cls: <NEW_LINE> <INDENT> list_of_elem = cls(list_of_elem) <NEW_LINE> <DEDENT> return deserialized.next_link or None, AsyncList(list_of_elem) <NEW_LINE> <DEDENT> async def get_next(next_link=None): <NEW_LINE> <INDENT> request = prepare_request(next_link) <NEW_LINE> pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> raise HttpResponseError(response=response, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> return pipeline_response <NEW_LINE> <DEDENT> return AsyncItemPaged( get_next, extract_data )
Gets all network security groups in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either NetworkSecurityGroupListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_08_01.models.NetworkSecurityGroupListResult] :raises: ~azure.core.exceptions.HttpResponseError
625941be5166f23b2e1a507f
def get_status_led(self): <NEW_LINE> <INDENT> return self.led.get_status()
Gets the state of the fan status LED Returns: A string, one of the predefined STATUS_LED_COLOR_* strings above
625941be6fece00bbac2d663
def test_GetKernelArguments_hello_world(): <NEW_LINE> <INDENT> args_ = args.GetKernelArguments("kernel void a(global float* a) {}") <NEW_LINE> assert args_[0].typename == "float"
Simple hello world argument type test.
625941be6fb2d068a760efc1
def _array_to_tile(tile_bits, tile, is_hex=False): <NEW_LINE> <INDENT> if is_hex: <NEW_LINE> <INDENT> for ii, xx in enumerate(tile_bits): <NEW_LINE> <INDENT> tile[ii] = _bits_to_nibbles(xx) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for ii, xx in enumerate(tile_bits): <NEW_LINE> <INDENT> tile[ii] = tile_bits.shape[1] * "%d" % tuple(xx)
Convert a numpy array to text icedb tile Modifies tile in place to simplify updating of iceconfig
625941be76d4e153a657ea57
def __init__(self, context, lower_risk_score, upper_risk_score): <NEW_LINE> <INDENT> self.upper_risk_score = upper_risk_score <NEW_LINE> self.lower_risk_score = lower_risk_score <NEW_LINE> self.context = context <NEW_LINE> self.users_risk_score_list = list() <NEW_LINE> self.internal_report = None
Initialise reporter :param context: AppContext instance :param lower_risk_score: value to filter users :param upper_risk_score: value to filter users
625941be7047854f462a1333
def __init__(self, obj, **adapted_methods): <NEW_LINE> <INDENT> self.obj = obj <NEW_LINE> self.__dict__.update(adapted_methods) <NEW_LINE> self.provider = None
We set the adapted methods in the object's dict
625941bee76e3b2f99f3a737
def multivariate_gauss_prob(observed, mean, covariance): <NEW_LINE> <INDENT> return None
Calculates the probability density at the observed point of a gaussian distribution with the specified mean and covariance The probability density at an observed point is, given a distribution, what is the likelihood of observing the provided point. The mean and covariance describe a gaussian distribution. args: observed: The point at which to calculate the probability density mean: the mean of the gaussian distribution covariance: the covariance of the gaussian distribution returns: the probability of selecting the observed point
625941be7c178a314d6ef381
def cycle_through_dates(self): <NEW_LINE> <INDENT> current_date = self.initial_date <NEW_LINE> while current_date != (self.until_date + timedelta(days=1)): <NEW_LINE> <INDENT> year = current_date.strftime('%Y') <NEW_LINE> month = current_date.strftime('%m') <NEW_LINE> day = current_date.strftime('%d') <NEW_LINE> log.info('Search records for {}-{}-{}'.format(year, month, day)) <NEW_LINE> pagedir = "{0}/data/raw/{1}-{2}-{3}/page-html".format( PROJECT_DIR, year, month, day) <NEW_LINE> formdir = "{0}/data/raw/{1}-{2}-{3}/form-html".format( PROJECT_DIR, year, month, day) <NEW_LINE> if not os.path.exists(pagedir): <NEW_LINE> <INDENT> log.info('Create directory {}'.format(pagedir)) <NEW_LINE> os.makedirs(pagedir) <NEW_LINE> <DEDENT> if not os.path.exists(formdir): <NEW_LINE> <INDENT> log.info('Create directory {}'.format(formdir)) <NEW_LINE> os.makedirs(formdir) <NEW_LINE> <DEDENT> search_date = '{}{}{}'.format(month, day, year) <NEW_LINE> self.navigate_search_page(year, month, day) <NEW_LINE> self.search_parameters(search_date) <NEW_LINE> self.parse_results(year, month, day) <NEW_LINE> current_date += timedelta(days=1)
For each date in range, search, parse results and save HTML. TODO: Make this asynchronous.
625941becc40096d61595878
def common_filter(): <NEW_LINE> <INDENT> mylist = [1, 4, -5, 10, -7, 2, 3, -1] <NEW_LINE> resultList = [n for n in mylist if n > 0]
列表推导式 :return:
625941be3617ad0b5ed67e1f
def unless_macos(): <NEW_LINE> <INDENT> if is_macos(): <NEW_LINE> <INDENT> return lambda func: func <NEW_LINE> <DEDENT> return unittest.skip("Test requires macOS.")
Decorator to skip a test unless it is run on a macOS system.
625941be30c21e258bdfa3c2
def _get_asset_files(self, asset_type: str) -> List["HarEntry"]: <NEW_LINE> <INDENT> return self.filter_entries(content_type=self.asset_types[asset_type])
Returns a list of all HarEntry object of a certain file type. :param asset_type: Asset type to filter for :type asset_type: str :return: List of HarEntry objects that meet the :rtype: List[HarEntry]
625941be45492302aab5e1e7
def test_antispamfield_not_escaped(self): <NEW_LINE> <INDENT> context = {'form': ContactForm()} <NEW_LINE> content = render_to_string('envelope/contact_form.html', context) <NEW_LINE> self.assertNotIn('&lt;div', content)
Antispam fields should not be escaped by Django.
625941bed486a94d0b98e06c