code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def testNumberRooms(self): <NEW_LINE> <INDENT> self.assertIs(type(Place.number_rooms), int) | Tests the number_rooms attribute | 625941e08c0ade5d55d3ed36 |
def __init__(self, client, auth=None): <NEW_LINE> <INDENT> super(FlaskTestClient, self).__init__(auth) <NEW_LINE> self.__client = client | contructor
:param client: a testing client created by flask.test_client()
:param auth pyswagger.Security: auth info holder | 625941e0711fe17d825426dc |
def look_to(self): <NEW_LINE> <INDENT> distance = 8 <NEW_LINE> step = 0.01 <NEW_LINE> x, y, z = self.myPos <NEW_LINE> dx, dy, dz = self.get_sight_vector() <NEW_LINE> dx *= step <NEW_LINE> dy *= step <NEW_LINE> dz *= step <NEW_LINE> k = p = (round(x), round(y), round(z)) <NEW_LINE> for _ in range(distance): <NEW_LINE> <... | Возвращает координаты точки, на которую направлен взгляд в пределах distance
:return: tuple | 625941e056b00c62f0f149d4 |
def make_friends(self, panda1, panda2): <NEW_LINE> <INDENT> if [panda1, panda2] in self._friendship: <NEW_LINE> <INDENT> raise PandasAlreadyFriends("Pandas Already Friends") <NEW_LINE> <DEDENT> if not self.has_panda(panda1): <NEW_LINE> <INDENT> self.add_panda(panda1) <NEW_LINE> <DEDENT> if not self.has_panda(panda2): <... | make two pandas friends | 625941e00c0af96317bb8561 |
def player_library_url(player_id=None, **pd_api_url_args): <NEW_LINE> <INDENT> player_id = player_id or settings.JWPLATFORM_EMBED_PLAYER_KEY <NEW_LINE> return legacy_pd_api_url(f'/libraries/{player_id}.js', **pd_api_url_args) | Return a signed URL to a JWPlayer player library. If ``player_id`` is None, the default embed
player is used. Remaining keyword arguments are passwd to ``pd_api_url``. | 625941e038b623060ff0b166 |
def check_gmailness(self): <NEW_LINE> <INDENT> if not GIMAPFetcher.GMAIL_EXTENSION in self.get_capabilities(): <NEW_LINE> <INDENT> raise Exception("GIMAPFetcher is not connect to a IMAP GMAIL server. Please check host (%s) and port (%s)" % (self.host, self.port)) <NEW_LINE> <DEDENT> return True | Check that the server is a gmail server | 625941e04428ac0f6e5bab6e |
def get_arch(self): <NEW_LINE> <INDENT> arch = '' <NEW_LINE> cpu = '' <NEW_LINE> for line in read_file(self.dotconfig): <NEW_LINE> <INDENT> m = self.re_arch.match(line) <NEW_LINE> if m: <NEW_LINE> <INDENT> arch = m.group(1) <NEW_LINE> continue <NEW_LINE> <DEDENT> m = self.re_cpu.match(line) <NEW_LINE> if m: <NEW_LINE> ... | Parse .config file and return the architecture.
Returns:
Architecture name (e.g. 'arm'). | 625941e03317a56b86939fc9 |
def dequeue(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> returned_value = self.front.data <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise IndexError('Can not remove from empty queue.') <NEW_LINE> <DEDENT> self.front = self.front.pre_node <NEW_LINE> try: <NEW_LINE> <INDENT> self.front.next_no... | returns the fron element and remove it | 625941e03539df3088e2e6c4 |
@app.route('/graph') <NEW_LINE> @app.route('/graph/<int:graph_id>') <NEW_LINE> def get_graph(graph_id=0): <NEW_LINE> <INDENT> return jsonify(gdb.get_graph_dict(graph_id)) | Build the graph with id **graph_id** according to the information stored in the database.
If the id is 0, the graph G is returned, otherwise a graph of J is returned.
A json file corresponding to the graph is built with the following format:
{
'nodes' : list of ids of the nodes of the graph,
'edges' : list of edges of ... | 625941e05fdd1c0f98dc05ae |
def features(im, max_features=6, min_pixels=50): <NEW_LINE> <INDENT> arr = numpy.asarray(im.convert('L')) <NEW_LINE> labels, _ = ndimage.label(numpy.invert(arr)) <NEW_LINE> slices = ndimage.find_objects(labels) <NEW_LINE> features = [] <NEW_LINE> for slice in slices: <NEW_LINE> <INDENT> feature = arr[slice] <NEW_LINE> ... | Returns a list of features found in `im`.
Args:
im (Image): Source image.
max_features (int): The maximum number of features to return.
min_pixels (int): The minimum number of pixels a feature must
contain to be included.
Return:
A list of Images describing each feature. | 625941e03617ad0b5ed6826f |
def configure_targets(deployment_target): <NEW_LINE> <INDENT> global S3_BUCKET <NEW_LINE> global S3_BASE_URL <NEW_LINE> global S3_DEPLOY_URL <NEW_LINE> global DEBUG <NEW_LINE> global DEPLOYMENT_TARGET <NEW_LINE> global ASSETS_MAX_AGE <NEW_LINE> if deployment_target == 'electron': <NEW_LINE> <INDENT> S3_BUCKET = None <N... | Configure deployment targets. Abstracted so this can be
overriden for rendering before deployment. | 625941e0a05bb46b383ecb98 |
def init_adj(self, periodic): <NEW_LINE> <INDENT> self.init_p2p_adj(periodic) <NEW_LINE> self.init_t_adj() | Initializes pore-to-pore, pore-to-tube and tube-to-pore adjacency list | 625941e0442bda511e8be78c |
def test_parse_integers(): <NEW_LINE> <INDENT> print(gui_helper.parse_integers('3, 4, 5')) <NEW_LINE> print(gui_helper.parse_integers('3:5, 4:10, 19')) <NEW_LINE> try: <NEW_LINE> <INDENT> int_list = gui_helper.parse_integers('3.2, 4') <NEW_LINE> <DEDENT> except RuntimeError as run_err: <NEW_LINE> <INDENT> print(run_err... | test main
:return: | 625941e06fece00bbac2dabb |
def to_circular(self): <NEW_LINE> <INDENT> new = self.__class__(self) <NEW_LINE> new.linear = False <NEW_LINE> return new | Make a new instance of sequence as circular. | 625941e03346ee7daa2b30e7 |
def count_yeses(group): <NEW_LINE> <INDENT> seen = set() <NEW_LINE> for resp in group: <NEW_LINE> <INDENT> resp_set = set(resp) <NEW_LINE> seen.update(resp_set) <NEW_LINE> <DEDENT> return len(seen) | Count the number of questions to which anyone answered "yes".
:param group: OBJ; generator
:return: INT | 625941e0e5267d203edce012 |
def sort(self): <NEW_LINE> <INDENT> for i in range(self.array_size): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> while index < self.array_size - 1 - i: <NEW_LINE> <INDENT> element = self.array[index] <NEW_LINE> next_element = self.array[index + 1] <NEW_LINE> if next_element <= element: <NEW_LINE> <INDENT> self.array[index... | Call the bubble sort algorithm | 625941e021bff66bcd684cc8 |
def validate_email(value): <NEW_LINE> <INDENT> import re <NEW_LINE> regex = re.compile(r'^[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}$') <NEW_LINE> if not regex.match(value): <NEW_LINE> <INDENT> raise db.BadValueError('Invalid email address %s' % (str(value))) | Don't accept an email address the doesn't match its basic form. | 625941e0fff4ab517eb2f7b7 |
def page(self, friendly_name=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> params = values.of({ 'FriendlyName': friendly_name, 'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) <NEW_LINE> response = self._version.page( 'GET', self._ur... | Retrieve a single page of ApiClientInstance records from the API.
Request is executed immediately
:param unicode friendly_name: Filter by friendly name
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records... | 625941e066673b3332b9240b |
def add_categorical_gene(self, name: str, domain: tuple) -> None: <NEW_LINE> <INDENT> genespecs = { 'type': 'categorical', 'specs': {'domain': domain} } <NEW_LINE> self._blueprint.update({name: genespecs}) | Add a Categorical gene specs for the blueprint.
Parameters
----------
:name: Gene name.
:domain: `tuple` with all categories.
Example
-------
>>> builder = BlueprintBuilder()
>>> builder.add_categorical_gene(name='letters', domain=('a', 'b', 'c'))
>>> blueprint = builder.get_blueprint()
>>> blueprint.show()
-... | 625941e0cc40096d61595cc8 |
def relu_forward(x): <NEW_LINE> <INDENT> out = None <NEW_LINE> out = ReLU(x) <NEW_LINE> cache = x <NEW_LINE> return out, cache | Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: x | 625941e0b5575c28eb68e37c |
def embed(self, sentence): <NEW_LINE> <INDENT> processed_sentence = self.prepare_data([sentence])[0] <NEW_LINE> sentence = [self.embeddings[self.lookup_dict[word]] for word in processed_sentence] <NEW_LINE> return np.array(sentence).sum(0) | Returns the embedding for the sentence
as the sum over the embeddings of the words | 625941e07d847024c06be638 |
def getargs(function, n = 0): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> argspec = getargspec(function) <NEW_LINE> if argspec.varargs or n == 0: <NEW_LINE> <INDENT> return argspec.args <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return argspec.args[n:] <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDE... | :Parameters:
----------------
function : callable
The function for which we want the args
n : int optional
get the name of the args after allowing for first n args to be set by *args.
The default is 0.
:Returns:
-------
None or a list of args | 625941e04f6381625f114db5 |
def Sort(arr): <NEW_LINE> <INDENT> for i in reversed(range(len(arr))): <NEW_LINE> <INDENT> key = arr[i] <NEW_LINE> j = i-1 <NEW_LINE> while (j >= 0 and key <= arr[j]): <NEW_LINE> <INDENT> arr[j+1] = arr[j] <NEW_LINE> j -= 1 <NEW_LINE> PrintArray(arr) <NEW_LINE> print('') <NEW_LINE> <DEDENT> arr[j+1] = key <NEW_LINE> <D... | Sorting array by ascending. | 625941e0d4950a0f3b08c6c3 |
def JClusterRadius(r200=None, sigma=None, cl=None, p=None, clsigma=None): <NEW_LINE> <INDENT> BAD_R = _FLOAT_INFO.max <NEW_LINE> if (r200 == None) or (r200 < 0): <NEW_LINE> <INDENT> r200 = 0.0 <NEW_LINE> <DEDENT> if (sigma == None) or (sigma < 0): <NEW_LINE> <INDENT> sigma = 0.0 <NEW_LINE> <DEDENT> d = r200+sigma <NEW_... | The radius from the cluster center that contains the specified
fraction of signal.
At least one of the size parameters r200 or sigma must be given.
If both are given, they must use a consistent set of units, either
radians or degrees. The returned radius is in the same units.
The coverage level can be specified expl... | 625941e0566aa707497f48dd |
def test_list_server_deployments(provider): <NEW_LINE> <INDENT> server = get_server(provider, HAWKULAR_PRODUCT_NAME) <NEW_LINE> ui_deps = get_deployments_set(MiddlewareDeployment.deployments( server=server)) <NEW_LINE> db_deps = get_deployments_set(MiddlewareDeployment.deployments_in_db( server=server)) <NEW_LINE> asse... | Tests deployments list for Hawkular Local server
Steps:
* Get Hawkular Local server
* Get deployments list from UI of server
* Get deployments list from Database of server
* Compares both lists [UI, Database] | 625941e0a8370b7717052c17 |
def order_strategies(self): <NEW_LINE> <INDENT> def get_generalization_depth(strategy, visited=None): <NEW_LINE> <INDENT> if visited is None: <NEW_LINE> <INDENT> visited = set() <NEW_LINE> <DEDENT> if strategy._generalizations: <NEW_LINE> <INDENT> if strategy in visited: <NEW_LINE> <INDENT> raise Exception("Cycle in ge... | NOT_RPYTHON | 625941e0d268445f265b51e8 |
def load_dataset(): <NEW_LINE> <INDENT> train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r") <NEW_LINE> train_set_x_orig = np.array(train_dataset["train_set_x"][:]) <NEW_LINE> train_set_y_orig = np.array(train_dataset["train_set_y"][:]) <NEW_LINE> test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r") <... | Convert the data in a training set (data.h5) in to a set of matrix
with training/text x and y data.
Return:
train_set_x_orig -- a numpy array of shape (m_train, num_pxm num_px,3)
- m_train (number of training examples)
- m_test (number of test examples)
- num_px (= height = width of a training image)
tra... | 625941e0046cf37aa974d0be |
def generate_csv(member): <NEW_LINE> <INDENT> from datetime import date <NEW_LINE> import unicodecsv <NEW_LINE> csv = tempfile.TemporaryFile() <NEW_LINE> csvw = unicodecsv.writer(csv, encoding='utf-8') <NEW_LINE> fields = ( date.today().strftime("%Y-%m-%d"), 'pending...', member.firstname, member.lastname, member.email... | returns a csv with the relevant data
to ease import of new data sets | 625941e026068e7796caf05d |
def operation_differences(zabbix_ops, user_ops): <NEW_LINE> <INDENT> if len(zabbix_ops) != len(user_ops): <NEW_LINE> <INDENT> return user_ops <NEW_LINE> <DEDENT> rval = {} <NEW_LINE> for zab, user in zip(zabbix_ops, user_ops): <NEW_LINE> <INDENT> for key, val in user.items(): <NEW_LINE> <INDENT> if key == 'opconditions... | Determine the differences from user and zabbix for operations | 625941e0187af65679ca5499 |
def _record_fetch_result(self, container_id, result): <NEW_LINE> <INDENT> self.__lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> self.__container_scoreboard[container_id] = result <NEW_LINE> self.__remaining_metrics_count -= 1 <NEW_LINE> self.__idle_workers_count += 1 <NEW_LINE> self.__cv.notifyAll() <NEW_LINE> <DED... | Record that the `stats` result for the specified container. If there was an error, result should be
None.
@type container_id: str
@type result: JsonObject | 625941e00383005118ecf95b |
def __repr__(self): <NEW_LINE> <INDENT> return "{} = {}".format(self._setting_name, self._current_value) | Return string information about the setting so that it
can be written into a text file to save it. Only name
of the setting and current value are recorded - files are
for modifying settings, not creating them. Example:
some_setting = On
(no parentheses)
:return: str | 625941e055399d3f05588a2f |
def mutate(self, mutation_rate): <NEW_LINE> <INDENT> self.network.mutate(mutation_rate) | Mutates the network at the specified rate. | 625941e0d99f1b3c44c67902 |
def remove_piece_at(self, square, into_hand=False): <NEW_LINE> <INDENT> piece_type = self.piece_type_at(square) <NEW_LINE> if piece_type == NONE: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if into_hand: <NEW_LINE> <INDENT> self.add_piece_into_hand(piece_type, self.turn) <NEW_LINE> <DEDENT> mask = BB_SQUARES[square]... | Removes a piece from the given square if present. | 625941e07b25080760e397d1 |
def test_proper_season_pack_2(self, execute_task): <NEW_LINE> <INDENT> task = execute_task('test_proper_season_pack_2') <NEW_LINE> assert task.find_entry('accepted', title='foo.s01.720p-flexget') <NEW_LINE> task = execute_task('test_proper_season_pack_3') <NEW_LINE> assert task.find_entry('accepted', title='foo.s01.720... | Series plugin: proper available immediately | 625941e0cb5e8a47e48b7e1f |
def tktFilter(status='open', **args): <NEW_LINE> <INDENT> extra = [] <NEW_LINE> if status.lower() == 'open': <NEW_LINE> <INDENT> extra.append('incident_state<4') <NEW_LINE> <DEDENT> elif status.lower() == 'closed': <NEW_LINE> <INDENT> extra.append('incident_state>=4') <NEW_LINE> <DEDENT> elif status.lower() == 'unresol... | Filter tickets. | 625941e04d74a7450ccd453e |
def read_cat_naf(cat_etree, naf_etree): <NEW_LINE> <INDENT> cat_event = extract_event_CAT(cat_etree) <NEW_LINE> dict_event_lemma = collections.defaultdict(list) <NEW_LINE> for elem in naf_etree.findall("terms/term"): <NEW_LINE> <INDENT> for k, v in cat_event.items(): <NEW_LINE> <INDENT> if elem.attrib.get('id', 'null')... | function which read CAT and NAF data
:param cat_etree: ecb+ file in CAT - extract eligible annotated events
:param naf_etree: ecb+ naf file - extract event lemmas, event same sentence
:return: cat_event, dict_event_lemma, dict_event_same_sentence: 3 dictionaries | 625941e0dc8b845886cb58b0 |
def __init_catalog(self, catalog_id): <NEW_LINE> <INDENT> str_id = str(catalog_id) <NEW_LINE> self.log('INFO', 'Initialize catalog {}...'.format(str_id)) <NEW_LINE> self.dict_catalogs[str_id] = CCatalog(self, str_id) | Instantiate sub resource:
catalog
Make URI ready without sub resources' mon data | 625941e099fddb7c1c9de709 |
def count_lines(path, extensions=None, excluded_dirnames=None): <NEW_LINE> <INDENT> if extensions is None: <NEW_LINE> <INDENT> extensions = ['.py', '.pyw', '.ipy', '.enaml', '.c', '.h', '.cpp', '.hpp', '.inc', '.', '.hh', '.hxx', '.cc', '.cxx', '.cl', '.f', '.for', '.f77', '.f90', '.f95', '.f2k', '.f03', '.f08'] <NEW_L... | Return number of source code lines for all filenames in subdirectories
of *path* with names ending with *extensions*
Directory names *excluded_dirnames* will be ignored | 625941e0cc40096d61595cc9 |
def BFS(G,root,direction='forward'): <NEW_LINE> <INDENT> Q = Queue() <NEW_LINE> d = {} <NEW_LINE> pred = {} <NEW_LINE> for v in G.vertices: <NEW_LINE> <INDENT> d[v] = gInfinity <NEW_LINE> <DEDENT> d[root] = 0 <NEW_LINE> pred[root] = root <NEW_LINE> Q.Append(root) <NEW_LINE> while Q.IsNotEmpty(): <NEW_LINE> <INDENT> v =... | Calculate BFS distances and predecessor without showing animations.
If G is directed, direction does matter:
- 'forward' BFS will use outgoing edges
- 'backward' BFS will use incoming edges
It uses gInfinity (from GatoGlobals.py) as infinite distance.
returns (dist,pred) | 625941e04527f215b584c7cd |
def __init__( self, A: jnp.ndarray, B: jnp.ndarray, Q: jnp.ndarray = None, R: jnp.ndarray = None, K: jnp.ndarray = None, start_time: int = 0, H: int = 5, lr_scale: Real = 0.005, decay: bool = False, delta: Real = 0.01, ) -> None: <NEW_LINE> <INDENT> self.d_state, self.d_action = B.shape <NEW_LINE> self.A, self.B = A, B... | Description: Initialize the dynamics of the model.
Args:
A (jnp.ndarray): system dynamics
B (jnp.ndarray): system dynamics
Q (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
R (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
K (jnp.ndarray): Starting policy (optional). Defaults to L... | 625941e08c3a873295158738 |
def create_reference_count_request(request_id: str): <NEW_LINE> <INDENT> file_path = "config/reference_count.json" <NEW_LINE> abs_file_path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), './../', file_path)) <NEW_LINE> print("Absolute path of " + file_path + ": " + abs_file_path) <NEW_LINE> ... | Create a reference count request
Keyword arguments:
request_id -- request_id | 625941e05510c4643540f756 |
def validate_datetime(namespace): <NEW_LINE> <INDENT> datetime_format = '^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T(2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9][a-zA-Z]{0,5}$' <NEW_LINE> if namespace.datetime is not None and re.search(datetime_format, namespace.datetime) is None: <NEW_LINE> <INDENT> raise CLIErro... | valid datetime format:YYYY-MM-DDThh:mm:ssZ | 625941e04e696a04525c97c6 |
def pipe_list_synonym(name): <NEW_LINE> <INDENT> def getter(self): <NEW_LINE> <INDENT> attr = getattr(self, name) <NEW_LINE> if attr: <NEW_LINE> <INDENT> return attr.strip('|').split('|') <NEW_LINE> <DEDENT> <DEDENT> def setter(self, value): <NEW_LINE> <INDENT> if isinstance(value, basestring): <NEW_LINE> <INDENT> seta... | Converts pipe separated text into a list | 625941e04a966d76dd55138c |
def delete_project(self, projectId: int): <NEW_LINE> <INDENT> return self.requester.request( method="delete", path=self.get_projects_path(projectId=projectId) ) | Delete Project.
Link to documentation:
https://support.crowdin.com/api/v2/#operation/api.projects.delete | 625941e0cdde0d52a9e533af |
@_create_machine.undo <NEW_LINE> def _undo_create_machine(provider_id, parameters, machine_group_uuid, skip_store, wait_spawning): <NEW_LINE> <INDENT> generic_filters = {} <NEW_LINE> meta_filters = { 'mysql-fabric-machine-group-uuid' : machine_group_uuid } <NEW_LINE> manager = _retrieve_machine_manager(provider_id) <NE... | Remove machines already created if there is an error.
| 625941e045492302aab5e641 |
def match(self, other_version): <NEW_LINE> <INDENT> major, minor, patch = _str_to_version(other_version, allow_wildcard=True) <NEW_LINE> return major in [self.major, "*"] and minor in [self.minor, "*"] and patch in [self.patch, "*"] | Returns True if other_version matches.
Args:
other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a
number or a wildcard. | 625941e0ec188e330fd5ab13 |
def write(self, file_handle): <NEW_LINE> <INDENT> for qname, readpair in self.readset.iteritems(): <NEW_LINE> <INDENT> for i, read in enumerate(readpair): <NEW_LINE> <INDENT> if read is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> which = i + 1 <NEW_LINE> header = "%s-%s %s" % (qname, which, self.keyvals) <NE... | Write FASTQ reads to file. | 625941e0d164cc61757830c9 |
def generate(self, shape, dtype=None): <NEW_LINE> <INDENT> self.log_weight_creation(shape) <NEW_LINE> if len(shape) < 2: <NEW_LINE> <INDENT> raise ValueError("Can only generate Tensors with at least 2" " dimensions, you gave: {}".format(len(shape))) <NEW_LINE> <DEDENT> elements = shape[-2] * shape[-1] <NEW_LINE> nonzer... | Construct and initialize a new Tensor object of the specified shape.
Arguments:
shape (list of ints): The size of each dimension of the Tensor.
dtype (dtype, optional): Element data type. If not specifed we use
the default dtype associated with that
ba... | 625941e031939e2706e4d1df |
def sign_manifest(seq, validation_pk, master_secret): <NEW_LINE> <INDENT> to_run = ['python', ARGS.ripple_home + '/bin/python/Manifest.py', 'sign', str(seq), validation_pk, master_secret] <NEW_LINE> try: <NEW_LINE> <INDENT> r = subprocess.check_output(to_run) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as ... | returns the signed manifest as a string | 625941e0d58c6744b4257fd8 |
def _prm_extract_missing_flags(self,data_dict, flags_dict): <NEW_LINE> <INDENT> for key,data in data_dict.items(): <NEW_LINE> <INDENT> if not key in flags_dict: <NEW_LINE> <INDENT> dtype = type(data) <NEW_LINE> if dtype in HDF5StorageService.TYPE_FLAG_MAPPING: <NEW_LINE> <INDENT> flags_dict[key]=HDF5StorageService.TYPE... | Extracts storage flags for data in `data_dict`
if they were not specified in `flags_dict`.
See :const:`~pypet.storageservice.HDF5StorageService.TYPE_FLAG_MAPPING`
for how to store different types of data per default. | 625941e05f7d997b87174e15 |
@bp.app_errorhandler(404) <NEW_LINE> def not_found_error(error): <NEW_LINE> <INDENT> current_app.logger.info(error) <NEW_LINE> return render_template('errors/404.html'), 404 | Error handler for code 404 | 625941e021a7993f00bc8070 |
def video_frame_class_gen(batch_size, time_steps): <NEW_LINE> <INDENT> video_name = pa.VIDEO_LIST[0] <NEW_LINE> video_path = os.path.join(pa.VIDEO_FOLDER_PATH, video_name + ".mp4") <NEW_LINE> srt_path = os.path.join(pa.VIDEO_FOLDER_PATH, video_name + ".srt") <NEW_LINE> frames = skvideo.io.vread(video_path)[ 900:990] <N... | Generate frames with corresponding labels
:param batch_size: RNN batch size
:param time_steps: Consecutive frames for 1 batch
:return: batch_time_frames, batch_time_labels | 625941e0e8904600ed9f22ac |
def test_is_symmetric(self): <NEW_LINE> <INDENT> self.assertRaises(AttributeError, lambda: is_symmetric(3)) <NEW_LINE> self.assertIs(is_symmetric(Atom(3)), Undef()) <NEW_LINE> self.assertIs(is_symmetric(Undef()), Undef()) <NEW_LINE> self.assertIs(is_symmetric(Undef(), _checked=False), Undef()) <NEW_LINE> self.assertTru... | Basic tests of relations.is_symmetric(). | 625941e08e05c05ec3eea6f2 |
def told(self, pat_name): <NEW_LINE> <INDENT> time_ago = datetime.today() - timedelta(days=45) <NEW_LINE> patients = PatientTrace.objects.filter(name__iexact=pat_name, start_date__gte=time_ago, status=patienttracing.get_status_new(), clinic=get_clinic_or_default(self.msg.contact) ) <NEW_LINE> if len(patients) == 0: <NE... | Respond to TOLD message, update PatientTrace db entry status to 'told' | 625941e03c8af77a43ae3b1e |
def _axisLabelMeasureOrOffset(self): <NEW_LINE> <INDENT> from music21 import stream <NEW_LINE> offsetMap = self.streamObj.measureOffsetMap([stream.Measure, note.Note]) <NEW_LINE> if len(offsetMap.keys()) > 0: <NEW_LINE> <INDENT> return 'Measure Number' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Offset' | Return an axis label for measure or offset, depending on if measures are available.
| 625941e07d43ff24873a301d |
def __init__( self, iterable = None ): <NEW_LINE> <INDENT> TypedList.__init__( self, iterable, allowedTypes = ( int, long, float ) ) | c'tor
:param self: self reference
:param mixed iterable: initial values | 625941e026068e7796caf05e |
def compare(self, comparison: 'TrackPosition', raw=False) -> bool: <NEW_LINE> <INDENT> comp = comparison <NEW_LINE> if raw: <NEW_LINE> <INDENT> equal = mstats.value.equivalent <NEW_LINE> if not equal(self.x.raw, comp.x.raw): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif not equal(self.y.raw, comp.y.raw): <N... | Compares the positions of this track position and the one specified by
the comparison argument and returns True if their positions and
uncertainties match.
:param comparison:
Another TrackPosition instance to compare with this instance | 625941e044b2445a3393240e |
def metadata(self): <NEW_LINE> <INDENT> return [s.get('metadata', {}) for s in self.items()] | Filter the results to provide only the metadata only. | 625941e0b545ff76a8914190 |
def _initialize_devices(self, num_gpus_per_worker, cluster_spec, task_type, task_id): <NEW_LINE> <INDENT> self._task_type = task_type or "worker" <NEW_LINE> self._task_id = task_id or 0 <NEW_LINE> self._worker_device = "/job:%s/task:%d" % (self._task_type, self._task_id) <NEW_LINE> if cluster_spec is None: <NEW_LINE> <... | Initialize internal devices.
It creates variable devices and compute devices. Variables and operations
will be assigned to them respectively. We have one compute device per tower.
The variable device is a device function or device string. The default
variable device assigns variables to parameter servers in a round-ro... | 625941e0d10714528d600061 |
def validate(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self._callable(data) <NEW_LINE> <DEDENT> except SchemaError as exc: <NEW_LINE> <INDENT> raise SchemaError([None] + exc.autos, [self._error.format(data) if self._error else None] + exc.errors) <NEW_LINE> <DEDENT> except BaseException as exc:... | Validate object.
:param data: data to validate
:raises SchemaError: when schema doesn't match
:return: Validation result | 625941e045492302aab5e642 |
def rest_delete_vlan_mapping_mode(self, mode=None): <NEW_LINE> <INDENT> t = test.Test() <NEW_LINE> c = t.controller('master') <NEW_LINE> url = '/api/v1/data/controller/applications/bcf/global-setting' <NEW_LINE> if mode is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> c.rest.delete(url, {"vlan-mapping": "default"}... | Function to delete vlan mapping
DELETE http://127.0.0.1:8080/api/v1/data/controller/applications/bcf/global-setting {"vlan-mapping": "global"}
DELETE http://127.0.0.1:8080/api/v1/data/controller/applications/bcf/global-setting {"vlan-mapping": "default"} | 625941e0bd1bec0571d909a9 |
def getlist(self, k, d=None): <NEW_LINE> <INDENT> v = self.get(k, d) <NEW_LINE> if isinstance(v, list) is False: <NEW_LINE> <INDENT> raise WorkerTaskParamsValueTypeError(k, v, list) <NEW_LINE> <DEDENT> return v | add in version 0.7.11 | 625941e03eb6a72ae02ec860 |
def is_conjugate(self, other): <NEW_LINE> <INDENT> from sage.misc.superseded import deprecation <NEW_LINE> deprecation(23479, "use sage.dynamics.arithmetic_dynamics.projective_ds.is_conjugate instead") <NEW_LINE> return self.as_dynamical_system().is_conjugate(other) | Return if this map and ``other`` are conjugate.
EXAMPLES::
sage: K.<w> = CyclotomicField(3)
sage: P.<x,y> = ProjectiveSpace(K,1)
sage: H = End(P)
sage: D8 = H([y^2, x^2])
sage: D8.is_conjugate(D8)
doctest:warning
...
True | 625941e0aad79263cf390dc1 |
def parse_baits(path, min_baits): <NEW_LINE> <INDENT> with open_text(path) as f: <NEW_LINE> <INDENT> baits = [ bait for bait in re.split(r'[\s,;]+', f.read()) if bait ] <NEW_LINE> if len(baits) < min_baits: <NEW_LINE> <INDENT> raise UserError( f'{path} needs at least {min_baits} baits, but contains only {len(baits)}' )... | Robustly parse baits file
Parameters
----------
path : ~pathlib.Path
Returns
-------
list
Bait names | 625941e01f037a2d8b946578 |
def voting_membership(request, variation_id): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> profile = user.profile <NEW_LINE> current_order = profile.voting_order <NEW_LINE> current_membership = profile.voting_product_variation <NEW_LINE> variation = ProductVariation.objects.get(id=variation_id) | Puts a voting membership product into the cart and redirects to checkout to finish the
membership process | 625941e0d18da76e23532855 |
def get_threshold(analysis, sensor_key): <NEW_LINE> <INDENT> path_alerts = c.get('Slack', 'config') <NEW_LINE> threshold = json.load(open(path_alerts, "r")) <NEW_LINE> default = threshold[analysis]['default'] <NEW_LINE> return threshold[analysis].get(sensor_key, default) | Return threshold value for a given sensor_key for a given analysis.
The threshold is fetched from the alerts.cfg file.
Parameters
----------
analysis : str
Name of the analysis
sensor_key : str
Sensor key for which the threshold has to be returned. | 625941e00fa83653e4657333 |
@pytest.fixture <NEW_LINE> def nlp(): <NEW_LINE> <INDENT> return en_coref_md.load() | Returns Sacy NLP model. | 625941e094891a1f4081be26 |
def get_flat_field(image, vignette_mask): <NEW_LINE> <INDENT> flat_field = numpy.array(image, dtype=float) <NEW_LINE> near_vignette_mask = vignette_mask ^ ndimage.binary_erosion(vignette_mask, iterations=10) <NEW_LINE> flat_field[~vignette_mask] = flat_field[near_vignette_mask].mean() <NEW_LINE> flat_field = _smooth_fl... | Return a flat-field correction image.
This function smooths out an image and corrects for vignetting to produce
a "flat-field correction image" that can be used to correct uneven
illumination.
The input image should be well-exposed and without any visible features,
and should be dark-current corrected. Ideally an ave... | 625941e050485f2cf553d116 |
def getSubRectangles(self, ims): <NEW_LINE> <INDENT> if len(ims) < 2: <NEW_LINE> <INDENT> return ims, [(0, 0) for i in ims] <NEW_LINE> <DEDENT> if np is None: <NEW_LINE> <INDENT> raise RuntimeError("Need Numpy to calculate sub-rectangles. ") <NEW_LINE> <DEDENT> ims2 = [ims[0]] <NEW_LINE> xy = [(0, 0)] <NEW_LINE> t0 = t... | getSubRectangles(ims)
Calculate the minimal rectangles that need updating each frame.
Returns a two-element tuple containing the cropped images and a
list of x-y positions.
Calculating the subrectangles takes extra time, obviously. However,
if the image sizes were reduced, the actual writing of the GIF
goes faster. I... | 625941e0091ae356686672d3 |
def load_environment(global_conf, app_conf): <NEW_LINE> <INDENT> config = PylonsConfig() <NEW_LINE> root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) <NEW_LINE> paths = dict(root=root, controllers=os.path.join(root, 'controllers'), static_files=os.path.join(root, 'public'), templates=[os.path.join(root... | Configure the Pylons environment via the ``pylons.config``
object | 625941e01d351010ab855e96 |
def cycleTabFocus (self,event=None): <NEW_LINE> <INDENT> trace = False and not g.unitTesting <NEW_LINE> w = self.tabWidget <NEW_LINE> i = w.currentIndex() <NEW_LINE> i += 1 <NEW_LINE> if i >= w.count(): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> <DEDENT> tabName = w.tabText(i) <NEW_LINE> self.selectTab(tabName,createText=Fal... | Cycle keyboard focus between the tabs in the log pane. | 625941e099fddb7c1c9de70a |
def mark_done(self, index): <NEW_LINE> <INDENT> if isinstance(index) != isinstance(0): <NEW_LINE> <INDENT> infex = int(index) <NEW_LINE> <DEDENT> self.__current_list.mark_done(index) | Marks the item in the current list with index specified as done | 625941e067a9b606de4a8232 |
def apply(self, func, keys = False, *args, **kwargs): <NEW_LINE> <INDENT> d1 = self <NEW_LINE> d2 = self.__recreate__(convert_children=False) <NEW_LINE> for k1 in self.keys(): <NEW_LINE> <INDENT> if keys: <NEW_LINE> <INDENT> k2 = func(k1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> k2 = k1 <NEW_LINE> <DEDENT> if isin... | recursively apply func to leaves or all keys of NestD
keys: {True,False} defaults to False, if True, apply func to keys, else apply func to leaves
*args, **kwargs: args and kwargs of func
e.g.
>> NestD({(1,1):{2:{3:4,5:6},'a':9}}).apply(lambda x: 2*x)
{
(1, 1): {
a: 18
2: {
3: 8
5: 12
}
}
}
>> Ne... | 625941e016aa5153ce3627f2 |
def __init__(self, real_label:float=1., fake_label:float=0.): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.real_label = torch.tensor(real_label) <NEW_LINE> self.fake_label = torch.tensor(fake_label) <NEW_LINE> self.loss = nn.MSELoss() | Args:
real_label (float): value for a real image
fake_label (bool): value of a fake image | 625941e08a349b6b435e84ee |
def select_pile(self): <NEW_LINE> <INDENT> return click.prompt( 'Select pile', type=click.IntRange(1, NUM_PILES)) - 1 | Query a pile to be replaced. | 625941e0d6c5a102081443c8 |
def __init__(self, team_slug=None, start=None, end=None, user_logs=None): <NEW_LINE> <INDENT> self.swagger_types = { 'team_slug': 'str', 'start': 'datetime', 'end': 'datetime', 'user_logs': 'list[UserLog]' } <NEW_LINE> self.attribute_map = { 'team_slug': 'teamSlug', 'start': 'start', 'end': 'end', 'user_logs': 'userLog... | OnCallLog - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941e016aa5153ce3627f3 |
def conv3d_ncdhw(Input, Filter, stride, padding, dilation, groups, out_dtype=None): <NEW_LINE> <INDENT> return conv(Input, Filter, stride, padding, dilation, groups, "NCDHW", out_dtype) | Conv3D operator in NCDHW layout.
Parameters
----------
Input : tvm.te.Tensor
5-D with shape [batch, in_channel, in_depth, in_height, in_width]
Filter : tvm.te.Tensor
5-D with shape [num_filter, in_channel, filter_depth, filter_height, filter_width]
stride : int or a list/tuple of three ints
Stride size, ... | 625941e050812a4eaa59c699 |
def get_existing_parent(path): <NEW_LINE> <INDENT> if path == "": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if os.path.exists(path) and not os.path.isfile(path): <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> return get_existing_parent(os.path.dirname(path)) | Return the 1st existing parent for a folder (or itself if the path
exists and is a directory). returns None, when none of the parents exists. | 625941e0a4f1c619b28b03ac |
def _authenticate(self): <NEW_LINE> <INDENT> print('Visit the following URL to authenticate: ' f"www.strava.com/oauth/authorize?client_id={self._client_id}" '&redirect_uri=http://localhost&response_type=code&scope=activity:read_all') <NEW_LINE> response_url = input('Enter the URL you were redirected to: ') <NEW_LINE> o... | Get access to user's activities. | 625941e007f4c71912b117ff |
def _duplicate_exists(self, cleaned_data): <NEW_LINE> <INDENT> collection = cleaned_data.get('collection') <NEW_LINE> source_id = cleaned_data.get('source_id') <NEW_LINE> solr = solr_interface() <NEW_LINE> query = solr.query( content_model=CollectionObject.COLLECTION_CONTENT_MODEL, source_id=source_id, archive_id=colle... | Determine if saving this form would create a duplicate
collection. Specifically, verify that there is no other collection
with the same collection (archive) and source_id present in solr. | 625941e038b623060ff0b168 |
def reset(self, data: int = 0): <NEW_LINE> <INDENT> ... | clears the buffer | 625941e010dbd63aa1bd2f1d |
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): <NEW_LINE> <INDENT> self.use_filter_show = False <NEW_LINE> im = item <NEW_LINE> modelsPosesColl = bpy.context.preferences.addons["phobos"].preferences.models_poses <NEW_LINE> if im.name in modelsPosesColl.keys(): <NEW_LINE> <I... | Args:
context:
layout:
data:
item:
icon:
active_data:
active_propname:
index:
Returns: | 625941e07b180e01f3dc4b72 |
def get_unassigned_students_with_stored_credentials(course_object, experiment): <NEW_LINE> <INDENT> if experiment.course_id != course_object.course_id: <NEW_LINE> <INDENT> raise UNAUTHORIZED_ACCESS <NEW_LINE> <DEDENT> for credential in course_object.credentials.all(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> reques... | Gets the list of students that have not been assigned a track.
This version of the function is for requests that have not come through
a web view and consequently must make a canvas request context from
cached credentials.
Note: Raises NoValidCredentials exception if none of the credentials
work for the API call. Thi... | 625941e0ab23a570cc250500 |
def get_transaction_status(self, tx_id): <NEW_LINE> <INDENT> tx = self.web3.eth.getTransaction(tx_id) <NEW_LINE> if not tx: <NEW_LINE> <INDENT> return TransactionStatus.UNKNOWN <NEW_LINE> <DEDENT> return self._get_tx_status(tx) | Get the transaction status.
:param str tx_id: transaction id (hash).
:returns: transaction status.
:rtype: `~kin.TransactionStatus` | 625941e0bf627c535bc1354a |
def poker(hands): <NEW_LINE> <INDENT> return max(hands, key=hand_rank) | This function is completed for you. Read it to learn the code.
Input: List of 2 or more poker hands
Each poker hand is represented as a list
Print the hands to see the hand representation
Output: Return the winning poker hand | 625941e0c432627299f04fc4 |
def support(request): <NEW_LINE> <INDENT> return TemplateResponse(request, 'help_support.html', {'title': _('Get Support')}) | Serve the support page | 625941e063d6d428bbe4486b |
def test_process_image(self): <NEW_LINE> <INDENT> dataset = tf.data.Dataset.from_tensor_slices({ 'image': tf.constant(np.zeros((3, 3, 3))), 'label': tf.constant(np.zeros((3, 1))) }) <NEW_LINE> dut = DataPreprocessor(dataset) <NEW_LINE> dut.process_image(lambda image, a: image + a + 1, a=1) <NEW_LINE> batch = dut.datase... | Test DataPreprocessor.process_image.
| 625941e0cc0a2c11143dd20c |
def get_lang_count(): <NEW_LINE> <INDENT> return len(settings.LANGUAGES) | Get the no. of supported language by the site
| 625941e0099cdd3c635f0fd4 |
def getdescription(self): <NEW_LINE> <INDENT> return 'display an item' | Returns the command description. | 625941e0287bf620b61d3ddd |
def getOrder(self, orderid): <NEW_LINE> <INDENT> path = '/v1/order/orders/%s' %orderid <NEW_LINE> params = {} <NEW_LINE> func = self.apiGet <NEW_LINE> callback = self.onGetOrder <NEW_LINE> return self.addReq(path, params, func, callback) | 查询某一委托 | 625941e04c3428357757c6a1 |
def __init__(self, tenant_id, subnet_id, subnet_cidr, gateway_ip=None, allocation_pools=None): <NEW_LINE> <INDENT> super(SpecificSubnetRequest, self).__init__( tenant_id=tenant_id, subnet_id=subnet_id, gateway_ip=gateway_ip, allocation_pools=allocation_pools) <NEW_LINE> self._subnet_cidr = netaddr.IPNetwork(subnet_cidr... | Initialize SpecificSubnetRequest
:param subnet: The subnet requested. Can be IPv4 or IPv6. However,
when IPAM tries to fulfill this request, the IP version must match
the version of the address scope being used.
:type subnet: netaddr.IPNetwork or convertible to one | 625941e03d592f4c4ed1d3df |
def reverse(self, x): <NEW_LINE> <INDENT> MIN = -(1<<31) <NEW_LINE> MAX = (1<<31)-1 <NEW_LINE> sign = 1 <NEW_LINE> if x == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if x < 0: <NEW_LINE> <INDENT> sign = -1 <NEW_LINE> x = -x <NEW_LINE> <DEDENT> ret = 0 <NEW_LINE> while x > 0: <NEW_LINE> <INDENT> ret = ret*10 + ... | :type x: int
:rtype: int | 625941e071ff763f4b549a0d |
def findMin(self, nums): <NEW_LINE> <INDENT> low = 0 <NEW_LINE> high = len(nums) - 1 <NEW_LINE> res = nums[0] <NEW_LINE> while low <= high: <NEW_LINE> <INDENT> mid = (low + high) / 2 <NEW_LINE> if nums[mid] <= nums[high]: <NEW_LINE> <INDENT> high = mid - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> low = mid + 1 <NE... | :type nums: List[int]
:rtype: int | 625941e06fece00bbac2dabd |
def test_n_dimensional_log_decoding_CanonLog2(self): <NEW_LINE> <INDENT> clog2 = 0.398254694983167 <NEW_LINE> x = log_decoding_CanonLog2(clog2) <NEW_LINE> clog2 = np.tile(clog2, 6) <NEW_LINE> x = np.tile(x, 6) <NEW_LINE> np.testing.assert_almost_equal( log_decoding_CanonLog2(clog2), x, decimal=7 ) <NEW_LINE> clog2 = np... | Test :func:`colour.models.rgb.transfer_functions.canon_log.log_decoding_CanonLog2` definition n-dimensional arrays support. | 625941e0bd1bec0571d909aa |
def get_lives(self): <NEW_LINE> <INDENT> return self.lives | Function to return the number of lives | 625941e0e1aae11d1e74a035 |
def __init__(self,entityResponse): <NEW_LINE> <INDENT> self.response_json=entityResponse <NEW_LINE> self.code=entityResponse[APIConstants.CODE] <NEW_LINE> self.message=entityResponse[APIConstants.MESSAGE] <NEW_LINE> self.status=entityResponse[APIConstants.STATUS] <NEW_LINE> self.details=None <NEW_LINE> self.data=None <... | Constructor | 625941e0e5267d203edce014 |
def getProjectionObject(self): <NEW_LINE> <INDENT> pass | Returns the projection obect from the baselayer.
| 625941e092d797404e304506 |
def get_upsampling_weight(self, in_channels, out_channels, kernel_size): <NEW_LINE> <INDENT> factor = (kernel_size + 1) // 2 <NEW_LINE> if kernel_size % 2 == 1: <NEW_LINE> <INDENT> center = factor - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> center = factor - 0.5 <NEW_LINE> <DEDENT> og = np.ogrid[:kernel_size, :ke... | Make a 2D bilinear kernel suitable for upsampling | 625941e03d592f4c4ed1d3e0 |
def updateParameters(self, parameters): <NEW_LINE> <INDENT> if not parameters[1].altered: <NEW_LINE> <INDENT> parameters[1].value = self.get_txt_name(parameters[0].valueAsText) <NEW_LINE> <DEDENT> return | Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed. | 625941e0fbf16365ca6f6545 |
def get_new_docking_coord2(MyMoves, ship_id, target_planet_id, old_target_coord, reverse_angle, ): <NEW_LINE> <INDENT> position_matrix = MyMoves.position_matrix[7] <NEW_LINE> planet_center = MyMoves.myMap.data_planets[target_planet_id]['coords'] <NEW_LINE> planet_angle = reverse_angle <NEW_LINE> planet_angle_left = rev... | USING CURVATURE OF PLANET
CLOCKWISE AND COUNTER CLOCKWISE DIRECTIONS
SINCE PREVIOUS COORDINATES ARE ALSO TAKEN | 625941e0bf627c535bc1354b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.