code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __lt__(self, other): <NEW_LINE> <INDENT> Duration._is_duration(other) <NEW_LINE> return self._millis < other._millis | Duration < Duration
>>> d_10 = Duration(10)
>>> d_20 = Duration(20)
>>> d_10 < d_20
True
>>> d_20 < d_10
False | 625941d8b830903b967e9b81 |
def on_init(self): <NEW_LINE> <INDENT> pass | Override at subclass. For example, initialize repositories that this
app would use. | 625941d8f548e778e58cd7f7 |
def do_failover(cfg, tags): <NEW_LINE> <INDENT> create_user_chains(cfg) <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> preUserChainName = cfg[tag]['prerouting']['chain'] <NEW_LINE> postUserChainName = cfg[tag]['postrouting']['chain'] <NEW_LINE> preUserChain = NATChain(preUserChainName) <NEW_LINE> postUserChain = NATCh... | :param cfg(dict): json data
:param tags(list): tag list | 625941d876d4e153a657edaa |
def cell(self, line, column): <NEW_LINE> <INDENT> return line[self._get_header_key(column)] | return the contents of a column in a line | 625941d829b78933be1e5921 |
def get(self, log_id): <NEW_LINE> <INDENT> action = ReadRecord(endpoint='medication', log_id=log_id) <NEW_LINE> return action.record | Read interaction | 625941d8adb09d7d5db6ca07 |
def velocityMatrix(self, depth_range=(0, 60000.), ddepth=100., phase='p'): <NEW_LINE> <INDENT> dmin, dmax = depth_range <NEW_LINE> uid = '.'.join(map(repr, (dmin, dmax, ddepth, phase))) <NEW_LINE> sdepth = num.linspace(dmin, dmax, (dmax - dmin) / ddepth) <NEW_LINE> ndepth = sdepth.size <NEW_LINE> if uid not in self._ve... | Create a regular sampled velocity matrix.
:param depth_range: Depth range, ``(dmin, dmax)``,
defaults to ``(0, 6000.)``
:type depth_range: tuple
:param ddepth: Stepping in [m], defaults to ``100.``
:type ddepth: float
:param phase: Phase to calculate ``p`` or ``s``,
defaults to ``p``
:type phase: str
:returns:... | 625941d816aa5153ce3626f0 |
def test_power_cycle_bad_arg(self): <NEW_LINE> <INDENT> with pytest.raises(FailedAPICallException): <NEW_LINE> <INDENT> C.node.power_cycle('node-07', 'wrong') | error on call to power_cycle with bad argument. | 625941d891f36d47f21ac76d |
def _cleanup(self): <NEW_LINE> <INDENT> Expect.ping_pong(self.rhel6client1, "rpm -e pymongo && echo SUCCESS", "[^ ]SUCCESS", 60) <NEW_LINE> Expect.ping_pong(self.rhel6client2, "rpm -e pymongo && echo SUCCESS", "[^ ]SUCCESS", 60) <NEW_LINE> '''[TCMS#178478 cleanup] Removing configuration rpm from the client ''' <NEW_LIN... | [TCMS#178478 cleanup] Removing RH rpm from the clients | 625941d8be8e80087fb20eb8 |
def getLyrics(trackId, filename): <NEW_LINE> <INDENT> req = apiCall('song.getLyrics', {'sng_id': trackId}) <NEW_LINE> if 'LYRICS_SYNC_JSON' in req: <NEW_LINE> <INDENT> rawLyrics = req['LYRICS_SYNC_JSON'] <NEW_LINE> ext = '.lrc' <NEW_LINE> lyrics = [] <NEW_LINE> for lyricLine in rawLyrics: <NEW_LINE> <INDENT> try: <NEW_... | Recieves (timestamped) lyrics from the unofficial api
and converts them to a conventional .lrc file.
If only the unsynced lyrics are found, these are written
to a .txt file. | 625941d8287bf620b61d3cdb |
def ExecuteStreamingSql(self, request, timeout, metadata=None, with_call=False, protocol_options=None): <NEW_LINE> <INDENT> raise NotImplementedError() | Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result
set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there
is no limit on the size of the returned result set. However, no
individual row in the result set can exceed 100 MiB, and no
column value can exceed 10 MiB. | 625941d8e5267d203edcdf13 |
def setCurrentPage(self, index): <NEW_LINE> <INDENT> pass | void KPageView.setCurrentPage(QModelIndex index) | 625941d8f7d966606f6aa27f |
def __compte_next__(self, D_result): <NEW_LINE> <INDENT> for shadui_infos in D_result: <NEW_LINE> <INDENT> D_result[shadui_infos].update(self.__pingyi__(shadui_infos)) <NEW_LINE> D_result[shadui_infos].update(self.__pingfen__(shadui_infos)) <NEW_LINE> hebing_result = self.__hebing__(shadui_infos) <NEW_LINE> D_result[sh... | 通过此层字典计算下一层字典
沙堆 可合并 天平
in : {((140), (), (), (), 1): {}}
out: {((140), (), (), (), 1): {
((70), (70), (), (), 1): {},
((69), (71), (), (), 1): {},
((71), (69), (), (), 1): {},
} | 625941d8f8510a7c17cf9976 |
def batch_norm_template(inputs, is_training, scope, moments_dims, bn_decay): <NEW_LINE> <INDENT> with tf.compat.v1.variable_scope(scope) as sc: <NEW_LINE> <INDENT> num_channels = inputs.get_shape()[-1].value <NEW_LINE> beta = tf.Variable(tf.constant(0.0, shape=[num_channels]), name='beta', trainable=True) <NEW_LINE> ga... | Batch normalization on convolutional maps and beyond...
Ref.: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow
Args:
inputs: Tensor, k-D input ... x C could be BC or BHWC or BDHWC
is_training: boolean tf.Varialbe, true indicates training phase
scope: ... | 625941d830c21e258bdfa717 |
def mkdirs(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(path) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.errno == os.errno.EEXIST and os.path.isdir(path): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise e | Recursively creating directories and won't throw exception if the path already exists.
| 625941d885dfad0860c3b0d4 |
def test_index(self): <NEW_LINE> <INDENT> response = self.tester.get('/', content_type="html/text") <NEW_LINE> self.assertEqual(response.status_code, 200) | Ensure route / returns 200 | 625941d8099cdd3c635f0ed3 |
def _localization_use_documents(self): <NEW_LINE> <INDENT> self.ensure_one() <NEW_LINE> return self.country_id.code == "CL" or super()._localization_use_documents() | Chilean localization use documents | 625941d8d58c6744b4257ed7 |
def get_file(self, digest): <NEW_LINE> <INDENT> file_path = os.path.join(self.path, digest) <NEW_LINE> if not os.path.exists(file_path): <NEW_LINE> <INDENT> raise KeyError("File not found.") <NEW_LINE> <DEDENT> return io.open(file_path, 'rb') | See FileCacherBackend.get_file().
| 625941d88da39b475bd651ee |
def add_piece(self, name, image, row=0, column=0): <NEW_LINE> <INDENT> print(name) <NEW_LINE> self.canvas.create_image(0,0, image=image, tags=(name, "piece"), anchor="c") <NEW_LINE> self.place_piece(name, row, column) | Add a piece to the playing board | 625941d8d486a94d0b98e3bf |
def return_partial_int(): <NEW_LINE> <INDENT> spcatch.error('static', 42) | Return a partially-constructed integer. | 625941d8e64d504609d74ab9 |
def _extract_traceback(start): <NEW_LINE> <INDENT> tb = sys.exc_info()[2] <NEW_LINE> for i in range(start): <NEW_LINE> <INDENT> tb = tb.tb_next <NEW_LINE> <DEDENT> trace = [] <NEW_LINE> n = 0 <NEW_LINE> while tb is not None: <NEW_LINE> <INDENT> f = tb.tb_frame <NEW_LINE> trace.append({ "depth": n, "file": f.f_code.co_f... | SNAGGED FROM traceback.py
RETURN list OF dicts DESCRIBING THE STACK TRACE | 625941d88a349b6b435e83ec |
def getPackingSlips( self, createdAfter: str, createdBefore: str, shipFromPartyId: str = None, limit: int = None, sortOrder: str = None, nextToken: str = None, ): <NEW_LINE> <INDENT> url = f"/vendor/directFulfillment/shipping/v1/packingSlips" <NEW_LINE> params = {} <NEW_LINE> if shipFromPartyId is not None: <NEW_LINE> ... | Returns a list of packing slips for the purchase orders that match the criteria specified. Date range to search must not be more than 7 days.
**Usage Plans:**
| Plan type | Rate (requests per second) | Burst |
| ---- | ---- | ---- |
|Default| 10 | 10 |
|Selling partner specific| Variable | Variable |
The x-amzn... | 625941d8d6c5a102081442c5 |
def add_modification(self, k, v): <NEW_LINE> <INDENT> self._modifications.append((k, v)) | Records a new value for k->v pair. Don't call, if you used the factory. | 625941d8d268445f265b50e7 |
def plot_image_masks(self): <NEW_LINE> <INDENT> log.info("Plotting the image masks ...") <NEW_LINE> for name in self.image_names: <NEW_LINE> <INDENT> levels = self.sigma_levels_for_images[name] <NEW_LINE> plot_path = self.image_mask_plot_paths[name] <NEW_LINE> if self.has_all_mask_plots_for_image(name): <NEW_LINE> <IND... | This function ...
:return: | 625941d87047854f462a1680 |
def MakeBold(font): <NEW_LINE> <INDENT> newFont = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(), wx.FONTWEIGHT_BOLD, font.GetUnderlined(), font.GetFaceName()) <NEW_LINE> return newFont | Makes a font bold. Utility method.
:param `font`: the font to be made bold. | 625941d8be7bc26dc91cd875 |
def update_process_methods(self, new): <NEW_LINE> <INDENT> self.update_dict(self._process_methods, new) | A recursive method for updating process method dicts. This prevents
subprocess reloads from overwriting the references that setupprocess
relies on for some reason. | 625941d84e4d5625662d464e |
def resize(self, shape): <NEW_LINE> <INDENT> arr = cv2.resize(self, shape[::-1]) <NEW_LINE> obj = self.__class__(arr) <NEW_LINE> obj.__array_finalize__(self) <NEW_LINE> return obj | Resize video frame to given dimensions
Parameters
----------
shape : tuple
Target image shape | 625941d87cff6e4e81117bfe |
def test_wait_command_not_found(self, r): <NEW_LINE> <INDENT> key = "foo" <NEW_LINE> node = r.get_node_from_key(key) <NEW_LINE> with r.monitor(target_node=node) as m: <NEW_LINE> <INDENT> response = wait_for_command(r, m, "nothing", key=key) <NEW_LINE> assert response is None | Make sure the wait_for_command func works when command is not found | 625941d8f7d966606f6aa280 |
def run_migrations_offline(): <NEW_LINE> <INDENT> url = config.get_main_section["sqlalchemy.url"] <NEW_LINE> context.configure( url=url, target_metadata=target_metadata, literal_binds=True) <NEW_LINE> with context.begin_transaction(): <NEW_LINE> <INDENT> context.run_migrations() | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | 625941d850485f2cf553d014 |
def __init__(self, path, _file_path_acceptance_fn=None): <NEW_LINE> <INDENT> if not _file_path_acceptance_fn: <NEW_LINE> <INDENT> _file_path_acceptance_fn = CheckFileStoragePathAcceptance <NEW_LINE> <DEDENT> _file_path_acceptance_fn(path) <NEW_LINE> self.file_path_acceptance_fn = _file_path_acceptance_fn <NEW_LINE> sel... | Create a new file device helper.
@raise errors.FileStoragePathError: if the file path is disallowed by policy | 625941d88da39b475bd651ef |
def atleast_one(*args): <NEW_LINE> <INDENT> return sum([1 for a in args if a is not None]) >= 1 | Asserts one of the arguments is not None
Returns:
result(bool): True if atleast one of the arguments is not None | 625941d8be383301e01b56fc |
def get_focused_widget(self): <NEW_LINE> <INDENT> w = self.body <NEW_LINE> for p in self.body.get_focus_path(): <NEW_LINE> <INDENT> if p != w.focus_position: <NEW_LINE> <INDENT> w.focus_position = p <NEW_LINE> <DEDENT> if not issubclass(type(w.focus.base_widget), urwid.WidgetContainerMixin): <NEW_LINE> <INDENT> break <... | Iterate across the focus path and return the in-focus
widget | 625941d831939e2706e4d0e0 |
def index_directories(): <NEW_LINE> <INDENT> unshacled_dirs = [] <NEW_LINE> top_level_dirs = os.listdir() <NEW_LINE> search_dirs = [(directory, None) for directory in top_level_dirs] + [ (directory + '/' + nested_dir, directory) for directory in top_level_dirs if os.path.isdir(directory) for nested_dir in os.listdir(di... | Iterates through all top-level directories and tries to identify
each as an UnSHACLed build by looking for 'index.html' and
'build-name' files. Returns a list of (name, directory) tuples. | 625941d8f548e778e58cd7f8 |
def init_model(net, restore): <NEW_LINE> <INDENT> net.apply(init_weights) <NEW_LINE> if restore is not None and os.path.exists(restore): <NEW_LINE> <INDENT> net.load_state_dict(torch.load(restore)) <NEW_LINE> net.restored = True <NEW_LINE> print("Restore model from: {}".format(os.path.abspath(restore))) <NEW_LINE> <DED... | Init models with cuda and weights. | 625941d8d99f1b3c44c67804 |
def normalize_intensities(self, x, y, threshold=True): <NEW_LINE> <INDENT> if x <= 0 and y <= 0: <NEW_LINE> <INDENT> return (nan, nan) <NEW_LINE> <DEDENT> tempx = x - self.offset_x <NEW_LINE> tempy = y - self.offset_y <NEW_LINE> tempx2 = cos(self.theta) * tempx + sin(self.theta) * tempy <NEW_LINE> tempy2 = -sin(self.th... | Apply this normalization transform to raw intensities
Args:
x (int): Raw x intensities
y (int): Raw y intensities
Returns:
(float, float): (xn, yn) normalized intensities as tuple of floats | 625941d8377c676e91272421 |
def c_update_overrides(self): <NEW_LINE> <INDENT> for tag, override in self.overrides.root.children.items(): <NEW_LINE> <INDENT> value_to_set = getattr(self.parsed_args, self.override_prefix + tag) <NEW_LINE> if value_to_set is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> override.set_string_value(value_to_se... | Update override options | 625941d826238365f5f0f0ea |
def set_cursor(self, cursor): <NEW_LINE> <INDENT> pass | Set the current cursor to one of the :class:`Cursors`
enums values | 625941d866656f66f7cbc425 |
def post_save_cart_item(sender, instance, *args, **kwargs): <NEW_LINE> <INDENT> if instance: <NEW_LINE> <INDENT> instance.cart.total_cart_price += instance.total_product_price <NEW_LINE> instance.cart.save() | Calculate the total price of cart -> product price * quantity | 625941d8507cdc57c6306f59 |
def inorderTraversal(root): <NEW_LINE> <INDENT> def inOrdertreeTraversal(root): <NEW_LINE> <INDENT> if root.left != None: <NEW_LINE> <INDENT> inOrdertreeTraversal(root.left) <NEW_LINE> <DEDENT> finalList.append(root.val) <NEW_LINE> if root.right != None: <NEW_LINE> <INDENT> inOrdertreeTraversal(root.right) <NEW_LINE> <... | :type root: TreeNode
:rtype: List[int] | 625941d8090684286d50ef61 |
def get_texture_index(glTF, filename): <NEW_LINE> <INDENT> if glTF.textures is None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> image_index = get_image_index(glTF, filename) <NEW_LINE> if image_index == -1: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> for texture_index, texture in enumerate(glTF.textures): ... | Return the texture index in the glTF array by a given file path. | 625941d8379a373c97cfadbf |
def http_call(method, url_templ): <NEW_LINE> <INDENT> formatted_names = set() <NEW_LINE> for match in format_param_rr.finditer(url_templ): <NEW_LINE> <INDENT> formatted_names.add(match.group(1)) <NEW_LINE> <DEDENT> def closure(connection, *args, **kwargs): <NEW_LINE> <INDENT> func = getattr(connection, method) <NEW_LIN... | return closure, which would takes parameters and
makes http calls with given url and method | 625941d8a934411ee375190d |
def test_006_create_network(self): <NEW_LINE> <INDENT> self.network = self._create_network(gateway_ip='') <NEW_LINE> self._insist_on_network_transition( self.network, ["BUILD"], "ACTIVE") | Submit a create network request | 625941d810dbd63aa1bd2e1c |
def int2bits(n: int) -> int: <NEW_LINE> <INDENT> if n < 0: <NEW_LINE> <INDENT> raise ValueError("int2bits: n must be greater then zero") <NEW_LINE> <DEDENT> if n == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> bits = 0 <NEW_LINE> while n: <NEW_LINE> <INDENT> n >>= 1 <NEW_LINE> bits += 1 <NEW_LINE> <DEDENT> retur... | Calculates the number of bits needed to represent an integer n.
Parameters
----------
n : int
The integer number.
Returns
-------
num_bits : int
The number of bits required to represent the number `n`.
Examples
--------
>>> list(map(int2bits, range(0,19)))
[1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, ... | 625941d85fdd1c0f98dc04ad |
def get_input_size(self): <NEW_LINE> <INDENT> return list(self.input_size) | Retrieves output size of processor. | 625941d84527f215b584c6ce |
def test_missing_total_points(self): <NEW_LINE> <INDENT> attributes = self._character_attributes() <NEW_LINE> del attributes['total_points'] <NEW_LINE> form = forms.CharacterForm(attributes) <NEW_LINE> self.assertFalse(form.is_valid()) | Create a CharacterForm without setting ``total_points``. | 625941d850812a4eaa59c599 |
def _box2d_to_bbox(pg_box2d: str) -> Tuple[float, float, float, float]: <NEW_LINE> <INDENT> m = _BOX2D_PATTERN.match(pg_box2d) <NEW_LINE> if m is None: <NEW_LINE> <INDENT> raise RuntimeError(f"Unexpected postgis box syntax {pg_box2d!r}") <NEW_LINE> <DEDENT> return tuple(float(m) for m in m.groups()) | Parse Postgis's box2d to a geojson/stac bbox tuple.
>>> _box2d_to_bbox(
... "BOX(134.806923200497 -17.7694714883835,135.769692610214 -16.8412669214876)"
... )
(134.806923200497, -17.7694714883835, 135.769692610214, -16.8412669214876)
>>> # Scientific notation in numbers is sometimes given
>>> _box2d_to_bbox(
... ... | 625941d821a7993f00bc7f6d |
def dtree_classify(dtree, x): <NEW_LINE> <INDENT> if dtree[0] is None: <NEW_LINE> <INDENT> return dtree[1] <NEW_LINE> <DEDENT> global attr <NEW_LINE> subtree_pos = attr[ dtree[0] ].index( x[dtree[0]] ) <NEW_LINE> return dtree_classify(dtree[1][subtree_pos], x) | Classifies a single example x using the given decision tree. Returns the predicted class label.
| 625941d8462c4b4f79d1d94a |
def cut(self): <NEW_LINE> <INDENT> for i in self.listview.selectedItems(): <NEW_LINE> <INDENT> txt = self.listview.takeItem(self.listview.row(i)) <NEW_LINE> self.clip.setText(txt.text(), mode=QtGui.QClipboard.Selection) <NEW_LINE> <DEDENT> self.statusbar.showMessage("Cut!", 500) | Cut selection and put into system's clipboard | 625941d87b180e01f3dc4a73 |
def calculate_commit_coverage( cov_data: 'CoverageData', commit_id: Optional[str] = None, ) -> Dict[str, Any]: <NEW_LINE> <INDENT> git_files = list(files_in_commit(commit_id)) <NEW_LINE> cov_files = list(files_covered(cov_data)) <NEW_LINE> covered_files = {} <NEW_LINE> for path in git_files: <NEW_LINE> <INDENT> if path... | Calculate the test coverage for the lines changed in the
given git commit Id
Args:
cov_data (CoverageData): coverage data object
commit_id (str): id of the commit to calculate coverage on | 625941d8656771135c3ebaeb |
def process_pixels(pixels, img_size=IMG_SIZE): <NEW_LINE> <INDENT> pixels_as_list = pandas_vector_to_list(pixels) <NEW_LINE> width = img_size <NEW_LINE> height = img_size <NEW_LINE> input_shape = (64, 64, 1) <NEW_LINE> faces = [] <NEW_LINE> for pixel_sequence in pixels_as_list: <NEW_LINE> <INDENT> face = [int(pixel) fo... | Takes in a string (pixels) that has space separated ints. Will transform the ints
to a 48x48 matrix of floats(/255).
:param pixels: string with space separated ints
:param img_size: image size
:return: array of 48x48 matrices | 625941d8956e5f7376d710e6 |
def do_something(self: ComponentB) -> None: <NEW_LINE> <INDENT> print("ComponentB") | Что-то делает. | 625941d8bd1bec0571d908a9 |
def load_params_bio(bio, callback=util.passphrase_callback): <NEW_LINE> <INDENT> dsa = m2.dsa_read_params(bio._ptr(), callback) <NEW_LINE> if dsa is None: <NEW_LINE> <INDENT> raise DSAError('problem loading DSA parameters') <NEW_LINE> <DEDENT> return DSA(dsa, 1) | Factory function that instantiates a DSA object with DSA
parameters from a M2Crypto.BIO object.
@param bio: Contains the PEM representation of the DSA
parameters.
@param callback: A Python callback object that will be
invoked if the DSA parameters file is
passphr... | 625941d8f9cc0f698b140873 |
def link_header_file(header_name): <NEW_LINE> <INDENT> source = header_name <NEW_LINE> dir_name = os.path.splitext(source)[0] <NEW_LINE> dir_path = os.path.join(sketchbook_path, dir_name) <NEW_LINE> destination_name = source <NEW_LINE> destination_path = os.path.join(dir_path, destination_name) <NEW_LINE> if os.path.ex... | This function creates a sym link in GadgetronSketchBook directory
:param header_name: The path to the generated header file
:return: | 625941d8dd821e528d63b421 |
def initAPIServer(self): <NEW_LINE> <INDENT> pass | initAPIServer initializes the server that handles HTTP calls | 625941d82c8b7c6e89b35a39 |
def normalize_lines(lines, show_progressbar=True, progress_label='Normalizing line scans:'): <NEW_LINE> <INDENT> if show_progressbar: <NEW_LINE> <INDENT> prg_lines = tqdm(lines, desc=progress_label) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prg_lines = lines <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> line_scans =... | Normalize line scans by their maximum in each spectra.
Operates in-place on the lines.
Parameters
----------
lines: list of :py:class:`~hyperspy.signal.Signal`
list of Hyperspy line scans to normalize
show_progressbar: bool
switch to determine whether a progressbar should be shown.
progress_label: str
labe... | 625941d815baa723493c41f1 |
def __int__(self): <NEW_LINE> <INDENT> if self.scaledval >= 0: <NEW_LINE> <INDENT> return int(self.scaledval // self.family.scale) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return int((self.scaledval + self.family.scale - 1) // self.family.scale) | Cast to integer | 625941d897e22403b379d215 |
def check_a3(username,reducers): <NEW_LINE> <INDENT> call(["mvn", "clean", "package"]) <NEW_LINE> call(["hadoop", "jar", "target/assignments-1.0.jar", "ca.uwaterloo.cs451.a3.BuildInvertedIndexCompressed".format(username), "-input", "/shared/uwaterloo/cs451/data/enwiki-20161220-sentences-0.1sample.txt", "-output", "cs45... | Run Assignment 3 on Altiscale | 625941d8796e427e537b0842 |
def fileListProjects(*args, **kwargs): <NEW_LINE> <INDENT> print >> sys.stderr, "dxpy.fileListProjects is deprecated; please use file_list_projects instead." <NEW_LINE> return file_list_projects(*args, **kwargs) | .. deprecated:: 0.42.0
Use :func:`file_list_projects()` instead. | 625941d830c21e258bdfa718 |
def __init__(self, parent_server): <NEW_LINE> <INDENT> logger.debug("Initializing WineProcessProtocol") <NEW_LINE> self.parent_server = parent_server <NEW_LINE> self.have_data = False | Initialize; save an instance variable pointing to our
:py:class:`~.TwistedServer`
:param parent_server: the TwistedServer instance that started this
:type parent_server: :py:class:`~.TwistedServer` | 625941d899fddb7c1c9de60b |
def verify(self,cipher): <NEW_LINE> <INDENT> self.swapkeys() <NEW_LINE> message=self.decrypt(cipher) <NEW_LINE> self.swapkeys() <NEW_LINE> return message | Verifies the given message. Input and output should be strings.
Returns garbage if unable to verify. | 625941d80c0af96317bb8462 |
def set_cell(self, coord, color): <NEW_LINE> <INDENT> s, p, d = coord <NEW_LINE> i = self.get_pixel((p,d)) <NEW_LINE> coord = (s,i) <NEW_LINE> if self.cell_exists(coord): <NEW_LINE> <INDENT> self.next_frame[coord] = color | Convert (s,p,d) coord to (s,i) and send out | 625941d8c432627299f04ec1 |
def test_tools_import_side_bar_help(self): <NEW_LINE> <INDENT> href = 'http://edx.readthedocs.io/projects/open-edx-building-and-running-a-course/en/' 'latest/releasing_course/export_import_course.html#export-a-course' <NEW_LINE> assert_side_bar_help_link( test=self, page=self.export_page, href=href, help_... | Scenario: Help link in side bar is working on tools Library export page
Given that I am on the tools Library import page
And I want help about the process
And I click the 'Learn more about exporting a course' in the sidebar links
Then Help link should open.
And help url should end with 'releasing_course/export_import_c... | 625941d850812a4eaa59c59a |
def Train(self): <NEW_LINE> <INDENT> self.init_epoch = self.epoch <NEW_LINE> if self.epoch >= self.params.num_epoch: <NEW_LINE> <INDENT> WARNING('Num_epoch should be smaller than current epoch. Skip training......\n') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for _ in range(self.epoch, self.params.num_epoch): <NEW_... | Train network in n epochs, n is defined in params.num_epoch | 625941d8ac7a0e7691ed4342 |
def coco_optimize(solver, fun, max_evals, max_runs=1e9): <NEW_LINE> <INDENT> range_ = fun.upper_bounds - fun.lower_bounds <NEW_LINE> center = fun.lower_bounds + range_ / 2 <NEW_LINE> if fun.evaluations: <NEW_LINE> <INDENT> print('WARNING: %d evaluations were done before the first solver call' % fun.evaluations) <NEW_LI... | `fun` is a callable, to be optimized by `solver`.
The `solver` is called repeatedly with different initial solutions
until either the `max_evals` are exhausted or `max_run` solver calls
have been made or the `solver` has not called `fun` even once
in the last run.
Return number of (almost) independent runs. | 625941d80fa83653e4657234 |
def feature_holds(self, feature, idx, node, ret_assignments=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pst = self.get_pst(node, idx) <NEW_LINE> assignments = pst.prove(feature) <NEW_LINE> feature_holds = (len(assignments) > 0) <NEW_LINE> <DEDENT> except CommitGoalError: <NEW_LINE> <INDENT> feature_holds = Fal... | Check whether a feature holds for the given sample ID.
Parameters
----------
feature : str
The feature name.
idx : int
The sample ID.
node : Node
ret_assignments : bool
Returns
-------
feature_holds : bool | 625941d8009cb60464c6362a |
def test_constructor_config_poison_values(config, mocker): <NEW_LINE> <INDENT> nersc_mover_config = config.copy() <NEW_LINE> nersc_mover_config["LTA_REST_URL"] = None <NEW_LINE> logger_mock = mocker.MagicMock() <NEW_LINE> with pytest.raises(ValueError): <NEW_LINE> <INDENT> NerscMover(nersc_mover_config, logger_mock) | Fail with a ValueError if the configuration object is missing required configuration variables. | 625941d8a8ecb033257d3346 |
def get(self, request): <NEW_LINE> <INDENT> form = FileUploadForm() <NEW_LINE> return render(request, 'thumbnailer/home.html', {'form': form}) | Get request will return home.html template | 625941d8cdde0d52a9e532af |
@skip_if_fixup <NEW_LINE> def test_commit_has_reference(commit_message): <NEW_LINE> <INDENT> has_gh_issue_refs = re.findall(r'#\d+', commit_message) <NEW_LINE> has_taiga_issue_refs = re.findall(r'TG-\d+', commit_message) <NEW_LINE> assert has_gh_issue_refs or has_taiga_issue_refs, ( 'Commit message does not reference r... | Verify that a commit includes a bug/issue/task/etc reference | 625941d8627d3e7fe0d690cb |
@remote_compatible <NEW_LINE> def test_pasn_gcmp_256(dev, apdev): <NEW_LINE> <INDENT> check_pasn_capab(dev[0]) <NEW_LINE> params = pasn_ap_params("PASN", "GCMP-256", "19") <NEW_LINE> hapd = start_pasn_ap(apdev[0], params) <NEW_LINE> check_pasn_akmp_cipher(dev[0], hapd, "PASN", "GCMP-256") | PASN authentication with WPA2/GCMP-256 AP | 625941d8b5575c28eb68e27c |
def s3_delete_file(user): <NEW_LINE> <INDENT> s3 = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) <NEW_LINE> bucket = s3.get_bucket(settings.BUCKET_NAME) <NEW_LINE> for size in ['orig', 'med', 'small']: <NEW_LINE> <INDENT> key = bucket.get_key('media/%s%s/%s_%s.jpg' % (settings.IMAGE_URL, u... | Delete a file uploaded to Amazon s3. | 625941d8cc0a2c11143dd10b |
def critical(obj, msg): <NEW_LINE> <INDENT> _logger.critical(_log_format.format( obj=obj, msg=msg )) | Logging function | 625941d84e696a04525c96c6 |
def delete(self, job_id, build_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self.parent.rest.do_build_request('DELETE', job_id, build_id, None) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.parent.log.exception('Failed to delete build %s/%s', job_id, build_id) <NEW_LINE> return False <NEW_LINE> <... | Delete a build | 625941d876e4537e8c3518ee |
def tokenize(filepath): <NEW_LINE> <INDENT> fn = os.path.basename(filepath) <NEW_LINE> outpth = os.path.join(TEMP, "GSW_3_"+fn) <NEW_LINE> subprocess.check_call(["python", os.path.join(EXTERNALDIR,"tokenizer", "pretok.py"), filepath, os.path.join(TEMP, "GSW_1_"+fn)]) <NEW_LINE> subprocess.check_call(["perl", os.path.jo... | Call the tokenizer, write to filepath.tokenized. Will raise an Exception if any call fails.
Returns the path to the tokenized file | 625941d894891a1f4081bd24 |
def make_name(estimator): <NEW_LINE> <INDENT> if estimator is not None: <NEW_LINE> <INDENT> if isinstance(estimator, six.string_types): <NEW_LINE> <INDENT> estimator_name = estimator <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> estimator_name = estimator.__class__.__name__ <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE>... | Helper function that returns the name of estimator or the given string
if a string is given | 625941d86aa9bd52df03701f |
def Z003_generate_flash_message(self, message, Params): <NEW_LINE> <INDENT> flashid = Params.get_inc('FLASHID') <NEW_LINE> message = message.ljust(250)[:250] <NEW_LINE> message = message.strip() <NEW_LINE> sql = 'select user from user' <NEW_LINE> count, ds_users = self.db_read(sql, '') <NEW_LINE> if count < 0: <NEW_LIN... | creates a new flash status message and stores a new message for each user on the
database. Each record is stored with a 24-hour countdown timer. | 625941d891f36d47f21ac76f |
def __init__(self, *args): <NEW_LINE> <INDENT> this = _lldb.new_SBValueList(*args) <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.this = this | __init__(self) -> SBValueList
__init__(self, SBValueList rhs) -> SBValueList | 625941d84a966d76dd55128b |
def after_delete(self, mapper, connection, target): <NEW_LINE> <INDENT> pass | Receive an object instance after a DELETE statement
has been emitted corresponding to that instance.
This event is used to emit additional SQL statements on
the given connection as well as to perform application
specific bookkeeping related to a deletion event.
The event is often called for a batch of objects of the
... | 625941d8e76e3b2f99f3aa82 |
def get_clicked_position(coords: Tuple[float, float], total_rows: int, surface_width: int) -> Tuple[int, int]: <NEW_LINE> <INDENT> node_width = surface_width // total_rows <NEW_LINE> x, y = coords <NEW_LINE> row = int(x // node_width) <NEW_LINE> column = int(y // node_width) <NEW_LINE> return row, column | Calculate and return row and column from the mouse coordinates given by pygame.
:param coords: mouse coordinates given by pygame
:param total_rows: number of rows; is also the number of nodes per row
:param surface_width: width of the surface (game window)
:return: (row, column) which was clicked | 625941d89c8ee82313fbb9f0 |
def create_bulk(): <NEW_LINE> <INDENT> id_bulk = requests.create_bulk() <NEW_LINE> if id_bulk is not None: <NEW_LINE> <INDENT> file_bulks.writte_bulk_id(id_bulk) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.error("Error creating bulk...") | This function creates a new bulk and
writes the id in the bulks.txt file | 625941d8a05bb46b383eca9b |
def CreateAccessibilityInstance(self,*args): <NEW_LINE> <INDENT> pass | CreateAccessibilityInstance(self: ToolStripItem) -> AccessibleObject
Creates a new accessibility object for the System.Windows.Forms.ToolStripItem.
Returns: A new System.Windows.Forms.AccessibleObject for the System.Windows.Forms.ToolStripItem. | 625941d891af0d3eaac9bc95 |
def sign_message(given_message,given_key): <NEW_LINE> <INDENT> if not given_message: <NEW_LINE> <INDENT> common.print_error("Cannot sign blank message.") <NEW_LINE> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> signature = crypto.sign(given_key,given_message,'sha512') <NEW_LINE> signature = base64.b64encode(... | Signs the (hash of the) given message with the given private key.
Returns the base64 encoded signature or or a blank string if something bad happened. | 625941d8f8510a7c17cf9978 |
def calculate_distance(x1, y1, x2, y2): <NEW_LINE> <INDENT> width = math.sqrt((x2 - x1)**2) <NEW_LINE> height = math.sqrt((y2 - y1)**2) <NEW_LINE> return math.sqrt(width**2 + height**2) | Calculate distance between two coordinates
Takes 2 sets of coordinates, and calculates the distance between using
Pythagoras's theorem | 625941d8442bda511e8be690 |
def __init__(self): <NEW_LINE> <INDENT> Frame.__init__(self) <NEW_LINE> self.master.config(bd=5,) <NEW_LINE> self.master.title("Repeat After Me Bot") <NEW_LINE> self.master.geometry("800x550") <NEW_LINE> self.grid() <NEW_LINE> self.information=Listbox(self, height=20, width=75) <NEW_LINE> self.information.grid(row=0, c... | configure window size | 625941d8e64d504609d74aba |
def p_SwitchStmt(t): <NEW_LINE> <INDENT> t[0] = n.Switchstmt(t[3], t[6]) | SwitchStmt : SWITCH LPAREN identifier RPAREN LBRACE CaseList RBRACE | 625941d892d797404e304405 |
def new_job(self): <NEW_LINE> <INDENT> pass | Create new job object and store it in job store.
New Job object will be in state PENDING, and has a UUID assigned. | 625941d8627d3e7fe0d690cc |
def SetHistory( self, value=(), selectionIndex = None, control=None ): <NEW_LINE> <INDENT> if control is None: <NEW_LINE> <INDENT> control = self.GetHistoryControl() <NEW_LINE> <DEDENT> if self.history == value: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.history = value <NEW_LINE> tempValue=control.GetValue() ... | Set the current history list | 625941d87d847024c06be539 |
def receive(self) -> bytes: <NEW_LINE> <INDENT> response = TcpMessage.from_stream(self._rfile) <NEW_LINE> while response is None and self._retry_count < TcpClient.RETRIES: <NEW_LINE> <INDENT> self._disconnect() <NEW_LINE> self._connect() <NEW_LINE> response = TcpMessage.from_stream(self._rfile) <NEW_LINE> self._retry_c... | Waits for a response from server_addr. Should only be used after send()
has been called. If no response is sent from the server, the
connection is retried up to TcpClient.RETRIES times
:return: The TcpMessage content from the server's response
:rtype: bytes | 625941d89b70327d1c4e1050 |
def content(self): <NEW_LINE> <INDENT> if len(self.lines) < self.lncnt: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return ', '.join(self.lines) | Returns None if the Line have not stored enough content. | 625941d899cbb53fe6792e61 |
def _print_task_result(self, result, error=False, **kwargs): <NEW_LINE> <INDENT> if 'print_action' in result._task.tags or error or self._display.verbosity > 1: <NEW_LINE> <INDENT> self._print_task() <NEW_LINE> self.last_skipped = False <NEW_LINE> msg = to_text(result._result.get('msg', '')) or to_text(r... | Run when a task finishes correctly. | 625941d8187af65679ca539a |
def valid_score(model, X, y, scoring=acc, cv=cv): <NEW_LINE> <INDENT> from sklearn.model_selection import cross_val_score <NEW_LINE> score = cross_val_score( model, X, y, cv=cv, scoring=scoring ) <NEW_LINE> print("Validation Set Scores:\n", score) | Find the validation score.
:param model: a model that can be entered in random search
:type model: sklearn model
:param X: the validation input
:type X: numpy.ndarray
:param y: validation label
:type y: numpy.ndarray
:param scoring: the scoring methodology
:type scoring: str
:param cv: number of sets to split for... | 625941d8a8ecb033257d3347 |
def test_end_to_end(mocker, tmpdir): <NEW_LINE> <INDENT> mock_initalize = mocker.patch( f"{STUDY_GENERATOR_MODULE}.StudyGenerator.initialize_study" ) <NEW_LINE> sg = StudyGenerator(working_dir=os.path.join(tmpdir, "temp")) <NEW_LINE> sg.ingest_study(clean=True, verify_counts=True, dry_run=True) <NEW_LINE> sg.ingest_stu... | Test StudyGenerator.ingest_study in dry_run mode
The dry_run mode runs the whole ingest pipeline except it doesn't
actually send the payloads to Dataservice. If we can check that
the correct payloads got constructed then we know StudyGenerator
is working as expected. | 625941d87b180e01f3dc4a74 |
def getmtm(cf, alpha=0.95): <NEW_LINE> <INDENT> nsims = cf.shape[0] <NEW_LINE> cumvalues = cf.sum(axis=2) <NEW_LINE> mean = cumvalues.mean(axis=1) <NEW_LINE> std = cumvalues.std(axis=1) <NEW_LINE> res = {} <NEW_LINE> for key, val in mean.items(): <NEW_LINE> <INDENT> res[key] = mkmcresults(val, std[key], nsims) <NEW_LIN... | Calcule la MtM (i.e. : les cash-flows moyens réalisés et un intervalle
de confiance) de chaque actif listé dans `cf`.
Paramètres
----------
cf : pandas.Panel
Cash-flows réalisés pour chaque simulation (`items`), chaque
actif (`major_axis`) et chaque date (`minor_axis`).
alpha : double compris entre 0. et 1.
... | 625941d88e7ae83300e4b248 |
def __init__(self, data_set: np.ndarray, categorical_indices: Optional[List[Index]] = None, neighbours: int = 7, distance_function: Optional[DistanceFunction] = None, normalise_scores: bool = True) -> None: <NEW_LINE> <INDENT> assert _validate_input_dc(data_set, categorical_indices, neighbours, distance_function, norma... | Initialises the ``DensityCheck`` class. | 625941d83c8af77a43ae3a1d |
def delete_organism(self, organism_id): <NEW_LINE> <INDENT> data = { 'organism': organism_id, } <NEW_LINE> response = self.post('deleteOrganismWithSequence', data) <NEW_LINE> return response | Remove an organism completely.
:type organism_id: str
:param organism_id: Organism ID Number
:rtype: dict
:return: a dictionary with information about the deleted organism | 625941d8be8e80087fb20ebb |
def get_initialised_create_form_or_404(self, data=None, files=None): <NEW_LINE> <INDENT> plugin_form = self.get_form() <NEW_LINE> if plugin_form: <NEW_LINE> <INDENT> initial_data = {} <NEW_LINE> try: <NEW_LINE> <INDENT> initial_data = dict(plugin_form.plugin_data_fields) <NEW_LINE> <DEDENT> except Exception as err: <NE... | Get initialized create form or page 404.
Same as ``get_initialised_create_form`` but raises
``django.http.Http404`` on errors. | 625941d8925a0f43d254a0f3 |
def traj_to_option_list_from_seq(traj_file_name): <NEW_LINE> <INDENT> traj = np.load(traj_file_name, allow_pickle = True) <NEW_LINE> option_list = [] <NEW_LINE> traj_arr = [] <NEW_LINE> traj_arr = [] <NEW_LINE> for i in range(traj.shape[0]): <NEW_LINE> <INDENT> for j in range(len(traj[i])): <NEW_LINE> <INDENT> traj_arr... | load traj from traj_file; seg/transfer traj to option idx new way; save option idx to option_file | 625941d87b25080760e396d3 |
def get_list_of_mutations(control: bool = False) -> List[str]: <NEW_LINE> <INDENT> list_of_mutations = [ attr for attr in dir(UISMutations) if isinstance(getattr(UISMutations, attr), graphene.Field) ] <NEW_LINE> if control: <NEW_LINE> <INDENT> list_of_mutations.remove("broadcast") <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | Gets list of mutations | 625941d821bff66bcd684bcb |
def _assert_request_status(self, uuid, expected_status): <NEW_LINE> <INDENT> request = CreditRequest.objects.get(uuid=uuid) <NEW_LINE> self.assertEqual(request.status, expected_status) | Check the status of a credit request. | 625941d894891a1f4081bd25 |
def test_list_stacks(self): <NEW_LINE> <INDENT> list_stack_resp = self.verify(20, self.list_stacks, 1, 'Stack list is unavailable. ', "stack listing", self.heat_client) | Request stack list
Target component: Heat
Scenario:
1. Request the list of stacks.
Duration: 10 s.
Deployment tags: Heat | 625941d8090684286d50ef62 |
def wordBreak(self, s, wordDict): <NEW_LINE> <INDENT> if not s: return False <NEW_LINE> lookup = [False] * len(s) <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> for word in wordDict: <NEW_LINE> <INDENT> if s[i - len(word) + 1: i + 1] == word and ((i - len(word) == -1) or lookup[i - len(word)]): <NEW_LINE> <INDE... | :type s: str
:type wordDict: List[str]
:rtype: bool | 625941d8cc40096d61595bca |
def __init__(self): <NEW_LINE> <INDENT> self.ResourceName = None <NEW_LINE> self.ResourceType = None | :param ResourceName: 资源名称
:type ResourceName: str
:param ResourceType: 资源类型
:type ResourceType: str | 625941d856b00c62f0f148d5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.