code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def strip_dir_path(source, dirname): <NEW_LINE> <INDENT> prefix = "" <NEW_LINE> prefix = dirname.replace(source, "") <NEW_LINE> if prefix != "": <NEW_LINE> <INDENT> prefix += "/" <NEW_LINE> if prefix.startswith("/"): <NEW_LINE> <INDENT> prefix = prefix[1:] <NEW_LINE> <DEDENT> <DEDENT> return prefix | Keep the folder structure after the path folder by
a) appending a '/' at the end of directory names
b) removing the first character from a directory name if it is a '/'
The result should look like this:
file1.txt
folder1/
folder1/folder2/
folder1/folder2/file2.txt | 625941cea4f1c619b28b0158 |
def error_gradient(self, x_i, y_i, beta): <NEW_LINE> <INDENT> return [x_ij * self.error(x_i, y_i, beta) for x_ij in x_i] | the gradient corresponding to the ith squared error term
| 625941cef9cc0f698b14071b |
def calculate_entropy(df, debug=False): <NEW_LINE> <INDENT> cter = collections.Counter(d[-1] for d in df).values() <NEW_LINE> _sum = sum(cter) <NEW_LINE> return sum(- (c * 1.0 / _sum) * math.log(c * 1.0 / _sum, 2) for c in cter) | Calculates entropy of the passed `list`
| 625941cebf627c535bc132ee |
def __init__(self, state=None, messages=None, progress=None, ): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.messages = messages <NEW_LINE> self.progress = progress <NEW_LINE> VapiStruct.__init__(self) | :type state: :class:`Job.BackupRestoreProcessState`
:param state: process state
:type messages: :class:`list` of :class:`Job.LocalizableMessage`
:param messages: list of messages
:type progress: :class:`long`
:param progress: percentage complete | 625941ce9f2886367277a9ac |
def to_table(self, format="ogip"): <NEW_LINE> <INDENT> table = self.axes["energy_true"].to_table(format=format) <NEW_LINE> rows = self.pdf_matrix.shape[0] <NEW_LINE> n_grp = [] <NEW_LINE> f_chan = np.ndarray(dtype=np.object, shape=rows) <NEW_LINE> n_chan = np.ndarray(dtype=np.object, shape=rows) <NEW_LINE> matrix = np.... | Convert to `~astropy.table.Table`.
The output table is in the OGIP RMF format.
https://heasarc.gsfc.nasa.gov/docs/heasarc/caldb/docs/memos/cal_gen_92_002/cal_gen_92_002.html#Tab:1
Parameters
----------
format : {"ogip", "ogip-sherpa"}
Format to use.
Returns
-------
table : `~astropy.table.Table`
Matrix table | 625941ce63d6d428bbe4460f |
def addBinary(self, a, b): <NEW_LINE> <INDENT> a_l = list(a) <NEW_LINE> b_l = list(b) <NEW_LINE> a_l.reverse() <NEW_LINE> b_l.reverse() <NEW_LINE> i_a, l_a = 0, len(a_l) <NEW_LINE> i_b, l_b = 0, len(b_l) <NEW_LINE> tag = 0 <NEW_LINE> res = [] <NEW_LINE> while (i_a < l_a) or (i_b < l_b) or (tag != 0): <NEW_LINE> <INDENT... | :type a: str
:type b: str
:rtype: str | 625941cebe7bc26dc91cd71f |
def add(self, contact, options=["done"]): <NEW_LINE> <INDENT> touchImage('ButtonAddContact') <NEW_LINE> time.sleep(1) <NEW_LINE> touchImage('EntryFirstname') <NEW_LINE> enter(contact.getFirstname()) <NEW_LINE> time.sleep(1) <NEW_LINE> touchImage('EntryLastname') <NEW_LINE> enter(contact.getLastname()) <NEW_LINE> time.s... | Add contact | 625941ced268445f265b4f8d |
def _get_backup_folders_sorted(backups_folder: Path) -> List[Path]: <NEW_LINE> <INDENT> regex = re.compile(r'\d{4}-\d{2}-\d{2}T\d{1,2}:\d{2}') <NEW_LINE> folders = [folder for folder in backups_folder.iterdir() if folder.is_dir() and regex.match(folder.name)] <NEW_LINE> folders.sort() <NEW_LINE> return [folder.absolute... | Gets the backups folders sorted. | 625941cecb5e8a47e48b7bca |
def addListener(self, channel, callback): <NEW_LINE> <INDENT> debug("Add new listener for the channel '%s': %s" % (channel, callback)) <NEW_LINE> if not channel in self.channels: <NEW_LINE> <INDENT> self.channels[channel] = [callback] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.channels[channel].append(callback) | Add a listener for a channel | 625941ce167d2b6e31218cb5 |
def test_gifs_get(self): <NEW_LINE> <INDENT> r = self.api.gifs_get(KEY, "YfCuW2maPixri,BeL3iFbYzAsfu") <NEW_LINE> self._validate(r) <NEW_LINE> self.assertEqual(len(r.data), 2) | Test case for gifs_get
Get GIFs by ID Endpoint | 625941ce8e71fb1e9831d8c8 |
def run_vscode_command_by_command_palette(command_id: str): <NEW_LINE> <INDENT> actions.user.command_palette() <NEW_LINE> actions.user.paste(command_id) <NEW_LINE> actions.key("enter") | Execute command via command palette. Preserves the clipboard. | 625941ce97e22403b379d0b9 |
def to_array(self, store_array=False): <NEW_LINE> <INDENT> if self._mat_u is not None: <NEW_LINE> <INDENT> return self._mat_u <NEW_LINE> <DEDENT> if store_array: <NEW_LINE> <INDENT> self._store_array() <NEW_LINE> return self._mat_u <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._sparse_mat_u.toarray() | Returns a dense matrix, calculated from the sparse matrix with counted
time points, which rows represents the number of spike trains and the
columns represents the binned index position of a spike in a
spike train.
The matrix columns contain the number of spikes that
occurred in the spike train(s).
If the **boolean** ... | 625941ce1f037a2d8b94631d |
def get_distinct_snapshot_length(self, item): <NEW_LINE> <INDENT> return 0 | Called by Lightstreamer Kernel through the Remote Server to ask for
the maximum allowed length for a Snapshot of an Item that has been
requested with publishing Mode DISTINCT. In fact, in DISTINCT
publishing Mode, the Snapshot for an Item is made by the last events
received for the Item and the Client can specify how m... | 625941ce796e427e537b06e6 |
def getLastStdin(tuples_list, inlined_line): <NEW_LINE> <INDENT> result = -1 <NEW_LINE> for index in range(len(tuples_list)): <NEW_LINE> <INDENT> this_tuple = tuples_list[index] <NEW_LINE> if int(this_tuple.mcpp_in_line) >= inlined_line - 1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if this_tuple.file == '"<stdin>"... | Return the last line containing <stdin> up to an line number. | 625941ce462c4b4f79d1d7f0 |
def get(self, id): <NEW_LINE> <INDENT> if id not in self.kv: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.kv[id] | Retrieves the value stored at `id`
:param str id: The id to get
:returns: The value, or None if `id` does not exist in the store
:rtype: str or None | 625941ce4e696a04525c956b |
def __init__(self): <NEW_LINE> <INDENT> pass | Initialize the class instance. | 625941ce7d43ff24873a2dc0 |
def reject_rogueharmpow(self): <NEW_LINE> <INDENT> for ii in reversed(list(range(len(self.cands)))): <NEW_LINE> <INDENT> cand = self.cands[ii] <NEW_LINE> maxharm = np.argmax(cand.harm_pows) <NEW_LINE> maxpow = cand.harm_pows[maxharm] <NEW_LINE> sortedpows = np.sort(cand.harm_pows) <NEW_LINE> if (cand.numharm >= 8 and m... | Find and remove candidates which are dominated by a single
high-power but high-numbered harmonic.
Inputs:
None
Ouputs:
None | 625941ce5e10d32532c5f046 |
def to_arrays( data, columns: Index | None, dtype: DtypeObj | None = None ) -> tuple[list[ArrayLike], Index]: <NEW_LINE> <INDENT> if isinstance(data, ABCDataFrame): <NEW_LINE> <INDENT> if columns is not None: <NEW_LINE> <INDENT> arrays = [ data._ixs(i, axis=1).values for i, col in enumerate(data.columns) if col in colu... | Return list of arrays, columns.
Returns
-------
list[ArrayLike]
These will become columns in a DataFrame.
Index
This will become frame.columns.
Notes
-----
Ensures that len(result_arrays) == len(result_index). | 625941cee5267d203edcddbd |
def generate_keys(self, k): <NEW_LINE> <INDENT> pass | To be implemented by the subclasses | 625941ce0a366e3fb873e93a |
def search_seq(self, sequence, evalue=1, identity=0.9, return_type="polymer_instance", no_hits=1000, select=False): <NEW_LINE> <INDENT> results = self.__rest_api_commands.get('sequence')(sequence, evalue, identity, resp_type=return_type, rows=no_hits).execute() <NEW_LINE> if select: <NEW_LINE> <INDENT> if return_type =... | Get dataframe with pdb ids have sequence similar to given sequence
:param sequence: (str) sequence used to fin similar ones
:param evalue: (float) minimum e value
:param identity: (float) minimum identity to input sequence
:param return_type: (str) type of returned data
:param no_hits: (int) number of hits to fetch, -1... | 625941cecdde0d52a9e53153 |
def BeginGeomInvLnext(self, *args): <NEW_LINE> <INDENT> return _itkQuadEdgeMeshLineCellPython.itkQuadEdgeMeshLineCellCIDQEMCTIF2_AutoPointer_BeginGeomInvLnext(self, *args) | BeginGeomInvLnext(self) -> itk::QuadEdgeMeshIteratorGeom<(itk::GeometricalQuadEdge<(unsigned long,unsigned long,bool,bool,true)>)>
BeginGeomInvLnext(self) -> itk::QuadEdgeMeshConstIteratorGeom<(itk::GeometricalQuadEdge<(unsigned long,unsigned long,bool,bool,true)>)> | 625941ce4f88993c3716c186 |
def tooltips(): <NEW_LINE> <INDENT> pass | Defines a set of dicts containing selector
tooltiptext and an additional/optional condition | 625941ce26068e7796caedff |
def exit_ball(self): <NEW_LINE> <INDENT> mainballspeed = self._ball[0].get_speed() <NEW_LINE> mainballpos = self._ball[0].get_position() <NEW_LINE> try: <NEW_LINE> <INDENT> if self._lives != 0 and self._current_ball == 0: <NEW_LINE> <INDENT> self._ball.pop(0) <NEW_LINE> self._paddle = Paddle(300) <NEW_LINE> self._ball ... | removes the ball from the game
Model.exit_ball() -> none | 625941ce004d5f362079a453 |
def as_tuple(self): <NEW_LINE> <INDENT> return tuple([self.confidence, self.torsion.phi, self.torsion.psi, self.torsion.omega]) | @return: convert this prediction to a tuple: (confidence, phi, psi, omega)
@rtype: tuple | 625941ceff9c53063f47c313 |
def get_week_effective_rate(self): <NEW_LINE> <INDENT> week_freq = ('W-SUN', 'W-MON', 'W-TUE', 'W-WED', 'W-THU', 'W-THU', 'W-FRI', 'W-SAT') <NEW_LINE> weeks = [g for n, g in self.__effective_rate_clean_data().groupby( pd.Grouper(freq=week_freq[pd.Series(self.__effective_rate_clean_data().index[0]).dt.weekday[0]]))] <NE... | 周有效率
:return: | 625941cedd821e528d63b2c9 |
@blueprint.route('/login') <NEW_LINE> def login(): <NEW_LINE> <INDENT> if current_user.is_authenticated(): <NEW_LINE> <INDENT> return redirect(url_for('home.index')) <NEW_LINE> <DEDENT> client = get_douban_client() <NEW_LINE> return redirect(client.authorize_url) | Redirect to douban.com to login | 625941ceb830903b967e9a2b |
def _items(self, req, entity_maker): <NEW_LINE> <INDENT> context = req.environ['xdrs.context'] <NEW_LINE> authorize(context, 'get_algorithms') <NEW_LINE> try: <NEW_LINE> <INDENT> algorithms = self.hosts_api.get_all_host_scheduler_algorithms_sorted_list(context) <NEW_LINE> <DEDENT> except exception.AlgorithmsNotFound: <... | Returns a list of algorithms, transformed through entity_maker. | 625941ce377c676e912722c8 |
def get_domain(val): <NEW_LINE> <INDENT> if val.find(".") == -1: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> if RE_IP.match(val): <NEW_LINE> <INDENT> return val.rsplit(".", 1)[0] <NEW_LINE> <DEDENT> return ".".join(val.split(".")[1:][::-1]) | Convert whatever this is, into a domain
1.2.3.4 becomes 1.2.3
mesonet.agron.iastate.edu becomes edu.iastate.agron
blah becomes '' | 625941ce6e29344779a62732 |
def evaluate_critical_path_by_stage(self, optree): <NEW_LINE> <INDENT> self.evaluate_critical_path_graph(optree, combinatorial=False) <NEW_LINE> valid_entry_list = [op for (op, combinatorial) in self.memoization_map.keys() if not combinatorial and not self.memoization_map[(op, combinatorial)] is None] <NEW_LINE> entry_... | Evaluate critical-path starting with node @p optree
in stage-by-stage mode | 625941ce56ac1b37e62642ef |
def __init__(self, version, assistant_sid, field_type_sid, sid): <NEW_LINE> <INDENT> super(FieldValueContext, self).__init__(version) <NEW_LINE> self._solution = {'assistant_sid': assistant_sid, 'field_type_sid': field_type_sid, 'sid': sid, } <NEW_LINE> self._uri = '/Assistants/{assistant_sid}/FieldTypes/{field_type_si... | Initialize the FieldValueContext
:param Version version: Version that contains the resource
:param assistant_sid: The unique ID of the Assistant
:param field_type_sid: The unique ID of the Field Type associated with this Field Value
:param sid: A 34 character string that uniquely identifies this resource
:returns: tw... | 625941ce8a349b6b435e8293 |
def _must_skip(self): <NEW_LINE> <INDENT> if self.helpscout_record.type == 'team': <NEW_LINE> <INDENT> return "Skipping import of Helpscout Team record." <NEW_LINE> <DEDENT> if not self.helpscout_record.email: <NEW_LINE> <INDENT> return "Skipping import of Helpscout User without email address." <NEW_LINE> <DEDENT> retu... | Skip records incompatible with Odoo user model. | 625941ce711fe17d8254248b |
def flatten(self, root: TreeNode) -> None: <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.flatten(root.left) <NEW_LINE> self.flatten(root.right) <NEW_LINE> right = root.right <NEW_LINE> root.right = root.left <NEW_LINE> root.left = None <NEW_LINE> while root.right: <NEW_LINE> <INDE... | Do not return anything, modify root in-place instead. | 625941ce3c8af77a43ae38c0 |
def find_path(self, start, end, size=1, heuristic=None): <NEW_LINE> <INDENT> if not heuristic: <NEW_LINE> <INDENT> heuristic = lambda x,y:abs(x-end[0])+abs(y-end[1]) <NEW_LINE> <DEDENT> dest = set(self.get_rect_from_center(end, size)) <NEW_LINE> start = tuple(start) <NEW_LINE> fringe = PriorityQueue() <NEW_LINE> fringe... | A* | 625941ce2c8b7c6e89b358e0 |
def backward_G(self): <NEW_LINE> <INDENT> lambda_idt = self.opt.lambda_identity <NEW_LINE> lambda_A = self.opt.lambda_A <NEW_LINE> lambda_B = self.opt.lambda_B <NEW_LINE> if lambda_idt > 0: <NEW_LINE> <INDENT> self.loss_iden_A = self.criterionIdt(self.iden_A, self.real_B) * lambda_B / 2 * lambda_idt <NEW_LINE> self.los... | Calculate the loss for generators G_A and G_B | 625941ce50812a4eaa59c442 |
def __str__(self): <NEW_LINE> <INDENT> string = "" <NEW_LINE> if self.convolutional: <NEW_LINE> <INDENT> string += 'Tabular values not available for NFQ with a ' + 'Convolutional Neural Network function approximator.' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for s in np.arange(self.state_dim):... | Print the current Q function and value function. | 625941ce57b8e32f524835bb |
def get_filenames_in_dir(input_dir): <NEW_LINE> <INDENT> filenames = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))] <NEW_LINE> return filenames | Get the filename list of a dir | 625941cee8904600ed9f204c |
def test_nested_flow_2(self, mock_class): <NEW_LINE> <INDENT> flow_config = FlowConfig({ 'description': 'Run a task and a flow', 'steps': { 1: {'task': 'pass_name'}, 2: {'flow': 'nested_flow_2'}, }, }) <NEW_LINE> flow = BaseFlow(self.project_config, flow_config, self.org_config) <NEW_LINE> flow() <NEW_LINE> self.assert... | Flows can run inside other flows and call other flows | 625941cee8904600ed9f204d |
def bol(self): <NEW_LINE> <INDENT> return self.__index < 0 | Return True if Begin Of list has been reached | 625941ce1d351010ab855c3c |
def log_input(flag): <NEW_LINE> <INDENT> sublime_api.log_input(flag) | Enables or disables input logging. This is useful to find the names of certain keys on the keyboard | 625941cebf627c535bc132ef |
def update(self): <NEW_LINE> <INDENT> self.shared_memory["visited"] = self.visited_queue | Method to update the shared memory object with the current visited_queue. | 625941ce23e79379d52ee684 |
def rotate_coordinates(vectors, theta, axis=2, **kwargs): <NEW_LINE> <INDENT> R_theta = rotation_matrix(theta, axis, **kwargs) <NEW_LINE> return np.dot(vectors, R_theta) | Rotate vector coordinate system or vectors themselves around an axis
A right-handed coordinate system is assumed, where positive rotations
are clockwise when looking along the rotation axis from the origin
towards the positive direction. With the default ``active=False``,
each row vector :math:`i` in input coordinate... | 625941ceec188e330fd5a8bf |
def calibrate_phase(self, z_bitshift=0): <NEW_LINE> <INDENT> avging_fac = 1.0 / (100.0 / 2.0**7) <NEW_LINE> cast_fac = 1.0 / 2.0**16 <NEW_LINE> bitshift_fac = 1.0 / (2.0**z_bitshift) <NEW_LINE> newphase = [] <NEW_LINE> for det in range(5): <NEW_LINE> <INDENT> newphase.append( np.array(self.phase[det]) ... | Hard-coded calibration that undoes the FPGA scaling and bitshifting.
A later version should store those bit-shifts in the original .h5 file
and pull them out automatically. | 625941ce7b25080760e39579 |
def account_billing(self, account_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.account_billing_with_http_info(account_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.account_billing_with_http_i... | Get Billing Information # noqa: E501
Get [billing information](https://support.zoom.us/hc/en-us/articles/201363263-About-Billing) of a Sub Account under a Master Account.<br>Only Master Accounts can use this API. Zoom only assigns this privilege to trusted partners and only approved partners can use this API. Contact... | 625941ce24f1403a92600c86 |
def __init__(self, common_name, gsd, center_wavelength, effective_bandwidth, image_band_index): <NEW_LINE> <INDENT> self.common_name = common_name <NEW_LINE> self.gsd = gsd <NEW_LINE> self.center_wavelength = center_wavelength <NEW_LINE> self.effective_bandwidth = effective_bandwidth <NEW_LINE> self.image_band_index = ... | Band object used in product specifications
Args:
common_name (str): common, human readable name for band used in UIs
gsd (float): ground sampling distance
center_wavelength (float): central wavelength
effective_bandwidth (float): bandwidth of band
image_band_index (int): index of band in source fil... | 625941ce3cc13d1c6d3c749a |
def writefuses(fuses='0x8C07FFFF'): <NEW_LINE> <INDENT> command = ["avr32program", "writefuses", "-finternal@0x80000000", "gp={0}".format(fuses)] <NEW_LINE> call(command) | write the fuses with the provided word
15:0 LOCK - flash region lock bits
16 EPFL - external privileged fetch lock
19:17 BOOTPROT - set size of bootloader protect area
25:20 BODLEVEL - brown-out detector trigger level - high = higher level
26 BODHYST - 1 enables BOD hysteresis
28:27 BODEN - hardware BOD enable state
2... | 625941ce7047854f462a152a |
def squeeze(l): <NEW_LINE> <INDENT> return l[0] if len(l) == 1 else l | Returns the element if list only contains it. | 625941ced58c6744b4257d80 |
def test_hook_jobobit_rerun_single_job_as_root(self): <NEW_LINE> <INDENT> self.run_test_func( self.jobobit_rerun_job) | Start a single job, issue a rerun as root, and verify that the jobobit
hook is executed for both runs. | 625941cecc0a2c11143dcfb1 |
def _config_error(self, message, status=2): <NEW_LINE> <INDENT> self.parser.exit(status, f'{self.parser.prog}: failed loading config: {message}\n') | Stub to replace error method that notes config failure. | 625941ced6c5a1020814416b |
def system_info(client, with_install=False, install_dir=None): <NEW_LINE> <INDENT> if with_install and install_dir: <NEW_LINE> <INDENT> perform_install(client, install_dir=install_dir) <NEW_LINE> <DEDENT> elif with_install: <NEW_LINE> <INDENT> perform_install(client) <NEW_LINE> <DEDENT> if client.is_windows(): <NEW_LIN... | Run ohai-solo on a remote system and gather the output.
:param client: :class:`ssh.SSH` instance
:returns: dict -- system information from ohai-solo
:raises: SystemInfoCommandMissing, SystemInfoCommandOld, SystemInfoNotJson
SystemInfoMissingJson
SystemInfoCommandMissing if `ohai` is not installed.
Sy... | 625941ce6aa9bd52df036ec5 |
def add_vertex(self, vertex): <NEW_LINE> <INDENT> self.vertices.append(vertex) <NEW_LINE> return None | Add a Vertex id to the path
:param vertex: the vertex ID, an integer
:return: None | 625941ce8da39b475bd65094 |
def isUCS(): <NEW_LINE> <INDENT> return _checkForDistribution("Univention") or "univention" in Distribution().distributor.lower() | Returns `True` if this is running on Univention Corporate Server.
Returns `False` if otherwise. | 625941ce460517430c3942a5 |
def set_section(state, section_name, items): <NEW_LINE> <INDENT> parser = _get_parser(state.model.filepath) <NEW_LINE> if not parser.has_section(section_name): <NEW_LINE> <INDENT> parser.add_section(section_name) <NEW_LINE> <DEDENT> for k in items: <NEW_LINE> <INDENT> key, value = _encode_item(state, k, items[k]) <NEW_... | Set section from items dictionary:
- Get parser
- If section present modify it; or
- Add new section
- Write and close file. | 625941ce16aa5153ce362598 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UpdateVehicleRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941cee64d504609d74960 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_2I().pack(_x.timeStamp.secs, _x.timeStamp.nsecs)) <NEW_LINE> _x = self.poisonStamp.originator <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941ce090684286d50ee06 |
def read_reference_data(self): <NEW_LINE> <INDENT> self.IDs = [] <NEW_LINE> self.expval = OrderedDict() <NEW_LINE> self.experr = OrderedDict() <NEW_LINE> self.nicknames = OrderedDict() <NEW_LINE> self.have_nicks = False <NEW_LINE> self.have_experr = False <NEW_LINE> for line in open(self.datafile).readlines(): <NEW_LIN... | Read the reference hydrational data from a file. | 625941ce5fcc89381b1e17e0 |
def __init__(self, red_tensor, lattice, space="r"): <NEW_LINE> <INDENT> self._reduced_tensor = red_tensor <NEW_LINE> self._lattice = lattice <NEW_LINE> self.space = space <NEW_LINE> if space == "g": <NEW_LINE> <INDENT> self._is_real_space = False <NEW_LINE> <DEDENT> elif space == "r": <NEW_LINE> <INDENT> self._is_real_... | Args:
red_tensor:
array-like object with the 9 cartesian components of the tensor
lattice:
Lattice object defining the reference system
space:
"r" if the lattice is a real space lattice
"g" if the lattice is a reciprocal space lattice | 625941ce8da39b475bd65095 |
@app.route("/posts/<int:post_id>/delete", methods=["POST"]) <NEW_LINE> def delete_post(post_id): <NEW_LINE> <INDENT> post = Post.query.get(post_id) <NEW_LINE> db.session.delete(post) <NEW_LINE> db.session.commit() <NEW_LINE> return redirect(f"/users/{user.id}") | Handle form submission for deleting an existing post | 625941ce596a897236089be1 |
@Framework.Utility_Wrapper() <NEW_LINE> def Write_Modified_Binaries(): <NEW_LINE> <INDENT> if Settings.disable_cleanup_and_writeback: <NEW_LINE> <INDENT> Print('Skipping Write_Extension; writeback disabled in Settings.') <NEW_LINE> return <NEW_LINE> <DEDENT> File_System.Write_Non_Ext_Files() <NEW_LINE> return | Write out any modified binaries. These are placed in the main x4
folder, not in an extension. | 625941ce2ae34c7f2600d252 |
def test_change_slider_value(self): <NEW_LINE> <INDENT> self.manipulate.focus_slider("bri") <NEW_LINE> self.manipulate.change_slider("-1") <NEW_LINE> received_value = self.manipulate.sliders["bri"].get_value() <NEW_LINE> self.assertEqual(received_value, -1) <NEW_LINE> self.vimiv["eventhandler"].set_num_str(5) <NEW_LINE... | Change slider value in manipulate. | 625941ce07f4c71912b115a3 |
def WritePolicy(self, policy): <NEW_LINE> <INDENT> desc = policy['desc'] <NEW_LINE> if policy['type'] in ('int-enum','string-enum'): <NEW_LINE> <INDENT> item_descs = [] <NEW_LINE> for item in policy['items']: <NEW_LINE> <INDENT> item_descs.append(str(item['value']) + ' - ' + item['caption']) <NEW_LINE> <DEDENT> desc = ... | Add strings to the stringtable corresponding a given policy.
Args:
policy: The policy for which the strings will be added to the
string table. | 625941ce31939e2706e4cf8b |
def remove_nonascii(text): <NEW_LINE> <INDENT> text = ''.join(i for i in text if ord(i)<128) <NEW_LINE> return text | removes non_ascii characters | 625941ce82261d6c526ab5c0 |
def api_handler(app, data): <NEW_LINE> <INDENT> if app.name == "wikipedia": <NEW_LINE> <INDENT> return wiki_handler(data) <NEW_LINE> <DEDENT> if app.name == "directions": <NEW_LINE> <INDENT> return dir_handler(data) <NEW_LINE> <DEDENT> if app.name == "weather": <NEW_LINE> <INDENT> return weather_handler(data) <NEW_LINE... | This acts as an interface between the sms handler and call
to an external API.
Data is retreived from a specific API and sent back to the sms handler | 625941ce4c3428357757c448 |
def close_connection(self): <NEW_LINE> <INDENT> self.imapSession.close() <NEW_LINE> self.imapSession.logout() | Close the connection to the IMAP server | 625941ce4f6381625f114b5c |
def _decode(self, data): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return self.signer.unsign_object(data, serializer=MessageSerializer) <NEW_LINE> <DEDENT> except signing.BadSignature: <NEW_LINE> <INDENT> decoded = None <NEW_LINE> <DEDENT> except (bina... | Safely decode an encoded text stream back into a list of messages.
If the encoded text stream contained an invalid hash or was in an
invalid format, return None. | 625941ce76e4537e8c351794 |
def test_unallocated_room_successfully(self): <NEW_LINE> <INDENT> self.dojo.add_person(self.person_args) <NEW_LINE> self.assertEqual(len(self.dojo.people["without_offices"]), 1) | Test add person | 625941ceb7558d58953c5035 |
def get_duedate(year, month, day, hour=23, minute=59): <NEW_LINE> <INDENT> return datetime.datetime(year, month, day, hour, minute) | Returns the date given by the parameters represented in milliseconds since unix epoch time
:parameters:
year - an int representing the year
month - int representing the month
day - int representing the day
hour (default: 23) - int representing the hour, using 24 hour format
minute (default: 59) - i... | 625941ced58c6744b4257d81 |
def get_keys_from_shelve(file_name, file_location): <NEW_LINE> <INDENT> temp_list = list() <NEW_LINE> file = __os.path.join(file_location, file_name) <NEW_LINE> shelve_store = __shelve.open(file) <NEW_LINE> for key in shelve_store: <NEW_LINE> <INDENT> temp_list.append(key) <NEW_LINE> <DEDENT> shelve_store.close() <NEW_... | Function to retreive all keys in a shelve
Args:
file_name: Shelve storage file name
file_location: The location of the file, derive from the os module
Returns:
a list of the keys | 625941ce7d847024c06be3dc |
def minimal_float(x): <NEW_LINE> <INDENT> s = '%.2f' % x <NEW_LINE> return s.rstrip('0').rstrip('.') | reduce the string length of a float by stripping trailing 0s | 625941ce85dfad0860c3af7c |
def SetSurfaceDistance(self,gridlines,distance): <NEW_LINE> <INDENT> pass | SetSurfaceDistance(self: DefaultDivideSettings,gridlines: UVGridlineType,distance: float)
Sets the default Divided Surface distance for a fixed,minimum,or maximum
distance layout for U or V gridlines.
gridlines: U-gridlines or V-gridlines.
distance: A default distance for a layout. | 625941ce56ac1b37e62642f0 |
def available_submittoeb(self): <NEW_LINE> <INDENT> if len(self.get_drafts()) > 0 or (not self.are_drafts_allowed()): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | unsure whether this goes here or elsewhere
| 625941ceadb09d7d5db6c8b0 |
def _get_profiles_template_per_type(conn: dict, type: str) -> dict: <NEW_LINE> <INDENT> return get(conn, PCC_APP_CREDENTIALS + "template/" + type) | Get profile's template per type
[Args]
(dict) conn: Connection dictionary obtained after logging in
(str) type: Type of application
[Returns]
(dict) Response: Get profile's template per type response (includes any errors) | 625941ce26238365f5f0ef8f |
def wing_downwash(aircraft,cz_wing): <NEW_LINE> <INDENT> dw_angle = cz_wing*wing_induced_factor(aircraft) <NEW_LINE> return dw_angle | Downwash angle generated behind the wing | 625941ce23849d37ff7b31b0 |
def web_call(self, location): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = requests.get( location, headers=self.headers, timeout=60, verify=False) <NEW_LINE> <DEDENT> except requests.exceptions.Timeout: <NEW_LINE> <INDENT> return self.terminal_colors.RED + ' ! ERROR: CONNECTION TIME OUT. Try inc... | Make web request for that URL, timeout in X secs and don't verify
SSL/TLS certs | 625941ceac7a0e7691ed41ed |
def divide_into_teams(players): <NEW_LINE> <INDENT> sharks = [] <NEW_LINE> dragons = [] <NEW_LINE> raptors = [] <NEW_LINE> experienced = [] <NEW_LINE> non_exp = [] <NEW_LINE> for player in players: <NEW_LINE> <INDENT> if player['Soccer Experience'] == 'YES': <NEW_LINE> <INDENT> experienced.append(player) <NEW_LINE> <D... | Create variables and programming logic to divide the 18 players into three teams: Sharks, Dragons and Raptors.
Make sure the teams have the same number of players on them,
and that the experience players are divided equally across the three teams. | 625941ce21bff66bcd684a74 |
def issues_involvement(index, start=None, end=None): <NEW_LINE> <INDENT> q = S().indexes(index).doctypes('IssuesEvent', 'IssueCommentEvent') <NEW_LINE> q = apply_time_filter(q, start, end) <NEW_LINE> q = all(q) <NEW_LINE> active_issues = most_active_issues(index, start, end) <NEW_LINE> active_issues = [i['term'] for i ... | Dict mapping from issue number to {issue: issue_obj,
users: [list of users_obj]}
for events that happened during the <start, end> time period.
! only for the 10 most popular during this time period | 625941cea17c0f6771cbe171 |
@pytest.fixture() <NEW_LINE> def search_get(): <NEW_LINE> <INDENT> return partial( current_search_client.get, Subject.index._name, doc_type="_doc" ) | Get a document from an index. | 625941cebf627c535bc132f0 |
def returner(ret): <NEW_LINE> <INDENT> _options = _get_options(ret) <NEW_LINE> from_jid = _options.get("from_jid") <NEW_LINE> password = _options.get("password") <NEW_LINE> recipient_jid = _options.get("recipient_jid") <NEW_LINE> if not from_jid: <NEW_LINE> <INDENT> log.error("xmpp.jid not defined in salt config") <NEW... | Send an xmpp message with the data | 625941ce5f7d997b87174bb9 |
def validate(dataset_joint, dataset_marginal, model, L, K, num_eval=10, batch_size=128): <NEW_LINE> <INDENT> model.eval() <NEW_LINE> loader_joint = data.DataLoader(dataset_joint, batch_size=batch_size, shuffle=True, drop_last=True) <NEW_LINE> loader_marginal = data.DataLoader(dataset_marginal, batch_size=batch_size, sh... | Evaluate the model. | 625941ce293b9510aa2c33b8 |
def subset_by_sentiment(self, num_unique_sentiments): <NEW_LINE> <INDENT> all_relevent_targets = [] <NEW_LINE> for targets in self.group_by_sentence().values(): <NEW_LINE> <INDENT> target_col = TargetCollection(targets) <NEW_LINE> if len(target_col.stored_sentiments()) == num_unique_sentiments: <NEW_LINE> <INDENT> all_... | Creates a subset based on the number of unique sentiment values per
sentence. E.g. if num_unique_sentiments = 2 then it will
return all the Target instances where each target intance has at least
two target instances per sentence and those targets can have only one
of two sentiment values. This can be used to test how ... | 625941ce046cf37aa974ce69 |
def setSustain(self, x): <NEW_LINE> <INDENT> self._sustain = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setSustain(wrap(x,i)) for i, obj in enumerate(self._base_objs)] | Replace the `sustain` attribute.
Parameters:
x : float
new `sustain` attribute. | 625941ceec188e330fd5a8c0 |
def _version_userdoc(self, strversion, isdev, revision): <NEW_LINE> <INDENT> filename = _os.path.join(self.dirs['userdoc_source'], 'conf.py') <NEW_LINE> shortversion = '.'.join(strversion.split('.')[:2]) <NEW_LINE> longversion = strversion <NEW_LINE> if isdev: <NEW_LINE> <INDENT> longversion = "%s.dev%d" % (strversion,... | Modify version in userdoc | 625941ce07d97122c41789ad |
def get_custom_settings(startargs): <NEW_LINE> <INDENT> dir_ = pathlib.Path(startargs['project_dir']) <NEW_LINE> file = 'settings.yml' <NEW_LINE> return config.read_config( str(dir_ / file) ) | Read the provided settings file.
:param startargs: parsed command line arguments
:return: | 625941ce5166f23b2e1a527a |
def close(self): <NEW_LINE> <INDENT> if self._sock: <NEW_LINE> <INDENT> self._sock.close() <NEW_LINE> self._sock = None | Close the tracker connection. | 625941ce6fb2d068a760f1bf |
def move_left(elem, seq, wrap = True): <NEW_LINE> <INDENT> if elem in seq: <NEW_LINE> <INDENT> pos = seq.index(elem) <NEW_LINE> if pos >= 0 and wrap or pos > 0: <NEW_LINE> <INDENT> next_pos = pos - 1 <NEW_LINE> if next_pos < 0: <NEW_LINE> <INDENT> next_pos = len(seq) - 1 <NEW_LINE> <DEDENT> next = seq[next_pos] <NEW_LI... | Move elem one position to the left, pushing the elem that was there to the right. | 625941ce090684286d50ee07 |
def get_results(self): <NEW_LINE> <INDENT> for i in self.output: <NEW_LINE> <INDENT> results = {} <NEW_LINE> toremove = {} <NEW_LINE> index = self.output[self.output.index(i)] <NEW_LINE> tspfile = index[2] <NEW_LINE> times = index[4].split('/') <NEW_LINE> toremove['tspid'] = index[0] <NEW_LINE> toremove['tspfile'] = ts... | Gather exit code and job file for a tsp job | 625941ceab23a570cc2502a4 |
def stripTrailingNL(s): <NEW_LINE> <INDENT> return s[:-1] if s.endswith('\n') else s | If s ends with a newline, drop it; else return s intact | 625941ce287bf620b61d3b85 |
def next_life_generation(A): <NEW_LINE> <INDENT> newA= copy(A) <NEW_LINE> height = len(A) <NEW_LINE> width = len(A[0]) <NEW_LINE> for row in range(1,height-1): <NEW_LINE> <INDENT> for col in range(1,width-1): <NEW_LINE> <INDENT> if A[row][col] == 1: <NEW_LINE> <INDENT> if countNeighbors(row,col,A) > 3: <NEW_LINE> <INDE... | makes a copy of A and then advances one
generation of Conway's game of life within
the *inner cells* of that copy.
The outer edge always stays at 0. | 625941ce50485f2cf553cebb |
def _stats(self): <NEW_LINE> <INDENT> self._create_dir_structure('stats', self._object_focus) <NEW_LINE> stats = self.player.retrieve_metric('stats', func='calculate_stats') <NEW_LINE> for name, dict_ in stats.iteritems(): <NEW_LINE> <INDENT> for key, value in dict_.iteritems(): <NEW_LINE> <INDENT> self.managed_files['... | Retrieve statistics and print them to file. | 625941ce30bbd722463cbee8 |
def on_message(self, message): <NEW_LINE> <INDENT> if self.ws.closed: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> this._task_id = alea.Alea().random_string(17, alea.UNMISTAKABLE) <NEW_LINE> try: <NEW_LINE> <INDENT> safe_call(self.logger.debug, '< %s %r', self, message) <NEW_LINE> for data in self.ddp_frames_fro... | Process a message received from remote. | 625941ceb57a9660fec339a5 |
@csrf_exempt <NEW_LINE> @http.json_response() <NEW_LINE> @http.verify_csrf() <NEW_LINE> @http.requires_token() <NEW_LINE> @http.moderators_token() <NEW_LINE> @http.require_http_methods("POST") <NEW_LINE> def feed(request, user): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> timestamp = int(reque... | @api {post} /moderators/template/feed/ PollTemplate feed method
@apiName feed
@apiGroup Moderators
@apiHeader {String} Csrf-Token CSRF token.
@apiHeader {String} Auth-Token Authentication token.
@apiParam {Number} timestamp Timestamp of poll.
@apiParam {Number} limit Limit per request.
@apiParam {Number[]} category_ids... | 625941ce1f037a2d8b94631f |
def initial(): <NEW_LINE> <INDENT> if not os.path.exists(logfile): <NEW_LINE> <INDENT> sys.stderr.write("wrong path to the risk_log\n") <NEW_LINE> sys.exit(3) <NEW_LINE> <DEDENT> global oids_per_ccy <NEW_LINE> global total <NEW_LINE> global total_rate <NEW_LINE> global total_per_id <NEW_LINE> global total_rate_per_id <... | Performs initial setup | 625941ce15baa723493c4097 |
def test_process_json_output_invalid(self): <NEW_LINE> <INDENT> task = CreateConnectedApp(self.project_config, self.task_config) <NEW_LINE> with pytest.raises(JSONDecodeError): <NEW_LINE> <INDENT> task._process_json_output("invalid") <NEW_LINE> <DEDENT> self.assertEqual( self.task_log["error"], ["Failed to parse json f... | _process_json_output with invalid input logs output and raises JSONDecodeError | 625941cee1aae11d1e749dd9 |
def last_day_of_month(date): <NEW_LINE> <INDENT> month_after = next_month(date) <NEW_LINE> return month_after - timedelta(days=month_after.day) | Return the last day of the given month (leap year-sensitive),
with date unchanged.
Thanks to Augusto Men: http://stackoverflow.com/a/13565185
:param datetime date: the first day of the given month
:return: datetime
>>> d = datetime(2012, 2, 1)
>>> last_day_of_month(d)
datetime.datetime(2012, 2, 29, 0, 0)
>>> d.day ==... | 625941ce796e427e537b06e8 |
def test_analyze_benchmark(self): <NEW_LINE> <INDENT> benchmark_result = BenchmarkResult() <NEW_LINE> benchmark_config = Benchmark() <NEW_LINE> benchmark_config.add_metric('request_size').add_metric( 'request_size', 'median') <NEW_LINE> benchmark_config.add_metric('connect_time') <NEW_LINE> benchmark_config.add_metric(... | Test analyzing benchmarks to compute aggregates | 625941ce462c4b4f79d1d7f2 |
def get(self, name): <NEW_LINE> <INDENT> value = self.sess_element.get(name) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> element = self.sess_element.find(name, NS) <NEW_LINE> if element is not None: <NEW_LINE> <INDENT> return element.text <NEW_LINE> <DEDENT> split_array = name.... | Get the value of a variable name in the session
:param name: The variable name that you want to get the value of
:return: The value of the variable or '' if not found. | 625941ce627d3e7fe0d68f71 |
def getNearCases(self,type): <NEW_LINE> <INDENT> return([ coord for coord in self.__method_near_cases__[type]() if coord != self.getCoordinate()]) | Retourne une liste d'objet Coordinate sans la coordonnée de la case courante | 625941ce38b623060ff0af0f |
@conf.commands.register <NEW_LINE> def kbdecrypt(pkt, key = None, verbose = None): <NEW_LINE> <INDENT> if verbose is None: <NEW_LINE> <INDENT> verbose = conf.verb <NEW_LINE> <DEDENT> if key == None: <NEW_LINE> <INDENT> if conf.killerbee_nkey == None: <NEW_LINE> <INDENT> log_killerbee.error("Cannot find decryption key. ... | Decrypt Zigbee frames using AES CCM* with 32-bit MIC | 625941ce71ff763f4b5497ad |
def _smartPop(self, name): <NEW_LINE> <INDENT> nestingResetTriggers = self.NESTABLE_TAGS.get(name) <NEW_LINE> isNestable = nestingResetTriggers != None <NEW_LINE> isResetNesting = name in self.RESET_NESTING_TAGS <NEW_LINE> popTo = None <NEW_LINE> inclusive = True <NEW_LINE> for i in range(len(self.tagStack)-1, 0, -1): ... | We need to pop up to the previous tag of this type, unless
one of this tag's nesting reset triggers comes between this
tag and the previous tag of this type, OR unless this tag is a
generic nesting trigger and another generic nesting trigger
comes between this tag and the previous tag of this type.
Examples:
<p>Foo<b>... | 625941ce21a7993f00bc7e11 |
def write_log( self, stream: IO[str], max_count: int = 50, rev_range: Optional[str] = None, with_gerrit_notes: bool = False, ) -> None: <NEW_LINE> <INDENT> cmd: Git_Cmd = [ "log", "--format=format:%H%n%aE%n%ci%n" + ("%N%n" if with_gerrit_notes else "") + "%n%B", "--log-size", "--max-count=%d" % max_count if max_count e... | Write formatted log to a stream.
:param stream: an open stream where to write the log content
:param max_count: max number of commit to display
:param rev_range: git revision range, see ``git log -h`` for details
:param with_gerrit_notes: if True also fetch Gerrit notes containing
review data such as Submitted-at,... | 625941ce8e7ae83300e4b0ee |
def SetRectangle(self, *args): <NEW_LINE> <INDENT> return _DigitalMicrograph.ROI_SetRectangle(self, *args) | SetRectangle(self, float top, float left, float bottom, float right) | 625941ce442bda511e8be53a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.