code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _write_disagg_result_node(self, site, value): <NEW_LINE> <INDENT> disagg_result_node_tag = "%sdisaggregationResultNode" % NRML <NEW_LINE> disagg_result_node_el = etree.SubElement( self.disagg_result_field_el, disagg_result_node_tag, nsmap=NSMAP) <NEW_LINE> self._set_id(disagg_result_node_el) <NEW_LINE> site_el = et...
Write a <disaggregationResult/> for a given site. :param site: site related to the disaggregation result :type site: :class:`openquake.shapes.Site` :param value: data to write :type value: dict in the following format:: {"groundMotionValue": 0.25, "path": "/path/to/file"} "path": "/path/to/file"} Given ...
625941f4d18da76e23532aea
def count(self): <NEW_LINE> <INDENT> e = self.alpha * float(self.m ** 2) / np.sum(2.0**(-self.reg)) <NEW_LINE> if e <= (5.0 / 2.0) * self.m: <NEW_LINE> <INDENT> num_zero = self.m - np.count_nonzero(self.reg) <NEW_LINE> return self._linearcounting(num_zero) <NEW_LINE> <DEDENT> if e <= (1.0 / 30.0) * (1 << 32): <NEW_LINE...
Estimate the cardinality of the data values seen so far. Returns: int: The estimated cardinality.
625941f40383005118ecfbec
def is_daterange(value, default=None): <NEW_LINE> <INDENT> if str(value) == "None": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not isinstance(value, list) or len(value) not in [3, 4]: <NEW_LINE> <INDENT> raise VdtDateTimeError("Need startdate, end date and step") <NEW_LINE> <DEDENT> closed = None if len(value) =...
Validation function of a :func:`pandas.date_range`
625941f4507cdc57c63072f6
def get_comment_object(self): <NEW_LINE> <INDENT> new_comment = super(CityCommentForm, self).get_comment_object() <NEW_LINE> new = create_from_existing_base(base_class=Comment, inheritor_class=CityComment, obj=new_comment) <NEW_LINE> new.phone = self.cleaned_data["phone"] <NEW_LINE> return new
Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``).
625941f430dc7b7665901f6b
def get_areas(self, ssxz: int, code: str = None): <NEW_LINE> <INDENT> res = [] <NEW_LINE> if ssxz == 0: <NEW_LINE> <INDENT> sql = "select code, name, post_name from obj_diqu where parent is null and ssxz= 0 order by pinyin asc" <NEW_LINE> res = self.fdm(sql) <NEW_LINE> <DEDENT> elif ssxz != 0 and code: <NEW_LINE> <I...
获取某个省所有的市/市里所有的区县
625941f48e71fb1e9831ddb2
def write_XML(outdir, mol): <NEW_LINE> <INDENT> report = construct_XML(mol) <NEW_LINE> tree = et.ElementTree(report) <NEW_LINE> outpath = osp.join(outdir, "report.xml") <NEW_LINE> tree.write(outpath, pretty_print=True, xml_declaration=True)
Takes in a PDBComplex object and writes an XML report to a dir.
625941f47d847024c06be8cd
def insecure__check_pw_secure_id(id, pw): <NEW_LINE> <INDENT> security = 0 <NEW_LINE> cursor = get_cursor() <NEW_LINE> compare = get_md5_bytes(pw) <NEW_LINE> sqlstring = """SELECT insecure_id from user WHERE secure_id = '""" + id + """' AND pw_md5 = '""" + compare + """'""" <NEW_LINE> cursor.execute(sqlstring) <NEW_LIN...
Unsicherer md5-byte passwort vergleich aus der DB anhand sicherer ID mit unsicherem Passwort Sicherheitsstufe (security) erhöht sich wenn ein passwordcheck geschafft wird und bleibt gleich sich wenn nicht geschafft werden security 0 = kein check geschafft --> falsches passwort security 1 = nur weiter check geschafft -...
625941f47cff6e4e81117f91
def test02_url_procuct(self): <NEW_LINE> <INDENT> url=self.get_url+'/#/main/(router-main:product)' <NEW_LINE> r = requests.get(url) <NEW_LINE> self.assertEqual(r.status_code,200) <NEW_LINE> print('成功get页面:产品页')
get页面:产品页
625941f497e22403b379d5a8
def get_x_y(gaps_picture, big_picture, result_path="", is_show=False): <NEW_LINE> <INDENT> gaps_temp = 'gaps_img_gray_temp.jpg' <NEW_LINE> big_temp = 'big_img_rgb_temp.jpg' <NEW_LINE> gaps_img_gray = cv2.imread(gaps_picture, 0) <NEW_LINE> cv2.imwrite(gaps_temp, gaps_img_gray) <NEW_LINE> w, h = gaps_img_gray.shape[::-1]...
输入缺口图片和匹配的大图、图片的类型,返回缺口图片在大图的起点位置(x,y) :param gaps_picture: 缺口图片路径 :param big_picture: 大图路径 :param i s_show: 默认不展示图片 :return:
625941f467a9b606de4a84c2
def __init__(self, master): <NEW_LINE> <INDENT> super(Application, self).__init__(master) <NEW_LINE> self.grid() <NEW_LINE> self.bttn_clicks = 0 <NEW_LINE> self.create_widget()
Create Frame
625941f426238365f5f0f482
def export_hashtag_totals(n=50): <NEW_LINE> <INDENT> start_date = EST.localize(datetime.datetime(2015, 10, 27, 0)) <NEW_LINE> stop_date = EST.localize(datetime.datetime(2015, 11, 2, 23, 59)) <NEW_LINE> with open("hashtag_totals.csv", "w") as f: <NEW_LINE> <INDENT> f.write("hashtag, mentions\n") <NEW_LINE> for hashtag i...
Export the N most mentioned hashtags and their respective counts to a CSV file.
625941f4627d3e7fe0d6945e
def update(self): <NEW_LINE> <INDENT> args = [] <NEW_LINE> msg = '>>> Starting layman sync for %(repo)s...' % ({'repo': self.repo.name}) <NEW_LINE> self.logger(self.xterm_titles, msg) <NEW_LINE> writemsg_level(msg + '\n') <NEW_LINE> location = self.repo.location.replace(self.repo.name, '') <NEW_LINE> args.ap...
Update existing repository
625941f4b7558d58953c5512
def guess_changelog_data(self): <NEW_LINE> <INDENT> pass
returns list of tuples (author, email) from git
625941f463b5f9789fde76f2
def __str__(self): <NEW_LINE> <INDENT> return "\n".join([str([entry]) for entry in self.values])
string representation.
625941f407f4c71912b11a91
def getLilyDuration(self): <NEW_LINE> <INDENT> value = "" <NEW_LINE> if not hasattr(self, "val_type"): <NEW_LINE> <INDENT> if hasattr(self, "duration") and self.duration is not None: <NEW_LINE> <INDENT> value = (self.duration / self.divisions) <NEW_LINE> value = (1 / value) <NEW_LINE> value *= 4 <NEW_LINE> if value >= ...
method to calculate duration of note in lilypond duration style :return:
625941f491f36d47f21acb05
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{{ cookiecutter.project_name }}.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't imp...
Run administrative tasks.
625941f44f6381625f115047
def validateDtd(self, ctxt, dtd): <NEW_LINE> <INDENT> if ctxt is None: ctxt__o = None <NEW_LINE> else: ctxt__o = ctxt._o <NEW_LINE> if dtd is None: dtd__o = None <NEW_LINE> else: dtd__o = dtd._o <NEW_LINE> ret = libxml2mod.xmlValidateDtd(ctxt__o, self._o, dtd__o) <NEW_LINE> return ret
Try to validate the document against the dtd instance Basically it does check all the definitions in the DtD. Note the the internal subset (if present) is de-coupled (i.e. not used), which could give problems if ID or IDREF is present.
625941f45fdd1c0f98dc0841
def call(self, inputs, training=True): <NEW_LINE> <INDENT> mask = tf.equal(inputs, 0) <NEW_LINE> mask = mask[:, :, np.newaxis] <NEW_LINE> word_emb = self.embedding(inputs) <NEW_LINE> word_emb *= tf.sqrt(tf.cast(self.cfg.d_model, tf.float32)) <NEW_LINE> emb = word_emb + self.pos_embedding <NEW_LINE> emb = tf.where(mask,...
:param inputs: [-1, seq_len] :param training: 是否训练, True: 是, False: 否 :return:
625941f48a349b6b435e877e
def agent_start(self, state): <NEW_LINE> <INDENT> state = tuple(state.intArray) <NEW_LINE> return self.do_step(state)
Called every time a new game is started
625941f432920d7e50b287e1
def __init__(self, final_survival_prob, depth): <NEW_LINE> <INDENT> super(Stochastic_Dropout, self).__init__() <NEW_LINE> self.final_survival = final_survival_prob <NEW_LINE> self.depth = depth
Stochastic layer dropout https://arxiv.org/pdf/1603.09382.pdf Args: Final_survival_prob: survival probability of the last layer, p_L (in paper) depth: Depth of the stack of layer (number of layers) dropout_rate: regular drop out rate
625941f44e696a04525c9a5a
def crop_to_pointcloud_proportion( self, pointcloud, boundary_proportion, minimum=True, constrain_to_boundary=True, return_transform=False, ): <NEW_LINE> <INDENT> if minimum: <NEW_LINE> <INDENT> boundary = boundary_proportion * np.min(pointcloud.range()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> boundary = boundary...
Return a copy of this image cropped so that it is bounded around a pointcloud with a border proportional to the pointcloud spread or range. Parameters ---------- pointcloud : :map:`PointCloud` The pointcloud to crop around. boundary_proportion : `float` Additional padding to be added all around the landmarks ...
625941f4f9cc0f698b140c02
def _check_transition_mx(self): <NEW_LINE> <INDENT> trans = self.transition_matrix <NEW_LINE> N = trans.shape[0] <NEW_LINE> if N != trans.shape[1]: <NEW_LINE> <INDENT> raise ValueError('Expect square transition matrix -- got %s:' % (trans.shape,) ) <NEW_LINE> <DEDENT> sums = np.ravel(mx.todense(trans.sum(axis=1))) <NEW...
Internally used function that checks the integrity/format of transition matrices.
625941f423849d37ff7b3696
def test_data(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'subclasses of Dataset must provide a test_data() method')
Return test data
625941f444b2445a3393269d
@task <NEW_LINE> def pull(): <NEW_LINE> <INDENT> with cd(env.code_dir): <NEW_LINE> <INDENT> run('git pull origin %s' % (env.code_branch, ))
Pull from repo
625941f4b5575c28eb68e612
def test_file_attachments_get_my_file_attachments(self): <NEW_LINE> <INDENT> pass
Test case for file_attachments_get_my_file_attachments Get my file attachments. Get files you've attached to timesheets. # noqa: E501
625941f4090684286d50f2fc
def str_in_list(l1, l2): <NEW_LINE> <INDENT> return [i for i in l1 if i.lower() in l2]
Check if one element of l1 is in l2 and if yes, returns the name of that element in a list (could be more than one. Examples -------- >>> print(str_in_list(['time', 'lon'], ['temp','time','prcp'])) ['time'] >>> print(str_in_list(['time', 'lon'], ['temp','time','prcp','lon'])) ['time', 'lon']
625941f4fff4ab517eb2fa4d
def print_menu(title, list_options, exit_message): <NEW_LINE> <INDENT> for index, value in enumerate(list_options): <NEW_LINE> <INDENT> print(f"({index+1}) {value}") <NEW_LINE> <DEDENT> print("(0) %s" % exit_message)
Displays a menu. Sample output: Main menu: (1) Store manager (2) Human resources manager (3) Inventory manager (4) Accounting manager (5) Sales manager (6) Customer relationship management (CRM) (0) Exit program Args: title (str): menu title list_optio...
625941f4fb3f5b602dac3ca6
def set_pkg_license_declared(self, doc, lic): <NEW_LINE> <INDENT> self.assert_package_exists() <NEW_LINE> if not self.package_license_declared_set: <NEW_LINE> <INDENT> self.package_license_declared_set = True <NEW_LINE> if validations.validate_lics_conc(lic): <NEW_LINE> <INDENT> doc.package.license_declared = lic <NEW_...
Sets the package's declared license. Raises SPDXValueError if data malformed. Raises OrderError if no package previously defined. Raises CardinalityError if already set.
625941f4851cf427c661ab15
def Remove(self, *__args): <NEW_LINE> <INDENT> pass
Remove(self: MeshVertexList, indices: IEnumerable[int], shrinkFaces: bool) -> bool Remove(self: MeshVertexList, index: int, shrinkFaces: bool) -> bool Removes the vertex at the given index and all faces that reference that index. index: Index of vertex to remove. shrinkFaces: If true, quads that ref...
625941f4dc8b845886cb5b43
def get_persistent_objects(self, cls): <NEW_LINE> <INDENT> updated = self.__get_objects_in_category("update", cls) <NEW_LINE> created = self.__get_objects_in_category("create", cls) <NEW_LINE> return created.extend(updated)
Возвращает список объектов на обновление и создание. Если указан класс, то список будет отфильтрован по этому классу.
625941f421bff66bcd684f59
def _cb_stream_established(self, call): <NEW_LINE> <INDENT> logger.info("in stream established callback, %s", threading.current_thread().getName()) <NEW_LINE> self.stream_established_event.set() <NEW_LINE> self.answered_event.clear() <NEW_LINE> logger.info("in stream established callback end")
callback for stream on server, use for rpc wait for functions
625941f476d4e153a657f13f
def __init__(self, idx, latitude, longitude, power_density, power_capacity, speed, elevation): <NEW_LINE> <INDENT> self.idx = idx <NEW_LINE> self.latitude = latitude <NEW_LINE> self.longitude = longitude <NEW_LINE> self.power_density = power_density <NEW_LINE> self.power_capacity = power_capacity <NEW_LINE> self.speed ...
Initializes turbine with a given target id, lat, long, power density and power capacity. Parameters ---------- target_idx : int A user-defined id. latitude : float Latitude. longitude : float Longitude power_density : float Power Density. power_capacity : float ...
625941f4bf627c535bc137dc
def __init__(self, parent): <NEW_LINE> <INDENT> QAbstractTableModel.__init__(self, parent) <NEW_LINE> self.owner = parent <NEW_LINE> self.nbCol = len(HEADERS_DEF) <NEW_LINE> self.mydata = []
Table Model for parameters @param parent: @type parent:
625941f4b57a9660fec33e99
def __init__(self, group_id, token): <NEW_LINE> <INDENT> self.group_id = group_id <NEW_LINE> self.token = token <NEW_LINE> self.vk = vk_api.VkApi(token=token) <NEW_LINE> self.api = self.vk.get_api() <NEW_LINE> self.longpoller = VkBotLongPoll(self.vk, self.group_id)
:param group_id: group id из группы вконтакте :param token: токен из группы вк
625941f48c0ade5d55d3efcd
def test_line(): <NEW_LINE> <INDENT> model = pb.Model(examples.chain_lattice(a=1), pb.line(0, 4.5)) <NEW_LINE> assert model.system.num_sites == 4 <NEW_LINE> model = pb.Model(examples.chain_lattice(a=1), pb.line([0, -0.5], [5, 0.5])) <NEW_LINE> assert model.system.num_sites == 6
1D shape with 1D lattice
625941f41f5feb6acb0c5155
def get_issues(jira,jql,start=0,max=100): <NEW_LINE> <INDENT> start=0 <NEW_LINE> max=100 <NEW_LINE> issues = [] <NEW_LINE> tempList = jira.search_issues( jql, startAt=start, maxResults=max ) <NEW_LINE> issues += tempList <NEW_LINE> while len(tempList)==100: <NEW_LINE> <INDENT> start=start+100 <NEW_LINE> max=max+100 <NE...
Returns issues found using a jira filter. Supports max and start values as the Jira API has a hard limit on results and requires looped queries to get all issues when the count is higher than that. Inputs: :jira: authenticated jira object :jql: the dict key for the filter in settings :start: Start poin...
625941f4d4950a0f3b08c952
def pivot_list_dict(iterable, key, none_mode='ignore', key_transform=None): <NEW_LINE> <INDENT> if key_transform is None: <NEW_LINE> <INDENT> key_transform = identity <NEW_LINE> <DEDENT> list_pivot = {} <NEW_LINE> for item in iter(iterable): <NEW_LINE> <INDENT> if item[key] is None and none_mode == 'ignore': <NEW_LINE>...
Builds a dictionary using the values of the given key in each of the indexable items in the given iterable as keys and lists of all items with the same key as values. Similar to L{pivot_dict} (see there for details on parameters), but it handles duplicate keys gracefully by building lists of items for each key. Examp...
625941f466656f66f7cbc7b9
def notify_admin(sender, instance, created, **kwargs): <NEW_LINE> <INDENT> if instance.notification: <NEW_LINE> <INDENT> if settings.EMAIL_BY and settings.EMAIL_TO: <NEW_LINE> <INDENT> subject = 'New post from %s !!!' % instance.author <NEW_LINE> mail_template = loader.get_template('blogs/post-notification.txt') <NEW_L...
Notify the administrator that a new post has been added.
625941f4adb09d7d5db6cd98
def setupInheritedModels(self): <NEW_LINE> <INDENT> opts = self.getMeta() <NEW_LINE> rootAlias = self.tables[0] <NEW_LINE> seen = {None: rootAlias} <NEW_LINE> for field, modal in opts.getFieldsWithModel(): <NEW_LINE> <INDENT> if modal not in seen: <NEW_LINE> <INDENT> self.joinParentModel(opts, modal, rootAlias, seen) <...
If the modal that is the basis for this QuerySet inherits other model, we need to ensure that those other model have their tables included in the query. We do this as a separate step so that subclasses know which tables are going to be active in the query, without needing to compute all the select columns (this method...
625941f4287bf620b61d406c
@main.route('/moderate/enable/<int:id>') <NEW_LINE> @login_required <NEW_LINE> @permission_required(Permission.MODERATE_COMMENTS) <NEW_LINE> def moderate_enable(id): <NEW_LINE> <INDENT> comment = Comment.query.get_or_404(id) <NEW_LINE> comment.disabled = False <NEW_LINE> db.session.add(comment) <NEW_LINE> return redire...
grabs comment by id, sets disabled to false, and returns moderate url to keep modding, and whatever page was inc'd in the request string. :param id: :return:
625941f4a17c0f6771cbe65b
def get_start_node(self): <NEW_LINE> <INDENT> return self.start_node
Return the start node for the grid
625941f46fece00bbac2dd53
def test_view_categories(self): <NEW_LINE> <INDENT> Perms.objects.create(user=self.user, access_level=4).save() <NEW_LINE> self.client.login(username='hodor', password='hodor') <NEW_LINE> response = self.client.get('/categories/') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTemplateUsed...
Testing with valid prems
625941f4377c676e912727b3
def calculate_age(self, born): <NEW_LINE> <INDENT> today = date.today() <NEW_LINE> years_difference = today.year - born.year <NEW_LINE> is_before_birthday = (today.month, today.day) <(born.month, born.day) <NEW_LINE> elapsed_years = years_difference - int(is_before_birthday) <NEW_LINE> return elapsed_years
Calculates age from date of birth
625941f47cff6e4e81117f92
def search(self, search_form_data): <NEW_LINE> <INDENT> from orb.models import Tag <NEW_LINE> qs = self.all() <NEW_LINE> for field_name in ['health_topic', 'resource_type', 'audience', 'geography', 'language', 'device']: <NEW_LINE> <INDENT> if search_form_data.get(field_name): <NEW_LINE> <INDENT> qs = qs.filter(tags__i...
Args: search_form_data: a dictionary of cleaned field data Returns:
625941f4a219f33f34628f6d
def test_invalid_utr(self): <NEW_LINE> <INDENT> self.tr.combined_cds = [] <NEW_LINE> self.tr.finalized = False <NEW_LINE> self.assertRaises(Mikado.exceptions.InvalidTranscript, self.tr.finalize)
Test that a transcript with UTR but no CDS defined will raise an exception. :return:
625941f4a8370b7717052eaa
def test_from_attr_to_cur_ctrl(self): <NEW_LINE> <INDENT> self.cset = self.device.cset[2] <NEW_LINE> self.chan = self.cset.chan[0] <NEW_LINE> test_attr = (("resolution-bits", 0), ("gain_factor", 1), ("offset", 2), ("max-sample-rate", 3), ("vref-src", 4), ("nshots", 0), ("post-samples", 1), ("pre-samples", 2) ) <NEW_LIN...
It tests that user value written on a trigger sysfs attribute will be written also on the current control.
625941f4b545ff76a8914422
def __init__( self, *, connection_string: str, name: str, subscription_id: Optional[str] = None, resource_group: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(RoutingServiceBusTopicEndpointProperties, self).__init__(**kwargs) <NEW_LINE> self.connection_string = connection_string <NEW_LINE> self.name = nam...
:keyword connection_string: Required. The connection string of the service bus topic endpoint. :paramtype connection_string: str :keyword name: Required. The name that identifies this endpoint. The name can only include alphanumeric characters, periods, underscores, hyphens and has a maximum length of 64 characters. ...
625941f47047854f462a1a0f
def chain2atomMask( self, chainMask, breaks=0 ): <NEW_LINE> <INDENT> return self.extendMask( chainMask, self.chainIndex( breaks=breaks ), self.lenAtoms() )
Convert chain mask to atom mask. :param chainMask: list/array of int, 1 x N_chains :type chainMask: list/array of int :param breaks: look for chain breaks in backbone coordinates (def. 0) :type breaks: 0||1 :return: 1 x N_atoms :rtype: array of int
625941f456ac1b37e62647cf
def prepare_strptime(parameters): <NEW_LINE> <INDENT> fieldname = parameters['field'] <NEW_LINE> formatstring = parameters.get('format') <NEW_LINE> if formatstring: <NEW_LINE> <INDENT> parse = lambda value: datetime.datetime.strptime(value, formatstring) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> import dateutil.par...
Parse dates The provided code is executed. The variable ``message`` is set to the a mapping type (dict) representing the message. Any changes to the message will be visible in the rest of the pipeline. Parameters: ```field``` Required. The field containing the timestamp to be processed. ```format``` The strf...
625941f4d6c5a1020814465c
@app.route('/nodes/clearAll', methods=['GET']) <NEW_LINE> def nodes_clear(): <NEW_LINE> <INDENT> node_list = {} <NEW_LINE> return jsonify("Cleared"), 200
Clear all nodes connected to the network
625941f456b00c62f0f14c6a
def rotate3(m, vector): <NEW_LINE> <INDENT> return np.multiply(vector, m)
Returns the rotation of vector by 3x3 (row major) matrix m
625941f42c8b7c6e89b35dc8
def certificate_check(self, certificate, valid, host): <NEW_LINE> <INDENT> raise Passthrough
Certificate callback. Override with your own function to determine whether to accept the server's certificate. Returns: True to connect, False to abort. Parameters: certificate : None The certificate. It is currently always None while we figure out how to represent it cross-platform. valid : bool Whethe...
625941f49f2886367277ae95
def extract_types(self): <NEW_LINE> <INDENT> left_ts = self.left_types.get() <NEW_LINE> right_ts = self.right_types.get() <NEW_LINE> if len(left_ts) == 0 or len(right_ts) == 0: <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> self.infer_arguments() <NEW_LINE> extracted = set() <NEW_LINE> for left in left_ts: <NEW_L...
Check all possible combinations.
625941f4d99f1b3c44c67b90
def add_str(*args, **kwargs): <NEW_LINE> <INDENT> kwargs_list = ['%s=%s' % (k, kwargs[k]) for k in kwargs] <NEW_LINE> print(''.join(args), ','.join(kwargs_list))
Concatenates all arguments as strings. Prints results to stdout.
625941f4f548e778e58cdb8d
def get_user(email): <NEW_LINE> <INDENT> model = get_user_model() <NEW_LINE> return model.objects.get(email=email)
Return a user object by email lookup
625941f4009cb60464c639b9
def load(self): <NEW_LINE> <INDENT> if not super(IFCPOLYLOOP,self).load(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
register inverses
625941f4956e5f7376d71478
def key_name(name): <NEW_LINE> <INDENT> parsed = HumanName(name) <NEW_LINE> if len(parsed.first) > 0: <NEW_LINE> <INDENT> first_name = parsed.first[0] <NEW_LINE> key = f"{parsed.last.lower()} {first_name.lower()}" <NEW_LINE> return key <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return name.lower()
Return a key associated to the `name` passed in input.
625941f494891a1f4081c0b9
def xy_to_canvasxy(self,xy): <NEW_LINE> <INDENT> return ((xy[0]-self.orig_x)*self.scale_x+self.scale_offset_x, (xy[1]-self.orig_y)*-self.scale_y+self.scale_offset_y)
converts xy Pairs to pixle coordinates on the plot canvas
625941f401c39578d7e75448
def getLineTypeList(html,reg=['<li><span>.*?<\/li>', '(?<=>).*?<', '(?<==).*?>']): <NEW_LINE> <INDENT> allType = re.findall(reg[0], html)[0] <NEW_LINE> return [ city + '/' + x[:-1] for x in re.findall( reg[2], allType )]
This Function use to get all type of the line. return a list contain all href.
625941f426068e7796caf2f5
def is_alive(self): <NEW_LINE> <INDENT> if self.started: <NEW_LINE> <INDENT> return self.proc.poll() is None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Checks if the process is alive.
625941f410dbd63aa1bd31af
def __new__(meta, name, bases, attributes, traits=tuple()): <NEW_LINE> <INDENT> if traits: <NEW_LINE> <INDENT> trait_attributes = collections.defaultdict(list) <NEW_LINE> for trait in traits: <NEW_LINE> <INDENT> for attr_name, attr_value in trait.__attributes__: <NEW_LINE> <INDENT> trait_attributes[attr_name].append((t...
Compose a new class and return it.
625941f48e71fb1e9831ddb3
def GetKeyValue(self, key_path, key_name, use_64bit=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> handle = self._OpenSubKey(key_path, create=False, use_64bit=use_64bit) <NEW_LINE> result = self._winreg.QueryValueEx(handle, key_name)[0] <NEW_LINE> handle.Close() <NEW_LINE> return result <NEW_LINE> <DEDENT> except ...
function to retrieve a Windows registry value. Args: key_path: the key we'll search in (such as SOFTWARE\Microsoft) key_name: the key that we want to get our value from (such as ProgramFilesDir) use_64bit: use the 64bit registry rather than 32bit Returns: the value of the specified registry key. Raises...
625941f44e696a04525c9a5b
def process(self, chain, request:Request, requestCnt:RequestContent, response:Response, **keyargs): <NEW_LINE> <INDENT> assert isinstance(chain, Chain), 'Invalid processors chain %s' % chain <NEW_LINE> assert isinstance(request, Request), 'Invalid request %s' % request <NEW_LINE> assert isinstance(requestCnt, RequestCo...
@see: HandlerProcessor.process Parse the request object.
625941f4009cb60464c639ba
def _load_controllers(self, node): <NEW_LINE> <INDENT> dic = {} <NEW_LINE> transport_node = node.xpath('./Controllers') <NEW_LINE> if transport_node: <NEW_LINE> <INDENT> dic["Controllers"] = self._get_parameters(transport_node[0]) <NEW_LINE> <DEDENT> return dic
This function parses a "Controllers" XML Tags from a node into a dictionary :type node: DOM node :param node: the node from which to get all parameters value :rtype dic: dict :return: the dictionary of controllers
625941f4236d856c2ad44df1
def get_ionic(self, elem, ion): <NEW_LINE> <INDENT> if self.m[0].is_valid_ion(elem, ion): <NEW_LINE> <INDENT> if (elem, ion) not in self._ionic: <NEW_LINE> <INDENT> self._ionic[elem, ion] = self._get_3d("get_ionic('{0}', {1})".format(elem, ion)) <NEW_LINE> <DEDENT> return self._ionic[elem, ion] <NEW_LINE> <DEDENT> else...
Return the 3D cube of ionic fraction corresponding to elem, ion
625941f4d58c6744b425826a
def test_character_model_1(self): <NEW_LINE> <INDENT> data = peopledata <NEW_LINE> d = data['1'] <NEW_LINE> id = 1 <NEW_LINE> character = Character(id, d['name'], d['gender'], d['birth_year'], d['height'], d['mass'], "http://starwarscardtraderapp.com/wp-content/uploads/2015/12/99-1-7-Award-Luke-Skywalker.png") <NEW_LIN...
Test querying the database by attribute using simple keywords
625941f4f8510a7c17cf9d0e
def explicit_bucket_metadata(bucket_name : str, service_account_key_file : str): <NEW_LINE> <INDENT> storage_client = storage.Client.from_service_account_json(service_account_key_file) <NEW_LINE> bucket = storage_client.get_bucket(bucket_name) <NEW_LINE> print("ID: {}".format(bucket.id)) <NEW_LINE> print("Name: {}".for...
Prints out a bucket's metadata.
625941f463b5f9789fde76f3
@raises(TypeError) <NEW_LINE> def test_set_evaluation_concurrency_fails_if_float(): <NEW_LINE> <INDENT> m = Concrete() <NEW_LINE> value = 42.0 <NEW_LINE> m.evaluation_concurrency = value
Test that evaluation_concurrency fails with a float.
625941f4be383301e01b5a87
def qemu_iso_ram(self): <NEW_LINE> <INDENT> return self.qemu_ram_size(self.ui.combo_iso_boot_ram, "QEMU: ISO RAM = %s")
Choose a ram size for ISO booting. :return: Ram size as string.
625941f45166f23b2e1a5766
def get_free_register(registers_used): <NEW_LINE> <INDENT> for register in register_mapping.values(): <NEW_LINE> <INDENT> if register not in registers_used: <NEW_LINE> <INDENT> return register
Returns a register that is not in use
625941f430c21e258bdfaab2
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(PCANInfo, self).__init__(*args, **kwds) <NEW_LINE> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.ems1 is None: <NEW_LINE> <INDENT> self.ems1 = vehicle_msgs.msg....
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,ems1,ems5,tcu1,epb1,esc2,es...
625941f4596a89723608a0c5
def assert_file(self, file_name: str, list_expected: List[TypeVarOutputRowData]) -> None: <NEW_LINE> <INDENT> list_output_row_data: List[TypeVarOutputRowData] = self.read_output_csv(file_name) <NEW_LINE> assert len(list_output_row_data) == len( list_expected ), f"len(list_output_row_data) = {len(list_output_row_data)},...
This method checks Zaim CSV file.
625941f407d97122c4178ea8
def get_all_names(self) -> list[str]: <NEW_LINE> <INDENT> result = [ "get_session", "Session", ] <NEW_LINE> return list(sorted(result))
Get names for `__all__` directive.
625941f4de87d2750b8603a7
def timeseriesprocessing_exponentialaverage( source, data, name, output_data=None, model=None, decay=0.9, **params): <NEW_LINE> <INDENT> entrypoint_name = 'TimeSeriesProcessing.ExponentialAverage' <NEW_LINE> inputs = {} <NEW_LINE> outputs = {} <NEW_LINE> if source is not None: <NEW_LINE> <INDENT> inputs['Source'] = try...
**Description** Applies a Exponential average on a time series. :param source: The name of the source column (inputs). :param data: Input dataset (inputs). :param name: The name of the new column (inputs). :param decay: Coefficient d in: d m(y_t) = d * y_t + (1-d) * m(y_(t-1)), it should be in [0, 1]. (inputs)...
625941f4287bf620b61d406d
def create_asm(self, out=None, target_asm="dll", target_platform=None, embed=True, standalone=True, mta=False, delete_resp=True, executable=constants.EXECUTABLE, copy_ipydll=False): <NEW_LINE> <INDENT> if self.compilable_modules == set(): <NEW_LINE> <INDENT> self.check_compilability() <NEW_LINE> <DEDENT> if out is None...
Compile your scripts into a .NET assembly, using pyc.py. This method compiles the scripts by calling pyc.py. If :attr:`compilable_modules` is empty, the scripts will be analyzed using :meth:`check_compilability`. For the detail of compilation see the source code of pyc.py. :param str out: (optional) Specify the name ...
625941f4283ffb24f3c55f07
def set_all_reverse_geocodes(self, root): <NEW_LINE> <INDENT> return self.scan_do_local_files(root, func_do=self.reverse_geocode_images)
Scan all manifest files in local directories and set reverse geocode keys for nongeotagged images with nonzero latitude or longitude. gk = GeotagKeys() gk.set_all_reverse_geocodes(r'c:\SmugMirror\Mirror')
625941f4d7e4931a7ee9e52d
def calculate_distance_matrix(locations_at_iteration, clusters_for_distance): <NEW_LINE> <INDENT> locations_at_iteration['Key'] = 0 <NEW_LINE> clusters_for_distance['Key'] = 0 <NEW_LINE> locations_at_iteration_with_clusters = locations_at_iteration.merge(clusters_for_distance) <NEW_LINE> locations_at_iteration_with_clu...
Calculate distance matrix :param locations_at_iteration: :param clusters_for_distance: :return:
625941f4e8904600ed9f2545
def save_state(self, f_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> state = { k: self.__dict__[k] for k in ExperimentState.state_fields } <NEW_LINE> with open(f_name, "wb") as f: <NEW_LINE> <INDENT> pickle.dump(state, f) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("Save experiment state failed...
convenient for restoring halted experient
625941f42eb69b55b151cec6
def getDataForTraining(self, classNrs, targetNr=2): <NEW_LINE> <INDENT> sensorData = np.concatenate([self.fused, self.gyro, self.acc], axis=1) <NEW_LINE> i = 0 <NEW_LINE> target = np.copy(self.targets) <NEW_LINE> while i < len(self.targets): <NEW_LINE> <INDENT> tLen = 0 <NEW_LINE> while i < len(self.targets) and self.t...
Method to return data in a format ready to be used
625941f4fbf16365ca6f67df
def convert_to_node(value): <NEW_LINE> <INDENT> if isinstance(value, _CLASS_NODE_BASE): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if isinstance(value, bool): <NEW_LINE> <INDENT> return const(value, 'uint1x1') <NEW_LINE> <DEDENT> if isinstance(value, Number): <NEW_LINE> <INDENT> return const(value) <NEW_LINE>...
Convert a python value to corresponding node type. Parameters ---------- value : str The value to be inspected. Returns ------- node : Node The corresponding node value.
625941f4a4f1c619b28b0637
def operator(self, index): <NEW_LINE> <INDENT> index = self._mod_index(index) <NEW_LINE> flat_index = self._flatten_site_index(index) <NEW_LINE> x = self._xs[flat_index] <NEW_LINE> z = self._zs[flat_index] <NEW_LINE> if x == 1 and z == 1: <NEW_LINE> <INDENT> return 'Y' <NEW_LINE> <DEDENT> if x == 1: <NEW_LINE> <INDENT>...
Returns the operator on the site identified by the index. Notes: * Index is in the format (x, y). * Index is modulo lattice dimensions, i.e. on a (2, 2) lattice, (2, -1) indexes the same site as (0, 1). :param index: Index identifying a site in the format (x, y). :type index: 2-tuple of int :return: Pauli operator. ...
625941f4099cdd3c635f1265
def test_trie_size(trie): <NEW_LINE> <INDENT> trie.insert('money') <NEW_LINE> assert trie.size() == 1 <NEW_LINE> trie.insert('monkey') <NEW_LINE> assert trie.size() == 2
.
625941f4bde94217f36833f9
def test_pep8_base(self): <NEW_LINE> <INDENT> pep8style = pep8.StyleGuide(quiet=True) <NEW_LINE> result = pep8style.check_files(['tests/test_models/test_base.py']) <NEW_LINE> self.assertEqual(result.total_errors, 0, "Found code style errors (and warnings).")
Test the test file xD
625941f43d592f4c4ed1d66a
def test_humanify_filter_sensor(self): <NEW_LINE> <INDENT> entity_id = 'sensor.bla' <NEW_LINE> pointA = dt_util.utcnow().replace(minute=2) <NEW_LINE> pointB = pointA.replace(minute=5) <NEW_LINE> pointC = pointA + timedelta(minutes=logbook.GROUP_BY_MINUTES) <NEW_LINE> eventA = self.create_state_changed_event(pointA, ent...
Test humanify filter too frequent sensor values.
625941f430dc7b7665901f6d
def tweet_biorxiv_claim(mode='tweet', verbose=True, testing=False): <NEW_LINE> <INDENT> if mode == 'tweet': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if os.path.isfile(BIORXIV_PATH): <NEW_LINE> <INDENT> with open(BIORXIV_PATH, 'r') as f: <NEW_LINE> <INDENT> biorxiv_urls = json.loads(f.read()) <NEW_LINE> <DEDENT> <DE...
Run this function to tweet or reply to the original tweet of Biorxiv mode: str, 'tweet' for tweeting claim from new articles, 'reply' to reply with extracted claim tweeted by @biorxivpreprint verbose: bool, if True, print the tweet text testing: bool, if True, will not tweet out
625941f47cff6e4e81117f93
def push(self, d): <NEW_LINE> <INDENT> width, _, _ = d.shapesize() <NEW_LINE> y_offset = width / 2 * 20 <NEW_LINE> d.sety(self.y + y_offset) <NEW_LINE> d.setx(self.x + 34 * len(self)) <NEW_LINE> self.append(d)
Objective : pushing frame
625941f4046cf37aa974d34f
def _get_mapping(self, port_index, port_descr): <NEW_LINE> <INDENT> port_id = None <NEW_LINE> try: <NEW_LINE> <INDENT> ent_alias_mapping_identifier = self.snmp.get(('ENTITY-MIB', 'entAliasMappingIdentifier', port_index, 0)) <NEW_LINE> port_id = int(ent_alias_mapping_identifier['entAliasMappingIdentifier'].split('.')[-1...
Get mapping from entPhysicalTable to ifTable. Build mapping based on ent_alias_mapping_table if exists else build manually based on entPhysicalDescr <-> ifDescr mapping. :return: simple mapping from entPhysicalTable index to ifTable index: | {entPhysicalTable index: ifTable index, ...}
625941f467a9b606de4a84c4
def conj(input, name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> _, _, _op = _op_def_lib._apply_op_helper( "Conj", input=input, name=name) <NEW_LINE> _result = _op.outputs[:] <NEW_LINE> _inputs_flat = _op.inputs <NEW_LINE> _attr...
Returns the complex conjugate of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of complex numbers that are the complex conjugate of each element in `input`. The complex numbers in `input` must be of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginar...
625941f48e05c05ec3eea988
def test_return_service_02(fixture_json_file_path, fixture_loadandparse_json_instance): <NEW_LINE> <INDENT> load_and_parser_json = LoadAndParseJson() <NEW_LINE> load_and_parser_json.load_file(fixture_json_file_path) <NEW_LINE> returned_service = load_and_parser_json.return_signal_by_title( fixture_loadandparse_json_ins...
Action : Test the server correct service return. Expected Results : Test finished with status "Passed". Returns: N/A.
625941f4ec188e330fd5ad9f
def store(self): <NEW_LINE> <INDENT> return True
Interface method for StorageHandler
625941f4f9cc0f698b140c03
def read_user_config(path): <NEW_LINE> <INDENT> if not path: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> config_path = os.path.join(path, "config") <NEW_LINE> if not os.path.exists(config_path): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(config_path, "r", encoding='utf-8'...
Parse and store the user config settings in electrum_spectrumcash.conf into user_config[].
625941f4b7558d58953c5514
@functools.lru_cache(maxsize=1) <NEW_LINE> def iter_modules_and_files(modules, extra_files): <NEW_LINE> <INDENT> sys_file_paths = [] <NEW_LINE> for module in modules: <NEW_LINE> <INDENT> if not isinstance(module, ModuleType) or getattr(module, '__spec__', None) is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ...
Iterate through all modules needed to be watched.
625941f45fdd1c0f98dc0843
def get_pages(self) -> List[str]: <NEW_LINE> <INDENT> with open('json_data/pages.json') as pages: <NEW_LINE> <INDENT> pages_list = json.load(pages) <NEW_LINE> <DEDENT> return pages_list
Реализация метода получения списка страниц из json-файла.
625941f432920d7e50b287e3
def open_mseed(self, f): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sound = read(f)[0] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print("Cannot read mseed. Maybe a bad url?") <NEW_LINE> <DEDENT> sound = read(f)[0] <NEW_LINE> self.data = (sound.normalize() * (2 ** 31 - 1)).astype("int32") <NEW_LINE> se...
Loads mseed file data into class from the given file-like object or path, f.
625941f4099cdd3c635f1266
def check_neighbors(self,arr, location, criteria, cols=1, non_binary=False): <NEW_LINE> <INDENT> if non_binary == True: <NEW_LINE> <INDENT> total = 0 <NEW_LINE> <DEDENT> neighbors_sick = False <NEW_LINE> try: <NEW_LINE> <INDENT> if arr[location[0] + 1][location[1]] in criteria: <NEW_LINE> <INDENT> neighbors_sick = True...
checks whether any of the neigbors are sick, if non_binary = False : if yes return true if non_binary = True : returns total number of sick neighbors
625941f4f9cc0f698b140c04
def get_detail_view_name(model): <NEW_LINE> <INDENT> return '%(model_name)s-detail' % { 'model_name': model._meta.object_name.lower() }
Given a model class, return the view name to use for URL relationships that refer to instances of the model.
625941f423849d37ff7b3698
def add_view(self, view): <NEW_LINE> <INDENT> if view.webview.uri: <NEW_LINE> <INDENT> self.__loaded_uri(view.webview, view.webview.uri) <NEW_LINE> <DEDENT> view.webview.connect("load-changed", self.__on_webview_load_changed) <NEW_LINE> view.connect("destroying", self.__on_view_destroying)
Add a new view to monitor @param view as View
625941f48e7ae83300e4b5dd
def test_can_access_with_access_profile_that_does_not_include_application(self): <NEW_LINE> <INDENT> app = ApplicationFactory() <NEW_LINE> user = UserFactory() <NEW_LINE> ap = AccessProfile.objects.create(name="test profile") <NEW_LINE> ap.oauth2_applications.add(app) <NEW_LINE> ap2 = AccessProfile.objects.create(name=...
The user has an access profile but it doesn't provide access to the app
625941f46fece00bbac2dd54
def test_put_counter_not_found(self): <NEW_LINE> <INDENT> resp = self.app.put("/counters/foo") <NEW_LINE> self.assertEquals(resp.status_code, 404)
Test counter not found
625941f45510c4643540f9e2
def entry(): <NEW_LINE> <INDENT> args = parse_arguments(sys.argv[1:]) <NEW_LINE> account_summary = [] <NEW_LINE> try: <NEW_LINE> <INDENT> if args.multiple > 1 and args.username is not None: <NEW_LINE> <INDENT> raise ValueError("Username cannot be set if --multiple is greater than 1!") <NEW_LINE> <DEDENT> if args.email ...
Main entry point for the package console commands
625941f455399d3f05588cc7