code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def setdefault(self, key, default=None): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> return self._store.setdefault(key, default) | Return value if key available, else default (also setting it). | 625941d3f8510a7c17cf98c3 |
def authenticate(twitter_auth_filename): <NEW_LINE> <INDENT> api_items = loadkeys(filename=twitter_auth_filename) <NEW_LINE> consumer_key, consumer_secret = api_items[0], api_items[1] <NEW_LINE> access_token, access_token_secret = api_items[2], api_items[3] <NEW_LINE> auth = tweepy.OAuthHandler(consumer_key, consumer_s... | Given a file name containing the Twitter keys and tokens,
create and return a tweepy API object. | 625941d3379a373c97cfad0c |
def LDLdecomposition(self): <NEW_LINE> <INDENT> if not self.is_square: <NEW_LINE> <INDENT> raise NonSquareMatrixError("Matrix must be square.") <NEW_LINE> <DEDENT> if not self.is_symmetric(): <NEW_LINE> <INDENT> raise ValueError("Matrix must be symmetric.") <NEW_LINE> <DEDENT> return self._LDLdecomposition() | Returns the LDL Decomposition (L, D) of matrix A,
such that L * D * L.T == A
This method eliminates the use of square root.
Further this ensures that all the diagonal entries of L are 1.
A must be a square, symmetric, positive-definite
and non-singular matrix.
Examples
========
>>> from sympy.matrices import Matrix, ... | 625941d37b25080760e3961f |
def _format_query(self, query, fields): <NEW_LINE> <INDENT> if isinstance(query, dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> items = query.iteritems() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> items = query.items() <NEW_LINE> <DEDENT> query_str = '^'.join(['%s=%s' % (field, value) for field... | The dict-to-string conversion used here was inspired by: https://github.com/locaweb/python-servicenow
:param query: query of type dict or string
:param fields: Comma-separated field names to return in the response
:return: servicenow query string | 625941d3a8370b7717052a65 |
def _filter(self, observation): <NEW_LINE> <INDENT> return observation.feature_screen.unit_hit_points_ratio / 255.0 | Filters out a filter value from the features player unit hit point (HP) array.
We especially pick a ratio version of this and then rescale for the values to stay between zero and one.
Args:
observation: a named list of numpy arrays coming from the environment's step method.
Returns:
A numpy array | 625941d38c0ade5d55d3eb82 |
def test_table_has_column(self): <NEW_LINE> <INDENT> coredb = Database( account=account, release=ENSEMBL_RELEASE, species="human", db_type="core" ) <NEW_LINE> self.assertTrue(coredb.table_has_column("seq_region", "name")) <NEW_LINE> self.assertFalse(coredb.table_has_column("seq_region", "blahblah")) | return correct values for whether a Table has a column | 625941d35e10d32532c5f0ed |
def __init__( self, *, token_id: Optional[str] = None, expiry: Optional[datetime.datetime] = None, name: Optional[Union[str, "TokenPasswordName"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(GenerateCredentialsParameters, self).__init__(**kwargs) <NEW_LINE> self.token_id = token_id <NEW_LINE> self.expiry = expiry <NE... | :keyword token_id: The resource ID of the token for which credentials have to be generated.
:paramtype token_id: str
:keyword expiry: The expiry date of the generated credentials after which the credentials
become invalid.
:paramtype expiry: ~datetime.datetime
:keyword name: Specifies name of the password which should... | 625941d330c21e258bdfa664 |
def scroll_viewport(self): <NEW_LINE> <INDENT> changed = False <NEW_LINE> left_bndry = self.view_left + VIEWPORT_MARGIN <NEW_LINE> if self.player.left < left_bndry: <NEW_LINE> <INDENT> self.view_left -= left_bndry - self.player.left <NEW_LINE> changed = True <NEW_LINE> <DEDENT> right_bndry = self.view_left + SCREEN_WID... | Manage scrolling of the viewport. | 625941d373bcbd0ca4b2c23d |
def test_prompt_number(self): <NEW_LINE> <INDENT> no_prompt_conf = Config( {"TemplateExporter":{ "exclude_input_prompt": True, "exclude_output_prompt": True, } } ) <NEW_LINE> exporter = HTMLExporter(config=no_prompt_conf, template_file='full') <NEW_LINE> (output, resources) = exporter.from_filename( self._get_notebook(... | Does HTMLExporter properly format input and output prompts? | 625941d36e29344779a627d8 |
def set_paddle_up(self): <NEW_LINE> <INDENT> self.paddle_up = True | Set the paddle to move up | 625941d3dd821e528d63b36f |
def _ShouldRecurse(ttype): <NEW_LINE> <INDENT> return ttype in _RECURSE_ON | Returns True if this ttype is one we recurse on for validation. | 625941d366673b3332b92258 |
def initcurrentsupply(self): <NEW_LINE> <INDENT> SCPICommands=['SYST:REM', 'SOUR:VOLT 40.0', 'SOUR:CURR 10.0', 'OUTP 1','SOUR:VOLT 0.0', 'SOUR:CURR 0.0', 'OUTP 0'] <NEW_LINE> self.CurrentON=False <NEW_LINE> self.writeSCPICommand(SCPICommands) | Init current supply, switch it to remote mode, set 0 current and 0 voltage, output off | 625941d3a05bb46b383ec9e8 |
def __init__(self): <NEW_LINE> <INDENT> self.results_filename = utilities.snip(sys.argv[0], 0, ".py") + ".results.log" <NEW_LINE> self.result = "N/A" <NEW_LINE> self.elapsed_time = "N/A" <NEW_LINE> self.number_passed=0 <NEW_LINE> self.number_failed=0 <NEW_LINE> self.number_warning=0 <NEW_LINE> self.number_skipped=0 <NE... | __init__():
This is the initialization constructor for reporting and initalizes the meta data | 625941d356ac1b37e6264394 |
def load_exception(self, exception): <NEW_LINE> <INDENT> self._exception = exception <NEW_LINE> if self._app.has('Exception{}Handler'.format(exception.__class__.__name__)): <NEW_LINE> <INDENT> return self._app.make('Exception{}Handler'.format(exception.__class__.__name__)).handle(exception) <NEW_LINE> <DEDENT> self.han... | Load the exception thrown into this handler.
Arguments:
exception {Exception} -- This is the exception object thrown at runtime. | 625941d37b25080760e39620 |
def test_celery_task(self): <NEW_LINE> <INDENT> output = StringIO() <NEW_LINE> sys.stdout = output <NEW_LINE> synchronize_external_layers.apply() <NEW_LINE> sys.stdout = sys.__stdout__ <NEW_LINE> self.assertIn('does not have an interoperability class specified', output.getvalue()) | ensure celery task works as expected | 625941d382261d6c526ab667 |
def add_new_user(self, movie_ids): <NEW_LINE> <INDENT> self.NEW_USERID += 1 <NEW_LINE> rated_movies = [(self.NEW_USERID, int(i), 5) for i in movie_ids] <NEW_LINE> new_user_ratings_rdd = self.spark_session.parallelize(rated_movies) <NEW_LINE> new_user_ratings_df = new_user_ratings_rdd.toDF(schema=self.columns) <NEW_LINE... | user_id: integer.
id of new user
movie_ids: list.
list of user provided movie ids (string). | 625941d3dc8b845886cb56fc |
def assigned_to_local_ip(self): <NEW_LINE> <INDENT> return self.ip_addr.startswith('127.') | :return: bool | 625941d3be8e80087fb20e08 |
def get_context_data(self, **context): <NEW_LINE> <INDENT> context = super().get_context_data(**context) <NEW_LINE> parent = context['flatpage'].parent <NEW_LINE> if parent is None: <NEW_LINE> <INDENT> breadcrumb_list = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> breadcrumb_list = [context['flatpage']] <NEW_LINE> ... | Returns the template context. Adds breadcrumb to it if neccessary. | 625941d326238365f5f0f036 |
def parse_packet(self): <NEW_LINE> <INDENT> if self.counter == 0: <NEW_LINE> <INDENT> self.counter = int(time.time()) <NEW_LINE> <DEDENT> packet = soup(self.packet) <NEW_LINE> proto = packet.findAll('section')[4].text <NEW_LINE> if proto not in self.protos: <NEW_LINE> <INDENT> self.protos[proto] = 0 <NEW_LINE> <DEDENT>... | This function will parse the needed data from the packet PSML XML
definition and send the data to the API. | 625941d35fcc89381b1e1887 |
def __isClassMethodDef(self): <NEW_LINE> <INDENT> line, col = self.editor.getCursorPosition() <NEW_LINE> indentation = self.editor.indentation(line) <NEW_LINE> curLine = line - 1 <NEW_LINE> if self.__classmethodRX.indexIn(self.editor.text(curLine)) == 0 and self.editor.indentation(curLine) == indentation: <NE... | Private method to check, if the user is defing a class method
(@classmethod).
@return flag indicating the definition of a class method (boolean) | 625941d382261d6c526ab668 |
def get(self, key: int) -> int: <NEW_LINE> <INDENT> index=key%self.size <NEW_LINE> if self.a[index]==None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_Node = self.a[index] <NEW_LINE> while current_Node: <NEW_LINE> <INDENT> if current_Node.key == key: <NEW_LINE> <INDENT> return cu... | Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key | 625941d3ad47b63b2c50a146 |
def build_table(self, itr_daily_data): <NEW_LINE> <INDENT> table = self.table_row_divider <NEW_LINE> try: <NEW_LINE> <INDENT> row = itr_daily_data.next() <NEW_LINE> for value in row: <NEW_LINE> <INDENT> table += "|%s" % value <NEW_LINE> for i in range((self.longest_string + 2) - len(value)): <NEW_LINE> <INDENT> table +... | A Recursive function that takes an iterator of the daily stock data
as an argument. It builds a row of the table cell by cell from the
strings in each iteratorion of the iterator. By calling itself it moves
on to do the next row of the table until it is done | 625941d34f6381625f114c01 |
@advertise(scopes=[], rate_limit=[1000, 3600 * 24]) <NEW_LINE> @bp.route('/icarus/<bibcode>', methods=['GET']) <NEW_LINE> def csl_icarus_format_export_get(bibcode): <NEW_LINE> <INDENT> return return_csl_format_export(solr_data=export_get(bibcode, 'icarus', 2), csl_style='icarus', export_format=adsFormatter.latex, journ... | :param bibcode:
:return: | 625941d385dfad0860c3b022 |
def prob_full(mode="sample"): <NEW_LINE> <INDENT> with open(mode + "_inputs/FULL.txt", "rU") as f: <NEW_LINE> <INDENT> total = float(f.next().strip()) <NEW_LINE> ions = [float(x.strip()) for x in f] <NEW_LINE> <DEDENT> with open("answer.txt", "wb") as g: <NEW_LINE> <INDENT> g.write("".join(rosalind.infer_peptide_from_f... | Inferring Peptide from Full Spectrum | 625941d36aa9bd52df036f6b |
def startup_prep(self, stageid, eventlist): <NEW_LINE> <INDENT> super(MewloTemplateManager,self).startup_prep(stageid, eventlist) <NEW_LINE> if (stageid == mconst.DEF_STARTUPSTAGE_routestart): <NEW_LINE> <INDENT> import mtemplate_jinja2 <NEW_LINE> self.register_templateclass(mtemplate_jinja2.MewloTemplate_Jinja2) | This is invoked by site strtup, for each stage specified in startup_stages_needed() above. | 625941d3091ae35668667123 |
def should_knock(self, signal_type, created=False): <NEW_LINE> <INDENT> should = { 'pre_save': False, 'pre_delete': False, 'post_save': True, 'post_delete': True, } <NEW_LINE> return should[signal_type] | Generic function to tell whether a knock should be emitted.
Override this to avoid emitting knocks under specific circumstances (e.g.: if the object
has just been created or update)
:param signal_type: type of signal between pre_save, post_save, pre_delete, post_delete
:param created: True if the object has been crea... | 625941d3e1aae11d1e749e7f |
def pre_xconv3x3_block(in_channels, out_channels, strides=1, padding=1, dilation=1, groups=1, bn_use_global_stats=False, return_preact=False, activate=True, expand_ratio=2): <NEW_LINE> <INDENT> return PreXConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=3, strides=strides, padding=padding, dil... | 3x3 version of the pre-activated x-convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding valu... | 625941d3cc40096d61595b17 |
def print_maze(maze, final=False): <NEW_LINE> <INDENT> if final: <NEW_LINE> <INDENT> for m in maze: <NEW_LINE> <INDENT> print(''.join(m).replace('X', ' ')) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> for m in maze: <NEW_LINE> <INDENT> print(''.join(m)) | (list, boolean=False) -> (None)
Prints the content of a maze represented by a 2-dimensional list as a matrix, final boolean determines if wrong paths are shown | 625941d3bd1bec0571d907f7 |
def parse_list_or_docstring(options, sps): <NEW_LINE> <INDENT> import py3status.docstrings as docstrings <NEW_LINE> home_path = os.path.expanduser("~") <NEW_LINE> xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config".format(home_path)) <NEW_LINE> options.include_paths = [ "{}/py3status/modules".format(xdg_home... | Handle py3-cmd list and docstring options. | 625941d3be383301e01b564b |
def handle_kill(self, numeric, command, args): <NEW_LINE> <INDENT> new_args = [self._getUid(args[0])] <NEW_LINE> new_args.extend(args[1:]) <NEW_LINE> return super().handle_kill(numeric, command, new_args) | Handles incoming KILLs. | 625941d301c39578d7e75002 |
def build(self): <NEW_LINE> <INDENT> raise NotImplementedError(self.rule.address) | Build the rule. Must be overridden by inheriting class. | 625941d363f4b57ef00012de |
def forward(self, x, h_t_1, h_s_1): <NEW_LINE> <INDENT> batch_size = x.size(0) <NEW_LINE> wh_t_b = self.weight_hh_t(h_t_1[0]) <NEW_LINE> wh_s = self.weight_hh_s(h_s_1[0]) <NEW_LINE> wi = self.weight_ih(x) <NEW_LINE> f_t, f_s, i, o, g = torch.split(wh_t_b + wh_s + wi, split_size=self.hidden_size, dim=1) <NEW_LINE> c = t... | Args:
x: A (batch, input_size) tensor containing input
features.
h_t_1: A tuple (h_t_1, c_t_1), in temporal dimension
h_s_1: A tuple (h_0, c_0), in spatial dimension
Returns:
h_1, c_1: Tensors containing the next hidden and cell state. | 625941d35fdd1c0f98dc03fb |
def spin_once(self, return_first_path): <NEW_LINE> <INDENT> self.curr_iter += 1 <NEW_LINE> rand_node = self.get_rand_node() <NEW_LINE> nearest_id = self.get_nearest_node_id(rand_node) <NEW_LINE> near_node = self.node_list[nearest_id] <NEW_LINE> new_node = self.steer(near_node, rand_node) <NEW_LINE> if new_node is not N... | Perform one iteration of tree-expansion and path-planning. | 625941d3236d856c2ad449a3 |
def create_volume_from_snapshot(self, volume, snapshot): <NEW_LINE> <INDENT> snapshot_name = self._name_translate(snapshot['name']) <NEW_LINE> volume_name = self._name_translate(volume['name']) <NEW_LINE> LOG.debug(_('create_volume_from_snapshot: snapshot ' 'name: %(snapshot)s, volume name: %(volume)s.') % {'snapshot':... | Create a volume from a snapshot.
We use LUNcopy to copy a new volume from snapshot.
The time needed increases as volume size does. | 625941d3187af65679ca52e7 |
def validate_title(self, field): <NEW_LINE> <INDENT> existing = set([simplify_text(c.title) for c in Category.query.filter_by(workspace=g.workspace).all() if c != self.edit_obj]) <NEW_LINE> if simplify_text(field.data) in existing: <NEW_LINE> <INDENT> raise wtforms.ValidationError("You have an existing category with th... | If the title is already in use, refuse to add this one. | 625941d37c178a314d6ef628 |
def do_something_useful(self: Component) -> int: <NEW_LINE> <INDENT> print("Делаем что-то полезное Component.") <NEW_LINE> return 2 | Делаем что-то полезное. | 625941d30a366e3fb873e9e2 |
def word_database_search(word, global_word_list, char_freq): <NEW_LINE> <INDENT> regex = '^' + word.replace('_', '[a-z]') + '$' <NEW_LINE> for list_word in global_word_list: <NEW_LINE> <INDENT> if len(list_word) == len(word)+1: <NEW_LINE> <INDENT> result = re.search(regex, list_word, re.IGNORECASE) <NEW_LINE> if resul... | This is the most important function. This is responsible
for finding all the words that are a potential match for
the current state and based on that updating the char freq
mapping.
Return -> None | 625941d338b623060ff0afb5 |
def get_background_rgb(self): <NEW_LINE> <INDENT> return Color.to_rgb(self.background) | Returns the panel's background color as an RGB tuple. Default is white.
@return: color as a 3-element rgb tuple such as (255, 0, 192)
@rtype: tuple | 625941d3796e427e537b078e |
def _get_l2_gw_multiple_interface_without_seg_id_data(self, name, device_name): <NEW_LINE> <INDENT> return {"l2_gateway": {"name": name, "devices": [{"interfaces": [{"name": "port1"}, {"name": "port2"}], "device_name": device_name}]}} | Get l2 gateway data helper method with partial seg id. | 625941d3656771135c3eba37 |
def CreateFromCornerPoints1(corner1, corner2, corner3, corner4, tolerance, multiple=False): <NEW_LINE> <INDENT> url = "rhino/geometry/brep/createfromcornerpoints-point3d_point3d_point3d_point3d_double" <NEW_LINE> if multiple: url += "?multiple=true" <NEW_LINE> args = [corner1, corner2, corner3, corner4, tolerance] <NEW... | Makes a Brep with one face from four corner points.
Args:
corner1 (Point3d): A first corner.
corner2 (Point3d): A second corner.
corner3 (Point3d): A third corner.
corner4 (Point3d): A fourth corner.
tolerance (double): Minimum edge length allowed before collapsing the side into a singularity.
Ret... | 625941d31f5feb6acb0c4d16 |
def __init__(self, model, beta, S0, mean_signal): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.beta = beta <NEW_LINE> self.S0 = S0 <NEW_LINE> self.mean_signal = mean_signal | Initalize a SparseFascicleFit class instance
Parameters
----------
model : a SparseFascicleModel object.
beta : ndarray
The parameters of fit to data.
S0 : ndarray
The mean non-diffusion-weighted signal.
mean_signal : ndarray
The mean of the diffusion-weighted signal | 625941d3796e427e537b078f |
def rmse(groundt, predicted): <NEW_LINE> <INDENT> return tf.sqrt( tf.reduce_mean(tf.square(tf.cast(groundt, tf.float32) - tf.cast(predicted, tf.float32))) ) | Computes the RMSE of the input arrays | 625941d38e05c05ec3eea53e |
def get_config_fpath(): <NEW_LINE> <INDENT> if os.getenv(CONFIG_FPATH_ENV, None) is None: <NEW_LINE> <INDENT> fpath = CONFIG_FPATH <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fpath = os.getenv(CONFIG_FPATH_ENV) <NEW_LINE> <DEDENT> return fpath | Get the configuration file path.
:returns: string | 625941d3d6c5a10208144214 |
def lossFun(inputs, targets, hprev): <NEW_LINE> <INDENT> xs, hs, ys, ps = {}, {}, {}, {} <NEW_LINE> hs[-1] = np.copy(hprev) <NEW_LINE> loss = 0 <NEW_LINE> for t in range(len(inputs)): <NEW_LINE> <INDENT> xs[t] = np.zeros((vocab_size, 1)) <NEW_LINE> xs[t][inputs[t]] = 1 <NEW_LINE> hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np... | inputs,targets are both list of integers.
hprev is Hx1 array of initial hidden state
returns the loss, gradients on model parameters, and last hidden state | 625941d367a9b606de4a8081 |
def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self.user, name) | Allow people to use the User attribute on CUV | 625941d3442bda511e8be5de |
def _embeddings_from_arguments(column, args, weight_collections, trainable, output_rank=2): <NEW_LINE> <INDENT> input_tensor = layers._inner_flatten(args.input_tensor, output_rank) <NEW_LINE> weight_tensor = None <NEW_LINE> if args.weight_tensor is not None: <NEW_LINE> <INDENT> weight_tensor = layers._inner_flatten(arg... | Returns embeddings for a column based on the computed arguments.
Args:
column: the column name.
args: the _DeepEmbeddingLookupArguments for this column.
weight_collections: collections to store weights in.
trainable: whether these embeddings should be trainable.
output_rank: the desired rank of the returned `Outp... | 625941d3442bda511e8be5df |
def tearDown(self): <NEW_LINE> <INDENT> Login.login=[] | tearDown method that does clean up after each test case has run. | 625941d3a79ad161976cc30d |
def test_index(client, auth): <NEW_LINE> <INDENT> response = client.get('/') <NEW_LINE> assert b"Log In" in response.data <NEW_LINE> assert b"Register" in response.data <NEW_LINE> auth.login() <NEW_LINE> response = client.get('/') <NEW_LINE> assert b'Log Out' in response.data <NEW_LINE> assert b'test title' in response... | Tests whether index page has features which should appear, both before and after logging in. | 625941d30a366e3fb873e9e3 |
def sanitize_hostname(hostname): <NEW_LINE> <INDENT> if is_unicode(hostname): <NEW_LINE> <INDENT> hostname = hostname.encode('latin-1', 'ignore') <NEW_LINE> if PY3: <NEW_LINE> <INDENT> hostname = hostname.decode('latin-1') <NEW_LINE> <DEDENT> <DEDENT> hostname = re.sub('[ _]', '-', hostname) <NEW_LINE> hostname = re.su... | Return a hostname which conforms to RFC-952 and RFC-1123 specs. | 625941d3b545ff76a8913fdd |
def test_features_by_ranking(dataset, y, clf, kf, clf_name): <NEW_LINE> <INDENT> global_results = {} <NEW_LINE> for feature in dataset.columns: <NEW_LINE> <INDENT> if(feature not in FEATURES): <NEW_LINE> <INDENT> print(feature) <NEW_LINE> test = FEATURES[:] <NEW_LINE> test.append(feature) <NEW_LINE> X = dataset[test] <... | This method is responsible for one iteration of the ranking algorithm.
It tests all unused features combined with the already chosen features,
one at a time.
The output is a i.txt file with the results for the ith iteration. | 625941d329b78933be1e5872 |
def has(self, key): <NEW_LINE> <INDENT> raise NotImplementedError | Check whether the index has a given key in it
Args:
key: Key to check for
Returns:
True if the key exists, else False | 625941d3d4950a0f3b08c516 |
def workflowRun(*args, **kwargs): <NEW_LINE> <INDENT> print("dxpy.workflowRun is deprecated; please use workflow_run instead.", file=sys.stderr) <NEW_LINE> return workflow_run(*args, **kwargs) | .. deprecated:: 0.42.0
Use :func:`workflow_run()` instead. | 625941d3d58c6744b4257e27 |
def read_triangle_mesh(filename): <NEW_LINE> <INDENT> fid = open(filename + ".node", "r") <NEW_LINE> nn = int( fid.readline().split()[0] ) <NEW_LINE> x = np.zeros(nn) <NEW_LINE> y = np.zeros(nn) <NEW_LINE> bnd = np.zeros(nn, dtype = np.int32) <NEW_LINE> for i in range(nn): <NEW_LINE> <INDENT> line = fid.readline().spli... | Function to read in an unstructured grid in Triangle's format.
Arguments
=========
filename: stem for the Triangle files, e.g. for the triangulation stored
in the files {path/my_tri.node, path/my_tri.ele, ...}, this
would be `path/my_tri`.
Returns
=======
x, y: coordinates of the triangulation
ele... | 625941d3d8ef3951e3243705 |
def get_moved_in(self, unit: int = None) -> JSONType: <NEW_LINE> <INDENT> return self.__get_JSON(self.__endpoint('moved-in', unit=unit)) | Returns the unit list of recently moved in members
Parameters
unit : int
Number of the church unit for which to retrieve the report
Returns
.. literalinclude:: ../JSON_schemas/get_moved_in-schema.md | 625941d37047854f462a15d0 |
def spell_checker(line: str) -> Tuple[int, int]: <NEW_LINE> <INDENT> stack = [] <NEW_LINE> matching_char = {"(": ")", "{": "}", "[": "]", "<": ">"} <NEW_LINE> corrupt_points = {")": 3, "]": 57, "}": 1197, ">": 25137} <NEW_LINE> incomplete_points = {"(": 1, "[": 2, "{": 3, "<": 4} <NEW_LINE> for char in line: <NEW_LINE>... | Returns a tuple of points: pt1_score, pt2_score. | 625941d3009cb60464c63579 |
def Dev_L_layer_model(X, Y, layers_dims, parameters, learning_rate = 0.0075, num_iterations = 3000, print_cost=True): <NEW_LINE> <INDENT> np.random.seed(1) <NEW_LINE> costs = [] <NEW_LINE> for i in range(0, num_iterations): <NEW_LINE> <INDENT> AL, caches = L_model_forward(X, parameters) <NEW_LINE> cost = compute_cost(A... | Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
Arguments:
X -- data, numpy array of shape (number of examples, num_px * num_px * 3)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
layers_dims -- list containing the input size and each layer si... | 625941d3d53ae8145f87a436 |
def create(self, album_id): <NEW_LINE> <INDENT> if not album_id: <NEW_LINE> <INDENT> raise ValueError('Album id is required') <NEW_LINE> <DEDENT> filename = os.path.join(settings.MEDIA_ROOT, 'zipfiles/{}.zip'.format(uuid4())) <NEW_LINE> photos = Photo.objects.filter(albums=album_id).values_list('filename', flat=True) <... | Overrides create method of models.Manager
by including compression of images. | 625941d3cb5e8a47e48b7c70 |
def __init__(self): <NEW_LINE> <INDENT> self.uplateau = {} <NEW_LINE> self.joueurs = [] <NEW_LINE> self.joueur_courant = None <NEW_LINE> self.nb_parties_nulles = 0 <NEW_LINE> self.initialiser() | Méthode spéciale initialisant une nouvelle partie du jeu Ultimate Tic-Tac-Toe. | 625941d36fece00bbac2d907 |
@data_loader("wcs1d-fits", identifier=identify_wcs1d_fits, dtype=Spectrum1D, extensions=['fits', 'fit'], priority=5) <NEW_LINE> def wcs1d_fits_loader(file_obj, spectral_axis_unit=None, flux_unit=None, hdu=0, **kwargs): <NEW_LINE> <INDENT> logging.info("Spectrum file looks like wcs1d-fits") <NEW_LINE> with read_fileobj_... | Loader for single spectrum-per-HDU spectra in FITS files, with the spectral
axis stored in the header as FITS-WCS. The flux unit of the spectrum is
determined by the 'BUNIT' keyword of the HDU (if present), while the
spectral axis unit is set by the WCS's 'CUNIT'.
Parameters
----------
file_obj: str, file-like or HDU... | 625941d3cc0a2c11143dd059 |
def __invoke_init(self, transaction, block, params): <NEW_LINE> <INDENT> self.logd('__invoke_init() start') <NEW_LINE> self.logd(f'{str(params)}') <NEW_LINE> if self.__initialized: <NEW_LINE> <INDENT> raise IcxError(Code.INVALID_TRANSACTION, 'icx_score has been already initialized.') <NEW_LINE> <DEDENT> address = param... | Initialize the value of account.
:param transaction: Transaction data.
:param block: Block data.
:param params: params from transaction data including 'address' and'value'. | 625941d34428ac0f6e5ba9bb |
def remove_stub_mapping(self, mapping_id): <NEW_LINE> <INDENT> url = '{}/mappings/{}'.format(self._base_url, mapping_id) <NEW_LINE> requests.delete(url) | Delete a stub mapping | 625941d356b00c62f0f14822 |
def _load_pressure_and_shear(self) -> None: <NEW_LINE> <INDENT> self.x_coord, self.pressure, self.shear_stress = np.loadtxt( str(self.simulation.it_dir / f"pressureAndShear.{self.config.io.data_format}"), unpack=True, ) <NEW_LINE> for el in [el for patch in self.planing_surfaces for el in patch.pressure_elements]: <NEW... | Load pressure and shear stress from file. | 625941d3f8510a7c17cf98c4 |
def _make_refresh(page, delay=3): <NEW_LINE> <INDENT> if page is None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> return _REFRESH % (delay, page) | Generate an appropriate <meta refresh=''> tag. If page is None, the
empty string will be returned.
Parameters:
page - page to redirect to
delay - delay in seconds (default: 3) | 625941d36fece00bbac2d908 |
def test_getLatestData(self): <NEW_LINE> <INDENT> print('## TESTING THE OPERATION OF THE getLatestData METHOD ##') <NEW_LINE> instance=AutomationVariables(**AutomationVariablesDict) <NEW_LINE> now=timezone.now().replace(microsecond=0) <NEW_LINE> instance.store2DB() <NEW_LINE> newValue=25 <NEW_LINE> InsertRegister2DB(DB... | getLatestData: method provided to retrieve the latest DB data of the var: | 625941d37d847024c06be485 |
def set_retry(self, attempt_number): <NEW_LINE> <INDENT> self.resource['metadata']['attempt_number'] = attempt_number | Setting retry attempt number | 625941d30c0af96317bb83b0 |
def nextGreaterElement(self, nums1, nums2): <NEW_LINE> <INDENT> r_list = [] <NEW_LINE> for item in nums1: <NEW_LINE> <INDENT> r_list.append(next((j for j in nums2[nums2.index(item):] if j > item),-1)) <NEW_LINE> <DEDENT> return r_list | :type nums1: List[int]
:type nums2: List[int]
:rtype: List[int] | 625941d34e4d5625662d459f |
def _read_data(self, fp, dtype, count=-1): <NEW_LINE> <INDENT> raise NotImplementedError('') | Construct an array from data in a binary file.
Parameters
----------
file : file
Open file object
dtype : data-type
Data type of the returned array.
Used to determine the size and byte-order of the items in the file.
count : int
Number of items to read. ``-1`` means all items (i.e., the complete
fi... | 625941d39b70327d1c4e0f9e |
def log_tags(self, ocromore_data, accumulated_tags): <NEW_LINE> <INDENT> my_results = ocromore_data['results'] <NEW_LINE> res_object = my_results.my_object <NEW_LINE> final_tags = {} <NEW_LINE> for key in res_object: <NEW_LINE> <INDENT> my_keys = [] <NEW_LINE> if "overall_info" in key: <NEW_LINE> <INDENT> continue <NEW... | Gets the all tags from the current result object in ocromore data
and the adds them (counted) in the accumulated tags segment
:param ocromore_data: data block with results
:param accumulated_tags: dictionary to collect accumulated taglist
:return: accumulated_tags -> input object + added tags | 625941d33d592f4c4ed1d233 |
def describe_api_stages(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) <NEW_LINE> stages = conn.get_stages(restApiId=restApiId, deploymentId=deploymentId) <NEW_LINE> return {'s... | Get all API stages for a given apiID and deploymentID
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.describe_api_stages restApiId deploymentId | 625941d38e7ae83300e4b195 |
def atomic_charges( self, D, ): <NEW_LINE> <INDENT> V = ls.Tensor.chain([self.A, self.S, D, self.S, self.A], [True, False, False, False, False]) <NEW_LINE> V2 = np.diag(V) <NEW_LINE> Q = ls.Tensor((self.minbasis.natom,), 'Q IBO') <NEW_LINE> for A, inds2 in enumerate(self.minao_inds): <NEW_LINE> <INDENT> Q[A] = np.sum(V... | Compute the atomic charges Q_A for an OPDM D_mn.
Only the electronic contribution is considered.
Params:
D (ls.Tensor of shape (nao, nao)) - density matrix
Returns:
Q (ls.Tensor of shape (natom,)) - atomic charges | 625941d3498bea3a759b9c77 |
def burn(self): <NEW_LINE> <INDENT> if not self.data: <NEW_LINE> <INDENT> raise ValueError("No data available") <NEW_LINE> <DEDENT> if hasattr(self, 'calculations'): <NEW_LINE> <INDENT> self.calculations() <NEW_LINE> <DEDENT> self.start_svg() <NEW_LINE> self.calculate_graph_dimensions() <NEW_LINE> self.foreground = etr... | Process the template with the data and
config which has been set and return the resulting SVG.
Raises ValueError when no data set has
been added to the graph object. | 625941d310dbd63aa1bd2d6b |
def _generate_word_list(): <NEW_LINE> <INDENT> words = [] <NEW_LINE> with open(FILE) as f: <NEW_LINE> <INDENT> for line in f.readlines(): <NEW_LINE> <INDENT> words.append(line.strip().lower()) <NEW_LINE> <DEDENT> <DEDENT> return words | Read in English words from <FILE> and return them.
The returned list is in alphabetical order.
@rtype: list[str] | 625941d3eab8aa0e5d26dd21 |
def get_queryset(self): <NEW_LINE> <INDENT> queryset = self.queryset.all() <NEW_LINE> queryset = queryset.select_related('customer', 'pdf', 'acknowledgement', 'employee', 'project', 'deal', ) <NEW_LINE> queryset = queryset.prefetch_related('items', 'items__pillows', 'items__image', 'items__product', 'customer__addresse... | Override 'get_queryset' method in order to customize filter | 625941d39f2886367277aa55 |
def print_block(msgitems, singlevalue=None): <NEW_LINE> <INDENT> if singlevalue: <NEW_LINE> <INDENT> print('{:>4}: {}'.format(msgitems, singlevalue)) <NEW_LINE> return None <NEW_LINE> <DEDENT> maxlen = len(max((k for k, _ in msgitems), key=len)) <NEW_LINE> indent = ' ' * maxlen <NEW_LINE> for k, v in msgitems: <NEW_LIN... | Print key: value style messages. | 625941d3e8904600ed9f20f6 |
def check_networks(self, req): <NEW_LINE> <INDENT> cfg = self.check_config <NEW_LINE> networks = self._get_networks_from_request(req) <NEW_LINE> if cfg.strict_boot_check and networks is None: <NEW_LINE> <INDENT> networks = set() <NEW_LINE> <DEDENT> if networks is None: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> ... | Checks required/banned/count of networks. | 625941d326068e7796caeea9 |
def total_pojedeni_otrovi(model): <NEW_LINE> <INDENT> agents = izdvoji_agente(model) <NEW_LINE> ukupno = 0 <NEW_LINE> for agent in agents: <NEW_LINE> <INDENT> ukupno+=agent.pojedeni_otrovi <NEW_LINE> <DEDENT> return ukupno | Vraca broj ukupnih pojedenih otrova | 625941d3090684286d50eeaf |
def remove_annotation_from_index(self, annotation: FeatureStructure): <NEW_LINE> <INDENT> self._indices[annotation.type.name].remove(annotation) | Removes an annotation from an index. This throws if the
annotation was not present.
Args:
annotation: The annotation to remove. | 625941d3596a897236089c88 |
def init_game_setting(self): <NEW_LINE> <INDENT> self.t = 0 | Testing function will call this function at the begining of new game
Put anything you want to initialize if necessary | 625941d3fff4ab517eb2f605 |
def create_gcs_if_not_exists(bucket_name, region, project_id): <NEW_LINE> <INDENT> credentials = GoogleCredentials.get_application_default() <NEW_LINE> client = discovery.build('storage', 'v1', credentials=credentials) <NEW_LINE> try: <NEW_LINE> <INDENT> client.buckets().get(bucket=bucket_name).execute() <NEW_LINE> <DE... | Creates a GCS bucket if it does not exist. | 625941d3de87d2750b85ff5c |
def fetch_risk_fxqyts_now(self): <NEW_LINE> <INDENT> url = "http://60.1.100.2/crristdetail/doReadWarningListJSON.do" <NEW_LINE> fetch_risk_info.log('now crawling 本月风险企业提示类预警提示') <NEW_LINE> fxqyts_now_info = OrderedDict() <NEW_LINE> idxSupCodeList = ["A02", "B02", "C02", "C04", "D01", "E01", "E07", ] <NEW_LINE> try: <NE... | 风险企业提示类预警提示本月 | 625941d3f8510a7c17cf98c5 |
def test_get_logical_router_status(self): <NEW_LINE> <INDENT> pass | Test case for get_logical_router_status
Get the status for the Logical Router of the given id # noqa: E501 | 625941d3e64d504609d74a08 |
def test_404_if_disabled(self, _mock_get_programs, _mock_get_pathways): <NEW_LINE> <INDENT> self.create_programs_config(enabled=False) <NEW_LINE> response = self.client.get(self.url) <NEW_LINE> self.assertEqual(response.status_code, 404) | Verify that the page 404s if disabled. | 625941d3507cdc57c6306ea5 |
def visit_docbook_informalequation(self, element, depth): <NEW_LINE> <INDENT> attrib = {} <NEW_LINE> attrib[html.class_] = 'db-equation' <NEW_LINE> return self.new_copy(moin_page('div'), element, depth, attrib=attrib) | <informalequation> --> <div html:class="equation"> | 625941d3d164cc6175782f17 |
def writeGifToFile(self, fp, images, durations, loops, xys, disposes): <NEW_LINE> <INDENT> palettes, occur = [], [] <NEW_LINE> for im in images: <NEW_LINE> <INDENT> palettes.append(im.im.getpalette()) <NEW_LINE> <DEDENT> for palette in palettes: <NEW_LINE> <INDENT> occur.append(palettes.count(palette)) <NEW_LINE> <DEDE... | writeGifToFile(fp, images, durations, loops, xys, disposes)
Given a set of images writes the bytes to the specified stream. | 625941d3379a373c97cfad0e |
def _parse_data(data, null): <NEW_LINE> <INDENT> data = [row.rstrip('\r\n') for row in data] <NEW_LINE> data = [row for row in data if row] <NEW_LINE> data = [row.split('\t') for row in data] <NEW_LINE> data = chain(*data) <NEW_LINE> data = list(data) <NEW_LINE> data = [null[value] if value in null.keys() else value fo... | .. Parse data from input.
Parameters
----------
data : list
Input data to parse.
null : dict
Dictionary of null characters and their replacements.
If replaced with ``None`` then remove value from data.
Returns
-------
data : list
List of data values from input. | 625941d3377c676e91272371 |
@benchmark.command() <NEW_LINE> @argument("url") <NEW_LINE> @argument("numjobs") <NEW_LINE> @argument("numfiles") <NEW_LINE> def read(url, numjobs, numfiles): <NEW_LINE> <INDENT> _setup_logging() <NEW_LINE> numjobs = positive_int(numjobs, 'NUMJOBS') <NEW_LINE> fmt, numfiles = _get_pattern_and_numfiles(numfiles) <NEW_LI... | Test reading files from parallel jobs. | 625941d35fcc89381b1e1888 |
@pytest.fixture <NEW_LINE> def mysql_restart_test(cmdopt_hostname, cmdopt_login, cmdopt_password): <NEW_LINE> <INDENT> command("systemctl restart mysql", cmdopt_hostname, cmdopt_login, cmdopt_password) <NEW_LINE> retcode, stdout, stderr = command("systemctl is-active mysql", cmdopt_hostname, cmdopt_login, cmdopt_passwo... | MySQL restart fixture | 625941d3b57a9660fec33a4e |
def is_field(self, proof = True): <NEW_LINE> <INDENT> return True | Return ``True``, since the rational field is a field.
EXAMPLES::
sage: QQ.is_field()
True | 625941d37b25080760e39621 |
def all_yes(self): <NEW_LINE> <INDENT> results = self.yes() <NEW_LINE> classifications = [cc.classification for cc in results] <NEW_LINE> for p in self.parents(): <NEW_LINE> <INDENT> for cc in p.yes(): <NEW_LINE> <INDENT> if cc.classification not in classifications: <NEW_LINE> <INDENT> results.append(cc) <NEW_LINE> cla... | include parents | 625941d3711fe17d82542532 |
def __init__(self, master=None): <NEW_LINE> <INDENT> super().__init__(master) <NEW_LINE> self.master = master <NEW_LINE> self.pack() <NEW_LINE> self.width=450 <NEW_LINE> self.height=300 <NEW_LINE> self.x = 0 <NEW_LINE> self.y = 0 <NEW_LINE> self.bgcolor="#000000" <NEW_LINE> self.fgcolor = "#FF0000" <NEW_LINE> self.last... | Constructor | 625941d3b7558d58953c50db |
def parse_tuple(tuple_string): <NEW_LINE> <INDENT> return tuple_string.strip().strip("\"[]") | strip any whitespace then outter characters. | 625941d373bcbd0ca4b2c23f |
def kbs(self): <NEW_LINE> <INDENT> return self._speed / 1024 | Return the speed in kB/s
:returns: a float | 625941d399fddb7c1c9de559 |
def check_id_card(id_card: str) -> bool: <NEW_LINE> <INDENT> pattern_18 = r'[1-9]\d{5}[12]\d{3}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9xX]' <NEW_LINE> pattern_15 = r'[1-9]\d{7}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}' <NEW_LINE> if len(id_card) == 18 and fullmatch(pattern_18, id_card): <NEW_LINE> <INDENT> value =... | 检查身份证号码格式是否正确 | 625941d3507cdc57c6306ea6 |
def get_config( argv, cwd=None ): <NEW_LINE> <INDENT> if argv and (argv[-1] in DATABASE): <NEW_LINE> <INDENT> database = argv.pop() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> database = 'galaxy' <NEW_LINE> <DEDENT> database_defaults = DATABASE[ database ] <NEW_LINE> default = database_defaults.get( 'config_file', DE... | Read sys.argv and parse out repository of migrations and database url.
>>> import os
>>> from ConfigParser import SafeConfigParser
>>> from tempfile import mkdtemp
>>> config_dir = mkdtemp()
>>> os.makedirs(os.path.join(config_dir, 'config'))
>>> def write_ini(path, property, value):
... p = SafeConfigParser()
...... | 625941d3435de62698dfde16 |
def normpath(path, case_normalize=False): <NEW_LINE> <INDENT> if not is_unicode(path): <NEW_LINE> <INDENT> path = decode_from_system(path) <NEW_LINE> <DEDENT> path = os.path.normpath(path) <NEW_LINE> if case_normalize and CASE_INSENSITIVE_FILESYSTEM: <NEW_LINE> <INDENT> path = path.lower() <NEW_LINE> <DEDENT> if WINDOW... | Replacement for os.path.normpath with some enhancements.
1. Non-Unicode paths are converted to Unicode using file system encoding.
2. Optionally lower-case paths on case-insensitive file systems.
That includes Windows and also OSX in default configuration.
3. Turn ``c:`` into ``c:\`` on Windows instead of keeping i... | 625941d3fbf16365ca6f6390 |
def _check_user_uniqueness(self, user_data: dict) -> bool: <NEW_LINE> <INDENT> if user_data.get(self.unique_user_filter_field): <NEW_LINE> <INDENT> unique_field_value = user_data.get(self.unique_user_filter_field) <NEW_LINE> unique_field = self.unique_user_filter_field + "__iexact" <NEW_LINE> filter_kwargs = {unique_fi... | Helper function that checks if the supplied user data is unique. If user_data does not
contain the unique user field the assumption is that the user
exists. | 625941d363d6d428bbe446b8 |
def get_conf_output (self): <NEW_LINE> <INDENT> return self.distribution.get_conf_filename(self.install_lib) | Get name of configuration file. | 625941d3dc8b845886cb56fe |
def flattening(self,R,z): <NEW_LINE> <INDENT> return nu.sqrt(nu.fabs(z/R*self.Rforce(R,z)/self.zforce(R,z))) | NAME:
flattening
PURPOSE:
calculate the potential flattening, defined as sqrt(|z/R F_R/F_z|)
INPUT:
R - Galactocentric radius
z - height
OUTPUT:
flattening
HISTORY:
2012-09-13 - Written - Bovy (IAS) | 625941d33539df3088e2e514 |
def read_city_data(path): <NEW_LINE> <INDENT> raw_cities = read_json(path) <NEW_LINE> cities = {} <NEW_LINE> for n in raw_cities['features']: <NEW_LINE> <INDENT> coords = np.array([c for c in n['geometry']['coordinates'][0][0]]) <NEW_LINE> if coords.shape[1] == 3: <NEW_LINE> <INDENT> coords = coords[:, :-1] <NEW_LINE> ... | Maps the neighborhoods of the city from the provided data
so each entry contains a map between the neighborhood and the
polygon delimiting it | 625941d392d797404e304353 |
def create_db(): <NEW_LINE> <INDENT> engine = create_engine('sqlite:///data\\dota_analysis.db', echo=True) <NEW_LINE> Base = declarative_base() <NEW_LINE> class Matches(Base): <NEW_LINE> <INDENT> __tablename__ = 'matches' <NEW_LINE> match_id = Column(Integer, primary_key=True) <NEW_LINE> barracks_status_dire = Column(I... | Create DB for storing match data. | 625941d385dfad0860c3b024 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.