code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@match_role("healthprovider") <NEW_LINE> def account_speciality(request): <NEW_LINE> <INDENT> u = Provider.objects.filter(poc__email=request.session['email']).first() <NEW_LINE> s = u.specialities.all() <NEW_LINE> class SpecialityForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Special...
route for account - speciality
625941d766656f66f7cbc3fd
def __init__(self, complex_type, *args, native=False, doc=""): <NEW_LINE> <INDENT> self._complex_type = complex_type <NEW_LINE> if len(args) >= 1 and isinstance(args[0], str): <NEW_LINE> <INDENT> self._complex_type_name = args[0] <NEW_LINE> args = args[1:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._complex_typ...
Define a complex type. Parameters ---------- complex_type : str The type of complex type (e.g. 'struct' or 'union'). complex_type_name : str The name of the complex type (e.g. if complex_type is 'struct' and complex_type_name is 'foo', the new type is called 'struct foo'). If omitted, the type will be ...
625941d7a4f1c619b28b0286
def sprout(): <NEW_LINE> <INDENT> global newBranches <NEW_LINE> global oldBranches <NEW_LINE> global allBranches <NEW_LINE> newBranches = [] <NEW_LINE> for branch in oldBranches: <NEW_LINE> <INDENT> branchA = Branch(branch.budX, branch.budY,incBranch(branch.direction)) <NEW_LINE> branchB = Branch(branch.budX, branch.bu...
Create new branches at the tips of the last generation of branches.
625941d799fddb7c1c9de5e2
def requete_verifier(event): <NEW_LINE> <INDENT> texte = requete.get("1.0", "end") <NEW_LINE> lettres = caracteres(texte) <NEW_LINE> data = Database.database(base) <NEW_LINE> if data.execute(texte) == None: <NEW_LINE> <INDENT> renseignement[2] = False <NEW_LINE> r_texte.set("La requete n'est pas valide, veuillez corrig...
sous-fonction qui permet de vérifier que le champs pour la requete est correcte
625941d707f4c71912b116d5
def complete(request, provider): <NEW_LINE> <INDENT> data = request.GET.copy() <NEW_LINE> data.update(request.POST) <NEW_LINE> backend = get_backend(provider) <NEW_LINE> response = backend.validate(request, data) <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> backend.login_user(request) <NEW_LINE> b...
After first step of public authentication, we must validate the response. If everything is ok, we must do the following: 1. If user is already authenticated: a. Try to login him again (strange variation but we must take it to account). b. Create new PublicID record in database. c. Merge authenticated accou...
625941d7293b9510aa2c34e5
@app.route("/<username>/<message>") <NEW_LINE> def send_message(username, message): <NEW_LINE> <INDENT> add_messages(username, message) <NEW_LINE> return redirect("/" + username)
Create a new message and redirect to chat page
625941d73539df3088e2e59c
def tometadata(self, metadata, schema=RETAIN_SCHEMA): <NEW_LINE> <INDENT> if schema is RETAIN_SCHEMA: <NEW_LINE> <INDENT> schema = self.schema <NEW_LINE> <DEDENT> elif schema is None: <NEW_LINE> <INDENT> schema = metadata.schema <NEW_LINE> <DEDENT> key = _get_table_key(self.name, schema) <NEW_LINE> if key in metadata.t...
Return a copy of this :class:`.Table` associated with a different :class:`.MetaData`. E.g.:: some_engine = create_engine("sqlite:///some.db") # create two metadata meta1 = MetaData() meta2 = MetaData() # load 'users' from the sqlite engine users_table = Table('users', meta1, autoload=True, ...
625941d70a366e3fb873ea6d
def domainXMLFromNative(self, nativeFormat, nativeConfig, flags=0): <NEW_LINE> <INDENT> ret = libvirtmod.virConnectDomainXMLFromNative(self._o, nativeFormat, nativeConfig, flags) <NEW_LINE> if ret is None: raise libvirtError ('virConnectDomainXMLFromNative() failed', conn=self) <NEW_LINE> return ret
Reads native configuration data describing a domain, and generates libvirt domain XML. The format of the native data is hypervisor dependent.
625941d756b00c62f0f148ac
def test_barray_record(self): <NEW_LINE> <INDENT> src_data = [(i, 's'*i) for i in range(10)] <NEW_LINE> self.assertRaises(TypeError, blz.barray, src_data, dtype=np.dtype('O,O'))
Testing barray handling of record dtypes containing objects. They must raise a type error exception, as they are not supported
625941d726238365f5f0f0c2
def add_extra_filter(self, method, expression): <NEW_LINE> <INDENT> efilters = self.efilters <NEW_LINE> efilters.append((method, expression)) <NEW_LINE> return efilters
Add an extra filter Args: method: a name of a known filter method, or a callable filter method expression: the filter expression (string)
625941d732920d7e50b28423
def cudnnSoftmaxForward(handle, algorithm, mode, alpha, srcDesc, srcData, beta, destDesc, destData): <NEW_LINE> <INDENT> status = _libcudnn.cudnnSoftmaxForward(handle, algorithm, mode, ctypes.byref(ctypes.c_float(alpha)), srcDesc, srcData, ctypes.byref(ctypes.c_float(beta)), destDesc, destData) <NEW_LINE> cudnnCheckSta...
" This routing computes the softmax function Parameters ---------- handle : cudnnHandle Handle to a previously created cuDNN context. algorithm : cudnnSoftmaxAlgorithm Enumerant to specify the softmax algorithm. mode : cudnnSoftmaxMode Enumerant to specify the softmax mode. alpha: float Scaling factor ...
625941d7bd1bec0571d90881
def test_get_item_xpath(self): <NEW_LINE> <INDENT> original_path = '{"itemPath": "./Section[@name=\'Body\'][@id=\'section_07\']", "FieldsToExtract": []}' <NEW_LINE> embark_field_definitions = json.loads(original_path) <NEW_LINE> item_xpath = get_embark_xml_definitions.get_item_xpath(embark_field_definitions) <NEW_LI...
test retrieving known item xpath
625941d7377c676e912723fa
def find_spt(digraph, root): <NEW_LINE> <INDENT> spt = nx.Graph() <NEW_LINE> s1 = {root} <NEW_LINE> s2 = set(G.nodes()) <NEW_LINE> s2.remove(root) <NEW_LINE> while s2: <NEW_LINE> <INDENT> nodes_from_s2_to_s1 = set() <NEW_LINE> direct_reachable_nodes = set() <NEW_LINE> for _s in s1: <NEW_LINE> <INDENT> for _i in digraph...
Finding the shortest-path-tree See algorithm here: https://web.archive.org/web/20200124171216/http://www.me.utexas.edu/~jensen/exercises/mst_spt/spt_demo/spt1.html (Original link is dead: http://www.me.utexas.edu/~jensen/exercises/mst_spt/spt_demo/spt1.html) :param digraph: graph :param root: root node :return: spt
625941d7a934411ee37518e5
def get_forecast(self, config: Config) -> Forecast: <NEW_LINE> <INDENT> latitude = config.get("latitude") <NEW_LINE> longitude = config.get("longitude") <NEW_LINE> api_key = config.get("openweather_api_key") <NEW_LINE> api_response = cherrypy.engine.publish( "urlfetch:get:json", "https://api.openweathermap.org/data/2.5...
Request current weather data from OpenWeather.
625941d767a9b606de4a810a
def config_exists(self): <NEW_LINE> <INDENT> return os.path.exists(self.CONFIG_PATH)
Returns True if config exists. :return:
625941d7baa26c4b54cb136f
def get_output_panel(self): <NEW_LINE> <INDENT> win = self.view.window() <NEW_LINE> view = win.find_output_panel('raw_line_edit_view') <NEW_LINE> if view is not None: <NEW_LINE> <INDENT> win.destroy_output_panel('raw_line_edit_view') <NEW_LINE> <DEDENT> return win.get_output_panel('raw_line_edit_view')
Get output panel.
625941d75fc7496912cc3bd0
def test_issue_paging(self): <NEW_LINE> <INDENT> from factories import OrganizationFactory, ProjectFactory <NEW_LINE> organization = OrganizationFactory(name=u'Code for America', projects_list_url=u'http://codeforamerica.org/projects.csv') <NEW_LINE> project = ProjectFactory(organization_name=u'Code for America',code_u...
test that issues are following page links
625941d7287bf620b61d3cb4
def remove_connection(self, connection_id: str) -> None: <NEW_LINE> <INDENT> for connection in self.connections: <NEW_LINE> <INDENT> if connection.ID == connection_id: <NEW_LINE> <INDENT> self.connections.remove(connection) <NEW_LINE> if connection.source is not None: <NEW_LINE> <INDENT> for sink in connection.sinks: <...
Removes a connection object from the device Args: connection_id (str): ID of the connection to be removed Raises: Exception: Raises the error if the connection is not found in the device
625941d791f36d47f21ac746
def supervisorctl(task): <NEW_LINE> <INDENT> with prefix('workon %s' % VIRTUAL_ENV_NAME): <NEW_LINE> <INDENT> run('supervisorctl -c "%s/etc/supervisor.conf" %s %s' % (HOME, task, SITE_NAME))
Controls the supervisor.
625941d750812a4eaa59c572
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs: <NEW_LINE> <INDENT> for k, v in kwargs.items(): <NEW_LINE> <INDENT> if k == 'created_at' or k == 'updated_at': <NEW_LINE> <INDENT> kwargs[k] = datetime.strptime(v, "%Y-%m-%dT%H:%M:%S.%f") <NEW_LINE> setattr(self, k, kwargs[k]) <NEW_LINE> <DEDENT> if k ...
Init
625941d7a79ad161976cc398
def jacobian_dxdy(deflectx,deflecty,ratio=1,dunit=1): <NEW_LINE> <INDENT> with warnings.catch_warnings(): <NEW_LINE> <INDENT> warnings.simplefilter('ignore') <NEW_LINE> dDXdy,dDXdx = np.gradient(deflectx*ratio/dunit) <NEW_LINE> dDYdy,dDYdx = np.gradient(deflecty*ratio/dunit) <NEW_LINE> A = (1-dDXdx)*(1-dDYdy)-dDXdy*dDY...
computes the determanant of the Jacobian matrix from deflection matrices
625941d7a934411ee37518e6
def epoch(self): <NEW_LINE> <INDENT> epc = int(time.time() * 1000) <NEW_LINE> return epc
Returns System Time :return:
625941d7498bea3a759b9d01
def print_hyperparameter_data_result(result): <NEW_LINE> <INDENT> print("Goal: {}".format(result["goal"])) <NEW_LINE> print("Trial count: {}".format(result["trialCount"])) <NEW_LINE> print("Best trial:") <NEW_LINE> print("{:8} Metrics: {}".format("", result["best_trials"]["metric"])) <NEW_LINE> print("{:8} Params: {}"....
Print the hyperparameter result in customed format. Args: result: The result. Example: {"best_trials": {}, "goal": "MINIMIZE", "trialCount": 4, "trial": [{}]} Each trial contains {"metric": 0.08, "params": "--foo=bar", "step": 100}
625941d794891a1f4081bcfc
def query_5_b(bn): <NEW_LINE> <INDENT> probs = {} <NEW_LINE> data_point = [2,'G','Typical','BP','H','Normal','H','Y','N'] <NEW_LINE> for i, point in enumerate(data_point): <NEW_LINE> <INDENT> if point in bn.map_for_key: data_point[i] = bn.map_for_key[point] <NEW_LINE> <DEDENT> data_point_1 = data_point[:] <NEW_LINE> da...
Please write a method which returns an answer to query 5b from the problem set input: - bn: a parameterized Bayes Net returns: answers, a dictionary with two keys, "H" and "L". "H" is the probability of high BP given the specified conditions. "L" is the probability of low BP, given the specified condit...
625941d74d74a7450ccd4415
def p_inheritance(self, p): <NEW_LINE> <INDENT> if p[1]: <NEW_LINE> <INDENT> if p[2].nullable: <NEW_LINE> <INDENT> msg = 'Reference cannot be nullable.' <NEW_LINE> self.errors.append((msg, p.lineno(1), self.path)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = p[2]
inheritance : EXTENDS type_ref | empty
625941d7be8e80087fb20e92
def rewrite_table_arc(self, name_tbl, name_list): <NEW_LINE> <INDENT> r_rewrt_tbl = [0, ''] <NEW_LINE> try: <NEW_LINE> <INDENT> self.conn = sqlite3.connect(self.path_db) <NEW_LINE> self.cur = self.conn.cursor() <NEW_LINE> self.cur.execute("DELETE FROM " + name_tbl) <NEW_LINE> self.cur.executemany("INSERT INTO " + name_...
rewrite data from table ARCHIV_PACK & PACK_TODAY --------
625941d7ac7a0e7691ed431b
def save(self): <NEW_LINE> <INDENT> with open('./cmu_weights.pkl','wb') as f: <NEW_LINE> <INDENT> pickle.dump(self.cum_weights,f)
DO NOT DELETE
625941d799fddb7c1c9de5e3
def filter_whitelist_errors(data, errors): <NEW_LINE> <INDENT> if not errors: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> whitelisted = [False for item in range(len(errors))] <NEW_LINE> for i, (error_type, msg, path, line) in enumerate(errors): <NEW_LINE> <INDENT> normpath = os.path.normcase(path) <NEW_LINE> if e...
Filter out those errors that are whitelisted in `data`.
625941d75f7d997b87174cec
def __init__(self, evaluate, initial_param_gen, temp_schedule=None, w_gamma=1., accept_probability=None, num_axes_to_update=1, **kwargs): <NEW_LINE> <INDENT> super().__init__(evaluate, initial_param_gen, **kwargs) <NEW_LINE> self.temp = temp_schedule if temp_schedule else lambda t: w_gamma / np.log(t + 2) <NEW_LINE> se...
Simulated Annealing Optimizer Parameters ---------- temp_schedule : function(int) -> float a function that takes as input the current iteration and outputs the desired temperature for that iteration. Defaults to gamma / log(iteration + 2) w_gamma : float initial multiplier for gamma function. Used in the d...
625941d74e696a04525c969e
def pc_output_buffers_full_var(self, *args): <NEW_LINE> <INDENT> return _blocks_swig5.tagged_stream_mux_sptr_pc_output_buffers_full_var(self, *args)
pc_output_buffers_full_var(tagged_stream_mux_sptr self, int which) -> float pc_output_buffers_full_var(tagged_stream_mux_sptr self) -> pmt_vector_float
625941d721a7993f00bc7f45
def binary_intercept(*, func: Callable[[float], float], start_x: float, step: float, target_y: float, atol: float) -> float: <NEW_LINE> <INDENT> start_y = func(start_x) <NEW_LINE> if abs(start_y - target_y) <= atol: <NEW_LINE> <INDENT> return start_x <NEW_LINE> <DEDENT> while (func(start_x + step) >= target_y) == (star...
Performs an approximate granular binary search over a monotonically ascending function.
625941d785dfad0860c3b0ae
def translate(self, point): <NEW_LINE> <INDENT> L = np.matrix(np.matrix([self.A, self.B, self.C]).transpose()) <NEW_LINE> a_ = np.matrix(point).transpose() <NEW_LINE> a = L * a_ <NEW_LINE> return np.array((a.transpose() + self.X))[0]
Переносит модель в нужную позицию в данных
625941d7956e5f7376d710be
def check(self): <NEW_LINE> <INDENT> s=self.scene <NEW_LINE> src = s.children[0] <NEW_LINE> i1, i2, i3 = src.children[0].children[1:] <NEW_LINE> self.assertEqual(i1.ipw.plane_orientation,'x_axes') <NEW_LINE> self.assertEqual(numpy.allclose(i1.ipw.center, (0, 31.5, 31.5)),True) <NEW_LINE> self.assertEqual( i2.ipw.plane_...
Do the actual testing.
625941d75fcc89381b1e1913
def tap_select_callback(attr, old, new): <NEW_LINE> <INDENT> new_index = new['1d']['indices'][0] <NEW_LINE> md_key = source.data['metadata_key'][new_index] <NEW_LINE> print(f'md key: {md_key}') <NEW_LINE> layout.children[1].children[2] = build_metadata_paragraph(md_key)
The callback function for when a user uses the TapTool to select a single data point.
625941d77047854f462a165a
def test_terminal_tab_title(setup_terminal, qtbot_module): <NEW_LINE> <INDENT> terminal = setup_terminal <NEW_LINE> qtbot_module.waitUntil( lambda: terminal.get_widget().server_is_ready(), timeout=TERM_UP) <NEW_LINE> qtbot_module.wait(1000) <NEW_LINE> terminal.create_new_term() <NEW_LINE> terminal.create_new_term() <NE...
Test if terminal tab titles are numbered sequentially.
625941d75fdd1c0f98dc0486
@pytest.mark.skipif( SKIP_PRIVATE or SKIP_CODECS or not imagecodecs.JPEG, reason=REASON ) <NEW_LINE> def test_read_zif(): <NEW_LINE> <INDENT> fname = private_file('zif/ZoomifyImageExample.zif') <NEW_LINE> with TiffFile(fname) as tif: <NEW_LINE> <INDENT> assert len(tif.pages) == 5 <NEW_LINE> assert len(tif.series) == 1 ...
Test read Zoomable Image Format ZIF.
625941d7baa26c4b54cb1370
def create_inactive_user(self, username, email, password, site, send_email=True): <NEW_LINE> <INDENT> from django.contrib.auth import get_user_model <NEW_LINE> User = get_user_model() <NEW_LINE> new_user = User.objects.create_user(username, email, password) <NEW_LINE> new_user.is_active = False <NEW_LINE> new_user.save...
Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``.
625941d79f2886367277aade
def compile_func(ast_node, filename, globals, **defaults): <NEW_LINE> <INDENT> funcion_name = ast_node.name <NEW_LINE> module = _ast.Module(body=[ast_node]) <NEW_LINE> ctx = {} <NEW_LINE> for key, arg in defaults.iteritems(): <NEW_LINE> <INDENT> ctx['%s_default' % key] = arg <NEW_LINE> <DEDENT> code = compile(module, f...
Compile a function from an ast.FunctionDef instance. :param ast_node: ast.FunctionDef instance :param filename: path where function source can be found. :param globals: will be used as func_globals :return: A python function object
625941d7a219f33f34628bb9
def perform_destroy(self, instance): <NEW_LINE> <INDENT> if self.push_deletions: <NEW_LINE> <INDENT> self.push_changes(self.PUSH_DELETE, instance, pre_destroy=True) <NEW_LINE> <DEDENT> super().perform_destroy(instance)
Sends the pusher event and then destroys the object This is done to ensure the serialization can occur
625941d723849d37ff7b32e0
def TotalSpace(self,value): <NEW_LINE> <INDENT> self.RecordData = self.AddToList(self.RecordData, "TotalSpace", "", str(value))
Total space (GB)
625941d726068e7796caef34
def get_timestamp(past: int = 0, future: int = 0, time_zone: str = 'local') -> str: <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> now += timedelta(minutes=future) <NEW_LINE> now -= timedelta(minutes=past) <NEW_LINE> if time_zone is None: <NEW_LINE> <INDENT> return now.isoformat()[:19] <NEW_LINE> <DEDENT> else: <N...
Get an ISO formatted timestamp. Args: past (int): Number of minutes in the past to get a timestamp. future (int): Number of minutes into the future to get a timestamp. # TODO: Set time in timezone of state (e.g. {'state': 'OK'} -> CDT)
625941d7a8ecb033257d331f
def calculate_awards_value(row): <NEW_LINE> <INDENT> if not row['EndOfSeason']: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> awards_value = 0 <NEW_LINE> if row['PlayerID'] in all_stars: <NEW_LINE> <INDENT> awards_value += all_star_value <NEW_LINE> <DEDENT> for team in ['1st', '2nd', '3rd']: <NEW_LINE> <INDENT> if r...
how much do we award a player in terms of all stars, mvps, and finals mvps?
625941d71f5feb6acb0c4da0
def test_missing_show(self): <NEW_LINE> <INDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> self.showview.get_show('NotExisting')
try to get a show that doesn't exist
625941d756ac1b37e626441f
def baz(a, b): <NEW_LINE> <INDENT> if type(a) is not Tensor or type(b) is not Tensor and has_torch_function((a, b)): <NEW_LINE> <INDENT> return handle_torch_function(baz, (a, b), a, b) <NEW_LINE> <DEDENT> return a + b
A function with multiple arguments
625941d73eb6a72ae02ec734
def reap(self): <NEW_LINE> <INDENT> while self._running: <NEW_LINE> <INDENT> dead = set() <NEW_LINE> for job in self._running: <NEW_LINE> <INDENT> st = job.state(self._cache) <NEW_LINE> if st == _RUNNING: continue <NEW_LINE> if st == _FAILURE: self._failures += 1 <NEW_LINE> dead.add(job) <NEW_LINE> <DEDENT> for job in ...
Collect the dead jobs.
625941d760cbc95b062c6796
def test_reverse_delete_rule_cascade_cycle(self): <NEW_LINE> <INDENT> class Dummy(Document): <NEW_LINE> <INDENT> reference = ReferenceField("self", reverse_delete_rule=CASCADE) <NEW_LINE> <DEDENT> base = Dummy().save() <NEW_LINE> other = Dummy(reference=base).save() <NEW_LINE> base.reference = other <NEW_LINE> base.sav...
Ensure reference cascading doesn't loop if reference graph isn't a tree
625941d74e4d5625662d4628
def writePotential(self, filename): <NEW_LINE> <INDENT> path = os.path.join(self.getSimulationFolder(), filename) <NEW_LINE> GPEPython.writePotential(self, path)
write 1D and 2D projections of the external potential
625941d7bde94217f3683042
def new(self, obj): <NEW_LINE> <INDENT> FileStorage.__objects['{}.{}'.format(obj.__class__.__name__, obj.id)] = obj
set in '__objects' the obj with key '<obj class name>.id'
625941d792d797404e3043dd
def GOE(N): <NEW_LINE> <INDENT> m = ra.standard_normal((N,N)) <NEW_LINE> m += m.T <NEW_LINE> return m
Creates an NxN element of the Gaussian Orthogonal Ensemble
625941d7d10714528d5fff38
def store_orig_strings(self, example_list): <NEW_LINE> <INDENT> self.original_reviews = [ex.original_reviews for ex in example_list] <NEW_LINE> self.original_answers = [ex.original_answer for ex in example_list] <NEW_LINE> self.original_questions = [ex.original_question for ex in example_list] <NEW_LINE> self.original_...
Store the original article and abstract strings in the Batch object
625941d730c21e258bdfa6f1
def get_runlist(metadata, kind, options): <NEW_LINE> <INDENT> runlist = list() <NEW_LINE> try: <NEW_LINE> <INDENT> metadata_list = get_content(metadata, kind, 'MetaList') <NEW_LINE> <DEDENT> except (error.WrongType, error.MissingField) as err: <NEW_LINE> <INDENT> info.log('WARNING', 'panzer', err) <NEW_LINE> return run...
return run list for kind from metadata
625941d7e8904600ed9f2182
def countPlayers(): <NEW_LINE> <INDENT> db, c = connect() <NEW_LINE> c.execute("SELECT count(*) FROM players;") <NEW_LINE> result = c.fetchone()[0] <NEW_LINE> db.close() <NEW_LINE> return result
Returns the number of players currently registered.
625941d7d53ae8145f87a4bf
def get_entry_group( self, name, read_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): <NEW_LINE> <INDENT> if "get_entry_group" not in self._inner_api_calls: <NEW_LINE> <INDENT> self._inner_api_calls[ "get_entry_group" ] = google.api_core.gapic...
Alpha feature. Gets an EntryGroup. Example: >>> from google.cloud import datacatalog_v1beta1 >>> >>> client = datacatalog_v1beta1.DataCatalogClient() >>> >>> name = client.entry_group_path('[PROJECT]', '[LOCATION]', '[ENTRY_GROUP]') >>> >>> response = client.get_entry_group(name) Args: ...
625941d78a43f66fc4b542b6
def _calc_concat_dim_coord(dim): <NEW_LINE> <INDENT> if isinstance(dim, basestring): <NEW_LINE> <INDENT> coord = None <NEW_LINE> <DEDENT> elif not hasattr(dim, 'dims'): <NEW_LINE> <INDENT> dim_name = getattr(dim, 'name', None) <NEW_LINE> if dim_name is None: <NEW_LINE> <INDENT> dim_name = 'concat_dim' <NEW_LINE> <DEDEN...
Infer the dimension name and 1d coordinate variable (if appropriate) for concatenating along the new dimension.
625941d70a50d4780f6670e7
def for_user(self, user): <NEW_LINE> <INDENT> if user.is_anonymous(): <NEW_LINE> <INDENT> return self.filter( Q(status=STATUS.active) & Q(isprivate=False) ).distinct() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> projects = (self .filter( Q(admins=user) | ( Q(status=STATUS.active) & ( Q(isprivate=False) | Q(usergroups...
Returns the projects for the user. For anonymous users: Returns all projects that are public and have at least one public data grouping. For authenticated users: Returns all projects that - are public - all projects the user can contribute or moderate Parameter --------- user : geokey.use...
625941d7d53ae8145f87a4c0
def _avro_producer(self, schema_registry: str, bootstrap_servers: str, namespace: str): <NEW_LINE> <INDENT> warnings.warn("Experimental. Please do not use, needs adaptations") <NEW_LINE> schema_registry_client = SchemaRegistryClient({"url": schema_registry}) <NEW_LINE> avro_serializer = AvroSerializer( schema_str=Schem...
onfigures a AVRO serializing producer to be used along with schema registry :param schema_registry: :param bootstrap_servers: :param namespace: :return:
625941d75166f23b2e1a53ac
def preview_string(self, page, format='png', dpi=72, background_colour=0xFFFFFF): <NEW_LINE> <INDENT> if page < 1 or page > self.page_count: <NEW_LINE> <INDENT> raise ValueError("Invalid page number; should be between 1 and {0:d}.".format(self.page_count)) <NEW_LINE> <DEDENT> self._shade_remaining_missing() <NEW_LINE> ...
Render a preview image of a page as a string. Parameters ---------- page: positive integer Which page to render. Must be in the range [1, page_count] format: string The image format to use for the preview. ReportLab uses the Python Imaging Library (PIL) internally, so any PIL format should be supported...
625941d7956e5f7376d710bf
@fbuild.db.caches <NEW_LINE> def guess_platform(ctx, arch=None): <NEW_LINE> <INDENT> ctx.logger.check('determining platform') <NEW_LINE> if arch is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> uname = fbuild.builders.find_program(ctx, ['uname'], quieter=1) <NEW_LINE> <DEDENT> except fbuild.builders.MissingProgram...
L{guess_platform} returns a platform set that describes the various features of the specified I{platform}. If I{platform} is I{None}, try to determine which platform the system is and return that value. If the platform cannot be determined, return I{None}.
625941d7f8510a7c17cf9950
def create_builtin(*args, **kwargs): <NEW_LINE> <INDENT> pass
Create an extension module.
625941d73cc13d1c6d3c75cc
def clean_site(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return self.endpoint_a.site_id <NEW_LINE> <DEDENT> return value
Always enforce that site is set.
625941d7d486a94d0b98e399
def run_xsim(args): <NEW_LINE> <INDENT> sims = find_xsims() <NEW_LINE> result_all = 0 <NEW_LINE> if not isinstance(args.target, list): <NEW_LINE> <INDENT> args.target = [args.target] <NEW_LINE> <DEDENT> if "cleanall" in args.target: <NEW_LINE> <INDENT> env = os.environ <NEW_LINE> env["REPO_BASE_PATH"] = _BASE_DIR <NEW_...
Run xsim for all specified modules
625941d7d18da76e2353272b
def find_attribute(self, key): <NEW_LINE> <INDENT> return self._ATTRIBUTES.get(key, None)
Find a Gripy attribute inside _ATTRIBUTES structure.
625941d7fff4ab517eb2f690
def __init__(self, require_root: bool = True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> if require_root: <NEW_LINE> <INDENT> if not os.geteuid() != 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> msg = 'Requires root, exiting' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if os.envir...
Can bypass not allowing root to run scripts by setting env var PY_IGNORE_ROOT_CHECK :param require_root: If True, running as root is required otherwise will terminate. If False, running as root will terminate.
625941d7090684286d50ef3a
def random_odd_arithgroup(index,nu3_max=None): <NEW_LINE> <INDENT> assert index%4 == 0 <NEW_LINE> G = random_even_arithgroup(index//2,nu2_max=0,nu3_max=nu3_max) <NEW_LINE> return G.one_odd_subgroup(random=True)
Return a random odd arithmetic subgroup EXAMPLES:: sage: from sage.modular.arithgroup.tests import random_odd_arithgroup sage: G = random_odd_arithgroup(20); G #random Arithmetic subgroup of index 20 sage: G.is_odd() True
625941d7d268445f265b50c1
def get_summonerbyname(self, summonername): <NEW_LINE> <INDENT> url = self._formurlforcall(url=self._API_summonerbyname, summonername=summonername) <NEW_LINE> status_code, text = self._pullfromapi(url, 'get_summonerbyname') <NEW_LINE> return status_code, text
Retrieve information for a particular summoner. Returns status_code, text (JSON). Use output= to redirect the output to this location rather than by using the standard return.
625941d750812a4eaa59c573
def test_query_courses_children_aggs_over_aggs_list(self, *_): <NEW_LINE> <INDENT> data = self.prepare_indices() <NEW_LINE> response = self.client.get( ( "/api/v1.0/courses/?subjects_aggs=" f"{data['subject_0_children'][0].get_es_id()}" "&subjects_aggs=" f"{data['subject_0_children'][1].get_es_id()}" "&subjects_childre...
When both [filter]_children_aggs and [filter]_aggs, two conflicting aggregations-related parameters, are present in a query, [filter]_children_aggs should take precedence.
625941d7b545ff76a8914069
def testCertificateData(self): <NEW_LINE> <INDENT> model = artikcloud.models.certificate_data.CertificateData()
Test CertificateData
625941d7097d151d1a2230ab
def _ensure_config(depc, tablekey, config, _debug=False): <NEW_LINE> <INDENT> configclass = depc.configclass_dict.get(tablekey, None) <NEW_LINE> if configclass is None: <NEW_LINE> <INDENT> config_ = config <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config_ = None <NEW_LINE> if config is None: <NEW_LINE> <INDENT> con...
Creates a full table configuration with all defaults using config Args: tablekey (str): name of the table to grab config from config (dict): may be overspecified or underspecfied
625941d70fa83653e465720d
def write_ply(data, fout, fields=None): <NEW_LINE> <INDENT> if not fields: <NEW_LINE> <INDENT> fields = data.keys() <NEW_LINE> <DEDENT> write_ply_header(data, fout, fields) <NEW_LINE> fmt_map = {np.dtype("int8") : "%d", np.dtype("uint8") : "%d", np.dtype("int16") : "%d", np.dtype("uint16") : "%d", np.dtype("int...
Write points as vertices in an ASCII PLY format.
625941d710dbd63aa1bd2df6
def process_batch(self, inputs): <NEW_LINE> <INDENT> for key, ipt in inputs.items(): <NEW_LINE> <INDENT> inputs[key] = ipt.to(self.device) <NEW_LINE> <DEDENT> if self.opt.pose_model_type == "shared": <NEW_LINE> <INDENT> all_color_aug = torch.cat([inputs[("color_aug", i, 0)] for i in self.opt.frame_ids]) <NEW_LINE> all_...
Pass a minibatch through the network and generate images and losses
625941d7435de62698dfdea0
def pq_apply_dict(): <NEW_LINE> <INDENT> d = {'Saturation_1': True, 'Saturation_2': True, 'Saturation_3': True, 'Saturation_4': True, 'Saturation_5': True, 'Saturation_61': True, 'Saturation_62': True, 'Saturation_7': True, 'Contiguity': True, 'Land_Sea': True, 'ACCA': True, 'Fmask': True, 'CloudShadow_1': True, 'Cloud...
Return a dictionary containing boolean values on whether or not to apply a PQ quality flag.
625941d7460517430c3943d4
def created_hosted_zone_parser(root, connection): <NEW_LINE> <INDENT> zone = root.find('./{*}HostedZone') <NEW_LINE> hosted_zone = parse_hosted_zone(zone, connection) <NEW_LINE> e_delegation_set = root.find('./{*}DelegationSet') <NEW_LINE> parse_delegation_set(hosted_zone, e_delegation_set) <NEW_LINE> e_change_info = r...
Parses the API responses for the :py:meth:`route53.connection.Route53Connection.create_hosted_zone` method. :param lxml.etree._Element root: The root node of the etree parsed response from the API. :param Route53Connection connection: The connection instance used to query the API. :rtype: HostedZone :returns: ...
625941d744b2445a339322e8
def print_metadata(self,outfile): <NEW_LINE> <INDENT> out_f = open('{}'.format(outfile),'w') <NEW_LINE> out_f.write('id:ID,:LABEL,preflabel,synonyms:IGNORE,definition\n') <NEW_LINE> out_f.write('owl#Thing,MONDOCLASS,"Thing","NA","Root class."\n') <NEW_LINE> for term in self.metadata: <NEW_LINE> <INDENT> id = term.get('...
This function extracts basic term metadata information for all terms in the ontology to be used in graph representation applications such as neo4j or Knowledge.Bio. Particularly, returns the id, :LABEL, label, synonyms, and definition :return: output file called 'pheno_concepts.tsv' with all the metadata for all terms
625941d763b5f9789fde7339
def rien_devant(self): <NEW_LINE> <INDENT> return RUR._UR.front_is_clear_(self.body)
Indique si un obstacle (mur, clôture, eau, mur de brique, ) bloque le chemin. Returns: True si le chemin est non bloqué, False autrement.
625941d7711fe17d825425bc
def _ocf_1_1_parameter_list_to_ocf_unified( parameter_list: Iterable[ResourceAgentParameterOcf1_1], ) -> List[ResourceAgentParameter]: <NEW_LINE> <INDENT> return [ ResourceAgentParameter( name=parameter.name, shortdesc=parameter.shortdesc, longdesc=parameter.longdesc, type=parameter.type, default=parameter.default, enu...
Transform OCF 1.1 parameters to a universal format parameter_list -- parameters according OCF 1.1
625941d707d97122c4178ae2
def __init__(self, n_epochs=10, l2=0): <NEW_LINE> <INDENT> self.n_epochs = n_epochs
Initialize the model. :param n_epochs: :param l2:
625941d7046cf37aa974cf9a
def randrange(self, start, stop=None, step=1, _int=int): <NEW_LINE> <INDENT> istart = _int(start) <NEW_LINE> if istart != start: <NEW_LINE> <INDENT> raise ValueError("non-integer arg 1 for randrange()") <NEW_LINE> <DEDENT> if stop is None: <NEW_LINE> <INDENT> if istart > 0: <NEW_LINE> <INDENT> return self._randbelow(is...
Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want.
625941d7cb5e8a47e48b7cfb
def loss_SSIM(self, y_true, y_pred): <NEW_LINE> <INDENT> ssim = tf.image.ssim(y_true, y_pred, max_val=1) <NEW_LINE> return tf.reduce_mean((1.0 - ssim) / 2, name='ssim_loss')
define loss function between Ground_truth and pred of network :param y_pred: :return: losss
625941d707f4c71912b116d7
def isErrorPage(self, page): <NEW_LINE> <INDENT> err_score = 0.0 <NEW_LINE> for pat, prob in list(err_pats.items()): <NEW_LINE> <INDENT> if err_score > 0.9: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if re.search(pat, page): <NEW_LINE> <INDENT> err_score += prob <NEW_LINE> <DEDENT> <DEDENT> log.debug("File error pag...
Example code from David Mertz' Text Processing in Python. Released in the Public Domain.
625941d78c3a87329515860f
def control_redis(start=False, stop=False): <NEW_LINE> <INDENT> global g_redis_process <NEW_LINE> if stop: <NEW_LINE> <INDENT> if g_redis_process: <NEW_LINE> <INDENT> _log.info('Stopping Redis server') <NEW_LINE> g_redis_process.terminate() <NEW_LINE> g_redis_process.wait() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>...
Start and/or stop Redis server.
625941d799fddb7c1c9de5e4
def test_add_image(self): <NEW_LINE> <INDENT> imagename = 'new.jpg' <NEW_LINE> usernick = 'carol' <NEW_LINE> interface.add_image(self.db, imagename, usernick) <NEW_LINE> images = interface.list_images(self.db, 5) <NEW_LINE> self.assertEqual(imagename, images[0]['filename'], 'wrong image name after add_image') <NEW_LINE...
Test that add_image updates the database properly
625941d7a8370b7717052af2
def create_cobra_model_from_agora_model(agora_name, validate=False): <NEW_LINE> <INDENT> response = requests.get('{0}AGORA/sbml/{1}.xml'.format(vmh_url, agora_name)) <NEW_LINE> if response.status_code != requests.codes.OK: <NEW_LINE> <INDENT> response.raise_for_status() <NEW_LINE> <DEDENT> with io.BytesIO(response.cont...
Create a COBRA model from an AGORA model. Parameters ---------- agora_name: str Name of AGORA model validate : bool, optional When True, perform validity checks on COBRA model Returns ------- cobra.Model COBRA model created from SBML representation of AGORA model
625941d7ab23a570cc2503d7
def list_pools(self, requestslib_kwargs=None): <NEW_LINE> <INDENT> full_url = self._POOLS_URL.format(base_url=self.url) <NEW_LINE> return self.request('GET', full_url, response_entity_type=Pools, requestslib_kwargs=requestslib_kwargs)
List Pools @summary: List all pools configured for the account. @rtype: Requests.response @note: This operation does not require a request body.
625941d78e71fb1e9831d9fc
def low_high_ebb_flow(lmr, hlr, perc_adj, tide_data, date_ranges, ebb_flow_data): <NEW_LINE> <INDENT> list_low = [] <NEW_LINE> lowest_tide_dt, highest_tide_dt = date_ranges[0] <NEW_LINE> date_format = '%Y-%m-%dT%H:%M:%S' <NEW_LINE> if perc_adj == 50: <NEW_LINE> <INDENT> list_high = sorted([[x[0].strftime(date_format), ...
Get all ebb flow and low high dates :param lmr: low max range :param hlr: high tide range :param perc_adj: adjusted percentage :param tide_data: tide data :param date_ranges: date ranges for epoch :param ebb_flow_data: input ebb flow data :return: individual list of low, high and ebb flow data
625941d730bbd722463cc01b
def test_download(): <NEW_LINE> <INDENT> connect = HeavyConnect() <NEW_LINE> try: <NEW_LINE> <INDENT> test_dir = get_test_dir() <NEW_LINE> file = abspath(join(test_dir, "image.jpg")) <NEW_LINE> url = "https://www.pythonscraping.com/img/gifts/img6.jpg" <NEW_LINE> connect.download(url, file) <NEW_LINE> assert exists(file...
Tests the download method.
625941d7ac7a0e7691ed431c
def test_reset_pass_code(self): <NEW_LINE> <INDENT> url = '/api/v1/user/reset_pass_code' <NEW_LINE> data1 = { 'email': user_init['email'], 'answer1': 'answer 1', 'answer2': 'answer 2', 'answer3': 'answer 3', } <NEW_LINE> exp_json = { "message": "Your password has been updated" } <NEW_LINE> response = self.client.post(u...
python manage.py test --settings=shinobi_core.settings.test shinobi_api.tests.UserAPITestCase.test_reset_pass_code
625941d773bcbd0ca4b2c2ca
def inp2isel(file, varname, isel): <NEW_LINE> <INDENT> dims = file.variables[varname].cf_dimensions <NEW_LINE> if isinstance(isel, str): <NEW_LINE> <INDENT> isel = crdSelect(isel, dims) <NEW_LINE> <DEDENT> if isinstance(isel, crdSelect): <NEW_LINE> <INDENT> isel = crdsel2idxsel(file, isel) <NEW_LINE> <DEDENT> return is...
Convert the input isel to a index space selection object.
625941d7009cb60464c63604
def process_command_line_input(): <NEW_LINE> <INDENT> input_args = sys.argv <NEW_LINE> if input_args[0].find('ipython') >= 0: <NEW_LINE> <INDENT> input_args = list() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input_args.pop(0) <NEW_LINE> <DEDENT> return input_args
Process command line input, needed to possible ipython use Returns ------- input_args : list List of input arguements
625941d7e5267d203edcdeee
def flush(self): <NEW_LINE> <INDENT> handled = [] <NEW_LINE> try: <NEW_LINE> <INDENT> fhandler = open(self.logfilename, 'a') <NEW_LINE> <DEDENT> except self.log(Exception): <NEW_LINE> <INDENT> raise Exception <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> for index, entry in enumerate(self.msgs): <NEW_LINE> <INDENT> try:...
A flush fuction.
625941d7ad47b63b2c50a1d3
def calculate_sse_for_sample(true_val, pred_val): <NEW_LINE> <INDENT> if true_val == 1: <NEW_LINE> <INDENT> return math.pow((pred_val[0] - 1), 2) + math.pow(pred_val[1], 2) + math.pow(pred_val[2], 2) + math.pow(pred_val[3], 2) <NEW_LINE> <DEDENT> elif true_val == 2: <NEW_LINE> <INDENT> return math.pow(pre...
helper function used to compute sum of squared error for a data point :param true_val: actual class of data point :param pred_val: predicted class of data point :return: sse
625941d7cdde0d52a9e53288
def setPlain(self): <NEW_LINE> <INDENT> self.head['Content-type'] = 'text/plain'
Sets the content type to indicate that the return is plain text.
625941d7be7bc26dc91cd850
def _left(): <NEW_LINE> <INDENT> global mode <NEW_LINE> oldCurser = window.curser <NEW_LINE> if (mode == "HEX"): <NEW_LINE> <INDENT> if window.halfbyte == False: <NEW_LINE> <INDENT> moveAmount = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> moveAmount = 0 <NEW_LINE> <DEDENT> <DEDENT> elif (mode == "TEXT"): <NEW_LINE>...
Move curser left, sets curser Location, adjusts screen location as needed
625941d75fdd1c0f98dc0487
def spins_cost(self, spins): <NEW_LINE> <INDENT> return self.bits_cost(tuple((1 + spin) / 2 for spin in spins))
Compute the cost function for the values of the variables specified by spins. Parameters ---------- spins: iterable The spins (+/-1 integers) encoding the values of the variables. Returns ------- float The value of the cost function.
625941d79c8ee82313fbb9c9
def is_shared_and_in_shared_time(self): <NEW_LINE> <INDENT> if not self.is_read_perms(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self.has_shared_limit(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.is_shared_end_time_out(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return ...
对象是否是分享的, 并且在有效分享时间内,即是否可公共访问 :return: True(是), False(否)
625941d7435de62698dfdea1
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941d7090684286d50ef3b
def test_topic_with_no_team_count(self): <NEW_LINE> <INDENT> with self.assertNumQueries(2): <NEW_LINE> <INDENT> serializer = TopicSerializer( self.course.teamsets[0].cleaned_data, context={'course_id': self.course.id}, ) <NEW_LINE> assert serializer.data == {'name': 'Tøpic', 'description': 'The bést topic!', 'id': '0',...
Verifies that the `TopicSerializer` correctly displays a topic with a team count of 0, and that it takes a known number of SQL queries.
625941d7379a373c97cfad9a
def loss(self, features, captions): <NEW_LINE> <INDENT> captions_in = captions[:, :-1] <NEW_LINE> captions_out = captions[:, 1:] <NEW_LINE> mask = (captions_out != self._null) <NEW_LINE> W_proj, b_proj = self.params['W_proj'], self.params['b_proj'] <NEW_LINE> W_embed = self.params['W_embed'] <NEW_LINE> Wx, Wh, b = self...
Compute training-time loss for the RNN. We input image features and ground-truth captions for those images, and use an RNN (or LSTM) to compute loss and gradients on all parameters. Inputs: - features: Input image features, of shape (N, D) - captions: Ground-truth captions; an integer array of shape (N, T) where eac...
625941d71b99ca400220ad05
def testApplyIGM(self): <NEW_LINE> <INDENT> testSed = Sed() <NEW_LINE> sedName = os.path.join(getPackageDir('sims_sed_library'), 'galaxySED') <NEW_LINE> testSed.readSED_flambda(os.path.join(sedName, 'Burst.10E08.002Z.spec.gz')) <NEW_LINE> testFlambda = [] <NEW_LINE> for fVal in testSed.flambda: <NEW_LINE> <INDENT> test...
Test application of IGM from Lookup Tables to SED objects
625941d760cbc95b062c6797
def synthesize_photometry(lbda, flux, filter_lbda, filter_trans, normed=True): <NEW_LINE> <INDENT> from .tools import nantrapz <NEW_LINE> def integrate_photons(lbda, flux, step, flbda, fthroughput): <NEW_LINE> <INDENT> filter_interp = np.interp(lbda, flbda, fthroughput) <NEW_LINE> dphotons = (filter_interp * flux) * lb...
Get Photometry from the given spectral information through the given filter. This function converts the flux into photons since the transmission provides the fraction of photons that goes though. Parameters ----------- lbda, flux: [array] Wavelength and flux of the spectrum from which you want to synthetize phot...
625941d7a17c0f6771cbe2a4
def count(content:str, PATTERN:list) -> int: <NEW_LINE> <INDENT> return sum([len(re.findall(P, content)) for P in PATTERN])
Count the number of pattern(s).
625941d701c39578d7e75090