code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@API.route('/statistics/') <NEW_LINE> def statistics(): <NEW_LINE> <INDENT> output = fedoratagger.lib.statistics(ft.SESSION) <NEW_LINE> jsonout = flask.jsonify(output) <NEW_LINE> return jsonout
Return the statistics of the package/tags in the database
625941bc07f4c71912b1136f
def label(self, image_np): <NEW_LINE> <INDENT> pass
Given a numpy array representing an RGB image, return a image showing bounding boxes around detected objects
625941bc56ac1b37e62640bc
def validate_query_from_token(self): <NEW_LINE> <INDENT> secret_key = self.app.config.get('conf').secret_key <NEW_LINE> self.decoded_token = tokenHelper.get_decoded_token(self.token, secret_key) <NEW_LINE> self.logger.info("==> token %s", self.decoded_token) <NEW_LINE> return True
read base64 token decide if it is valid return True/False
625941bc15fb5d323cde09f3
def parse_args(args): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description="Just a Fibonacci demonstration") <NEW_LINE> parser.add_argument( "--version", action="version", version="post_processing {ver}".format(ver=__version__)) <NEW_LINE> parser.add_argument( dest="n", help="n-th Fibonacci number", type=int, metavar="INT") <NEW_LINE> parser.add_argument( "-v", "--verbose", dest="loglevel", help="set loglevel to INFO", action="store_const", const=logging.INFO) <NEW_LINE> parser.add_argument( "-vv", "--very-verbose", dest="loglevel", help="set loglevel to DEBUG", action="store_const", const=logging.DEBUG) <NEW_LINE> return parser.parse_args(args)
Parse command line parameters Args: args ([str]): command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace
625941bcbf627c535bc130b6
def on_msg_received(msg): <NEW_LINE> <INDENT> if is_authorized(msg): <NEW_LINE> <INDENT> log(msg) <NEW_LINE> tipo = msg_type(msg) <NEW_LINE> if tipo == "text": <NEW_LINE> <INDENT> plugin_match, matches = msg_matches(msg["text"]) <NEW_LINE> if plugin_match is not None and matches is not None: <NEW_LINE> <INDENT> loaded = importlib.import_module("plugins." + plugin_match) <NEW_LINE> try: <NEW_LINE> <INDENT> loaded.on_msg_received(msg, matches) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> exc_type, exc_value, exc_traceback = sys.exc_info() <NEW_LINE> printable = repr(traceback.format_exception(exc_type, exc_value, exc_traceback)) <NEW_LINE> for sudoer in config.config["sudoers"]: <NEW_LINE> <INDENT> api.send_message(sudoer, "ME CAPOTARO AQUI PORRA \n\n" + printable) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif tipo != "text" and tipo != "outra coisa": <NEW_LINE> <INDENT> stt = importlib.import_module("plugins.stats") <NEW_LINE> stt.do_statistics(msg) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> log("Mensagem não autorizada de " + msg["from"]["first_name"] + " (" + str(msg["from"]["id"]) + ")")
Callback pra quando uma mensagem é recebida.
625941bc187af65679ca5005
def _get_related_checks(self, checks): <NEW_LINE> <INDENT> return [ch for ch in checks if ch.get("system") == self.CHECK_SYSTEM]
Returns a list of checks which have the same check system as this class.
625941bc99cbb53fe6792acf
def float_lt(v1, v2): <NEW_LINE> <INDENT> return v2 - v1 > ACCURACY
v1 < v2
625941bc15baa723493c3e5b
def find_equivalence_class(self, state, sse_states, syscall_states): <NEW_LINE> <INDENT> ec = set([state]) <NEW_LINE> changed = True <NEW_LINE> while changed: <NEW_LINE> <INDENT> changed = False <NEW_LINE> new_ec = set(ec) <NEW_LINE> for member in ec: <NEW_LINE> <INDENT> for X in sse_states[member].get_incoming_nodes(SavedStateTransition): <NEW_LINE> <INDENT> if not id(X) in syscall_states: <NEW_LINE> <INDENT> new_ec.add(id(X)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for member in (ec - syscall_states): <NEW_LINE> <INDENT> for X in sse_states[member].get_outgoing_nodes(SavedStateTransition): <NEW_LINE> <INDENT> new_ec.add(id(X)) <NEW_LINE> <DEDENT> <DEDENT> if new_ec != ec: <NEW_LINE> <INDENT> ec = new_ec <NEW_LINE> changed = True <NEW_LINE> <DEDENT> <DEDENT> return ec
This function finds the equivalence class for a given system state.
625941bc566aa707497f445f
def create_several_approvals_for_course(self, number_of_courses = 1): <NEW_LINE> <INDENT> teacher = self.create_and_return_local_user() <NEW_LINE> for N in range(number_of_courses): <NEW_LINE> <INDENT> course_id = new_course({ 'teacher' : teacher.key.id(), 'title' : 'foo course', 'body' : 'hey look mom', }) <NEW_LINE> list_of_ids_to_approve = [1,2,3,4,5] <NEW_LINE> course = get_course_by_id(course_id) <NEW_LINE> for i in list_of_ids_to_approve: <NEW_LINE> <INDENT> new_approval_request( course = course, googleID=i, formalName='John Doe %s' % i, email='j%s@example.com' % i )
create a course then approve several googleID's to access the course a helper method for the tests in this class; returns the course for which the approvals were generated. If more than 1 course is created, return the user instead of course/ids
625941bc4428ac0f6e5ba6d9
def on_response(self, src_node, nodes, token, max_nodes): <NEW_LINE> <INDENT> qnode = _QueuedNode(src_node, src_node.id.distance(self.info_hash), token) <NEW_LINE> self._add_responded_qnode(qnode) <NEW_LINE> qnodes = [_QueuedNode(n, n.id.distance( self.info_hash), None) for n in nodes] <NEW_LINE> self._add_queued_qnodes(qnodes) <NEW_LINE> return self._pop_nodes_to_query(max_nodes)
Nodes must not be duplicated
625941bcbe383301e01b5374
def __compute_cost_with_regularization(self, cross_entropy_cost, lambd): <NEW_LINE> <INDENT> W, m = self._features, self._depth + 1 <NEW_LINE> summ = np.sum(np.square(W)) <NEW_LINE> for l in range(1, m): <NEW_LINE> <INDENT> W = self._parameters['W' + str(l)] <NEW_LINE> summ += np.sum(np.square(W)) <NEW_LINE> <DEDENT> cost = (summ * lambd / (2 * m)) + cross_entropy_cost <NEW_LINE> return cost
:param net_output: :param Y: :param layer_index: :param lambd: :return:
625941bc8a43f66fc4b53f50
@_plot2d <NEW_LINE> def contour(x, y, z, ax, **kwargs): <NEW_LINE> <INDENT> primitive = ax.contour(x, y, z, **kwargs) <NEW_LINE> return ax, primitive
Contour plot of 2d DataArray Wraps matplotlib.pyplot.contour
625941bc55399d3f0558859b
@app.route('/') <NEW_LINE> def home_route(): <NEW_LINE> <INDENT> return (f"Enter Available Route Endpoints. Where dates are required, modify date selection as desired: <br><br/>" f"1. Dates & temps dictionary: <br/>" f" /api/v1.0/precipitation/ <br><br/>" f"2. JSON list of stations: <br/>" f" /api/v1.0/stations/ <br><br/>" f"3. JSON list of Temp Observations: <br/>" f" /api/v1.0/tobs/ <br><br/>" f"Please enter date as form 'yyyy' or 'yyyy-mm' or 'yyyy-mm-dd' <br><br/>" f"4. Stats Combined Stations. Enter Start date: <br/>" f" /api/v1.0/2017-01-01 <br><br/>" f"5. Stats Combined Stations. Enter Start & End Date: <br/>" f" /api/v1.0/2017-01-01/2018-08-29 <br><br/><end>")
Available API Route Endpoints
625941bccc0a2c11143dcd78
def __init__(self, element_description, *further_coefficients): <NEW_LINE> <INDENT> if isinstance(element_description, self.__class__): <NEW_LINE> <INDENT> self.__coefficients = element_description.__coefficients <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if type(element_description) in [ list, tuple ]: <NEW_LINE> <INDENT> coefficients = element_description <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> coefficients = [ element_description ] + list(further_coefficients) <NEW_LINE> <DEDENT> F = self._coefficient_field <NEW_LINE> self.__coefficients = [ F(c) for c in coefficients ] <NEW_LINE> <DEDENT> self.__remove_leading_zeros()
Create a new polynomial from the given @p element_description. @param element_description Valid input values are: - A Polynomial over the same field: then the polynomial is copied and @p further_coefficients is ignored. - An iterable object (with an @c __iter__() method): then the polynomial coefficients are read from the iterable and, again, @p further_coefficients is ignored. The list must be in ascending order: first the constant, then the linear, quadratic, and cubic coefficients; and so on. - Any number of arguments that can be interpreted as coefficient field elements; they will be combined into the list of coefficients @param further_coefficients The list of variable positional arguments. For example, there are several ways to construct the polynomial @f$ x^3 + 4x^2 - 3x + 2@f$: @code # Suppose R is a Polynomials template specialization # List of coefficients p2 = R( [2, -3, 4, 1] ) # Variable argument count p3 = R( 2, -3, 4, 1 ) # Copy p1 = R( p2 ) @endcode @note Leading zeros will be ignored.
625941bcf9cc0f698b1404e6
@when(u'I translate the text to upper case') <NEW_LINE> def step_impl(context): <NEW_LINE> <INDENT> context.result = to_uppercase(context.input)
Zavolani testovane funkce.
625941bc627d3e7fe0d68d36
def years_gold_value_decreased(gold_prices: str = gold_prices) -> (int, int): <NEW_LINE> <INDENT> pass
Analyze gold_prices returning a tuple of the year the gold price decreased the most and the year the gold price increased the most.
625941bc9f2886367277a778
def set_Page(self, value): <NEW_LINE> <INDENT> super(ListActivityInputSet, self)._set_input('Page', value)
Set the value of the Page input for this Choreo. ((optional, integer) The page number of the results to be returned. Used together with the PerPage parameter to paginate a large set of results.)
625941bca8ecb033257d2fbc
def testLocking(self): <NEW_LINE> <INDENT> corpus = LeeCorpus() <NEW_LINE> for sg in range(2): <NEW_LINE> <INDENT> model = word2vec.Word2Vec(size=4, hs=1, negative=5, min_count=1, sg=sg, window=5) <NEW_LINE> model.build_vocab(corpus) <NEW_LINE> locked0 = numpy.copy(model.syn0[0]) <NEW_LINE> unlocked1 = numpy.copy(model.syn0[1]) <NEW_LINE> model.syn0_lockf[0] = 0.0 <NEW_LINE> model.train(corpus) <NEW_LINE> self.assertFalse((unlocked1 == model.syn0[1]).all()) <NEW_LINE> self.assertTrue((locked0 == model.syn0[0]).all())
Test word2vec training doesn't change locked vectors.
625941bc94891a1f4081b990
def copy(self): <NEW_LINE> <INDENT> new_self = [[0] * 3 for x in range(3)] <NEW_LINE> b = '' <NEW_LINE> for row in range(len(self.tiles)): <NEW_LINE> <INDENT> for col in range(len(self.tiles[0])): <NEW_LINE> <INDENT> b += str(self.tiles[row][col]) <NEW_LINE> <DEDENT> <DEDENT> new_object = Board(b) <NEW_LINE> return new_object
returns a newly-constructed Board object that is a deep copy of the called object.
625941bcb7558d58953c4e02
def server(self, node, cluster, options=[]): <NEW_LINE> <INDENT> options2 = options + [ ('--datadir', node.get_workdir()), ('--zookeeper', self._zkargs()), ] <NEW_LINE> server = JubaServer(node, cluster.service, cluster.name, options2) <NEW_LINE> cluster._servers += [server] <NEW_LINE> self._rpc_servers.append(server) <NEW_LINE> return server
Constructs new server.
625941bc24f1403a92600a51
def absolute_difference( labels, predictions, weights=1.0, scope=None, loss_collection=ops.GraphKeys.LOSSES): <NEW_LINE> <INDENT> with ops.name_scope(scope, "absolute_difference", [predictions, labels, weights]) as scope: <NEW_LINE> <INDENT> predictions.get_shape().assert_is_compatible_with(labels.get_shape()) <NEW_LINE> predictions = math_ops.to_float(predictions) <NEW_LINE> labels = math_ops.to_float(labels) <NEW_LINE> losses = math_ops.abs(math_ops.sub(predictions, labels)) <NEW_LINE> return compute_weighted_loss(losses, weights, scope, loss_collection)
Adds an Absolute Difference loss to the training procedure. `weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a `Tensor` of shape `[batch_size]`, then the total loss for each sample of the batch is rescaled by the corresponding element in the `weights` vector. If the shape of `weights` matches the shape of `predictions`, then the loss of each measurable element of `predictions` is scaled by the corresponding value of `weights`. WARNING: `weights` also supports dimensions of 1, but the broadcasting does not work as advertised, you'll wind up with weighted sum instead of weighted mean for any but the last dimension. This will be cleaned up soon, so please do not rely on the current behavior for anything but the shapes documented for `weights` below. Args: labels: The ground truth output tensor, same dimensions as 'predictions'. predictions: The predicted outputs. weights: Coefficients for the loss a scalar, a tensor of shape `[batch_size]` or a tensor whose shape matches `predictions`. scope: The scope for the operations performed in computing the loss. loss_collection: collection to which this loss will be added. Returns: A scalar `Tensor` representing the loss value. Raises: ValueError: If the shape of `predictions` doesn't match that of `labels` or if the shape of `weights` is invalid.
625941bc7cff6e4e8111786e
def limited_integrate(fa, fd, G, DE): <NEW_LINE> <INDENT> fa, fd = fa*Poly(1/fd.LC(), DE.t), fd.monic() <NEW_LINE> Fa = Poly(0, DE.t) <NEW_LINE> Fd = Poly(1, DE.t) <NEW_LINE> G = [(fa, fd)] + G <NEW_LINE> h, A = param_rischDE(Fa, Fd, G, DE) <NEW_LINE> V = A.nullspace() <NEW_LINE> V = [v for v in V if v[0] != 0] <NEW_LINE> if not V: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c0 = V[0][0] <NEW_LINE> v = V[0]/(-c0) <NEW_LINE> r = len(h) <NEW_LINE> m = len(v) - r - 1 <NEW_LINE> C = list(v[1: m + 1]) <NEW_LINE> y = -sum([v[m + 1 + i]*h[i][0].as_expr()/h[i][1].as_expr() for i in range(r)]) <NEW_LINE> y_num, y_den = y.as_numer_denom() <NEW_LINE> Ya, Yd = Poly(y_num, DE.t), Poly(y_den, DE.t) <NEW_LINE> Y = Ya*Poly(1/Yd.LC(), DE.t), Yd.monic() <NEW_LINE> return Y, C
Solves the limited integration problem: f = Dv + Sum(ci*wi, (i, 1, n))
625941bceab8aa0e5d26da46
def add_root(self, e) -> Position: <NEW_LINE> <INDENT> if self._root is not None: <NEW_LINE> <INDENT> raise ValueError('Root exists') <NEW_LINE> <DEDENT> self._size = 1 <NEW_LINE> self._root = self._Node(e) <NEW_LINE> return self._make_position(self._root)
Place element e at root of empty tree.
625941bccb5e8a47e48b7996
def remove_load(self): <NEW_LINE> <INDENT> coord = self._curr_element_coord <NEW_LINE> if isinstance(self.editor.bus_grid[coord], Bus): <NEW_LINE> <INDENT> bus = self.bus_at(coord) <NEW_LINE> bus.pl = 0 <NEW_LINE> bus.ql = 0 <NEW_LINE> bus.load_ground = EARTH <NEW_LINE> self.status_msg.emit("Removed load") <NEW_LINE> self.update_values()
Called by: add_load_button.pressed
625941bc91f36d47f21ac3d8
def test_no_root_needed_if_matched_requirements_even_uninstalled(self): <NEW_LINE> <INDENT> with patch('umake.frameworks.RequirementsHandler') as requirement_mock: <NEW_LINE> <INDENT> requirement_mock.return_value.is_bucket_installed.return_value = True <NEW_LINE> self.loadFramework("testframeworks") <NEW_LINE> self.assertFalse(self.CategoryHandler.categories["category-f"].frameworks["framework-a"].is_installed) <NEW_LINE> self.assertFalse(self.CategoryHandler.categories["category-f"].frameworks["framework-a"].need_root_access)
Framework which are uninstalled but with matched requirements doesn't need root access
625941bcd99f1b3c44c6747e
def disconnect_all(): <NEW_LINE> <INDENT> if not have_dbus(): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> for active in NetworkManager.NetworkManager.ActiveConnections: <NEW_LINE> <INDENT> conn = NetworkManager.Settings.GetConnectionByUuid(active.Uuid) <NEW_LINE> if conn.GetSettings()['connection']['type'] == 'vpn': <NEW_LINE> <INDENT> disconnect_provider(active.Uuid)
Disconnect all active VPN connections.
625941bc63b5f9789fde6fce
def maxelements(seq): <NEW_LINE> <INDENT> max_indices = [] <NEW_LINE> if seq: <NEW_LINE> <INDENT> max_val = seq[0] <NEW_LINE> for i,val in ((i,val) for i,val in enumerate(seq) if val >= max_val): <NEW_LINE> <INDENT> if val == max_val: <NEW_LINE> <INDENT> max_indices.append(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> max_val = val <NEW_LINE> max_indices = [i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return max_indices
Return list of position(s) of largest element
625941bc925a0f43d2549d5c
def xiinUseChecker(self, xiinArgDict): <NEW_LINE> <INDENT> if xiinArgDict.upload is None: <NEW_LINE> <INDENT> if len(xiinArgDict.args) < 2: <NEW_LINE> <INDENT> self.parser.error('Nothing to do. Try option -h or --help.') <NEW_LINE> exit(2) <NEW_LINE> <DEDENT> elif xiinArgDict.filename is None and xiinArgDict.display is None and xiinArgDict.grep is None: <NEW_LINE> <INDENT> self.parser.error('specify to display output or send to a file') <NEW_LINE> exit(3) <NEW_LINE> <DEDENT> elif xiinArgDict.directory == '/proc': <NEW_LINE> <INDENT> self.parser.error('xiin can not walk /proc') <NEW_LINE> exit(4) <NEW_LINE> <DEDENT> elif xiinArgDict.directory is None: <NEW_LINE> <INDENT> self.parser.error('xiin needs a directory') <NEW_LINE> exit(5) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if len(xiinArgDict.upload ) < 2: <NEW_LINE> <INDENT> print('') <NEW_LINE> self.parser.error('ERROR: No xiin upload options given') <NEW_LINE> self.parser.error('[Usage: uploader <source> <target> <uname> <password> ]') <NEW_LINE> exit(6)
Checks for use errors.
625941bc4f88993c3716bf53
def _check_percentile(self, q): <NEW_LINE> <INDENT> msg = ("percentiles should all be in the interval [0, 1]. " "Try {0} instead.") <NEW_LINE> q = np.asarray(q) <NEW_LINE> if q.ndim == 0: <NEW_LINE> <INDENT> if not 0 <= q <= 1: <NEW_LINE> <INDENT> raise ValueError(msg.format(q / 100.0)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not all(0 <= qs <= 1 for qs in q): <NEW_LINE> <INDENT> raise ValueError(msg.format(q / 100.0)) <NEW_LINE> <DEDENT> <DEDENT> return q
Validate percentiles. Used by describe and quantile
625941bc71ff763f4b54956f
def PSC_writeParameters(self, File, parameters): <NEW_LINE> <INDENT> out_list = [] <NEW_LINE> out_list.append('\n## Parameters\n') <NEW_LINE> for x in range(len(parameters)): <NEW_LINE> <INDENT> out_list.append( parameters[x][0] + ' = ' + self.mode_number_format % parameters[x][1] + '\n' ) <NEW_LINE> <DEDENT> for x in out_list: <NEW_LINE> <INDENT> File.write(x) <NEW_LINE> <DEDENT> File.write('\n')
PSC_writeParameters(File,parameters) Write mode parameter initialisations to a PSC file Arguments: ========= File: open, writable file object parameters: a list of (parameter,value) pairs
625941bc9b70327d1c4e0cbc
def _get_impl(self) -> MailClientImpl: <NEW_LINE> <INDENT> if not hasattr(self, '_impl') or not self._impl: <NEW_LINE> <INDENT> if self._settings.impl_type == ImplementationType.DUMMY: <NEW_LINE> <INDENT> from .dummy_mail_client import DummyMailClient <NEW_LINE> self._impl = DummyMailClient(DummyMailClientSettings.load_settings(self._config_path)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from .generic_mail_client import GenericMailClient <NEW_LINE> self._impl = GenericMailClient(GenericMailClientSettings.load_settings(self._config_path)) <NEW_LINE> <DEDENT> <DEDENT> return self._impl
initializes implementation classes, if not already done Returns: MailClientImpl: the configured implementation class
625941bca4f1c619b28aff28
def diff_values(a, b, tolerance=0.0): <NEW_LINE> <INDENT> if isinstance(a, float) and isinstance(b, float): <NEW_LINE> <INDENT> if np.isnan(a) and np.isnan(b): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return not np.allclose(a, b, tolerance, 0.0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return a != b
Diff two scalar values. If both values are floats they are compared to within the given relative tolerance.
625941bcc4546d3d9de7291a
def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None
Operator - a model defined in Swagger
625941bc925a0f43d2549d5d
def command(*args, **kwargs): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> if not func or not callable(func): <NEW_LINE> <INDENT> raise TypeError( "Decorator @{command} should be added to a method " "instead of {type}.".format( command=command.__name__, type=type(func).__name__) ) <NEW_LINE> <DEDENT> arguments = list(args) <NEW_LINE> name = kwargs.get('name') <NEW_LINE> if not name: <NEW_LINE> <INDENT> command_name = func.__name__.lower().replace('_', '-') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> command_name = name <NEW_LINE> <DEDENT> kwargs.setdefault('description', func.__doc__) <NEW_LINE> func.__command__ = _Command( func.__name__, command_name, kwargs, arguments) <NEW_LINE> return func <NEW_LINE> <DEDENT> return decorator
Add this decorator to a method to expose it to the commands function.
625941bc26238365f5f0ed53
def test2(): <NEW_LINE> <INDENT> payload = {'key1': 'value1', 'key2': 'value2'} <NEW_LINE> html = requests.get("http://httpbin.org/get", params=payload) <NEW_LINE> print(html.url) <NEW_LINE> print('html.text:{}'.format(html.text)) <NEW_LINE> html = requests.post("http://httpbin.org/post", data=payload) <NEW_LINE> print('html.text:{}'.format(html.text)) <NEW_LINE> soup = BeautifulSoup(html.text, 'lxml') <NEW_LINE> print(soup)
https://medium.com/@yanweiliu/python%E7%88%AC%E8%9F%B2%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E4%B8%80-beautifulsoup-1ee011df8768
625941bc01c39578d7e74d23
def plot(self, output_dir="", interpolate=True, length=3, method='cubic', export=True): <NEW_LINE> <INDENT> mpl.style.use('fivethirtyeight') <NEW_LINE> from matplotlib.font_manager import FontProperties <NEW_LINE> font = FontProperties(fname=r"c:\windows\fonts\msyh.ttc", size=14) <NEW_LINE> mpl.rcParams['axes.unicode_minus'] = False <NEW_LINE> plt.figure(figsize=(10, 6), dpi=320, facecolor=None) <NEW_LINE> plt.title(u'城投债', fontproperties=font) <NEW_LINE> plt.xlabel(u'期限', fontproperties=font) <NEW_LINE> plt.ylabel(u'收益率', fontproperties=font) <NEW_LINE> plt.xticks(self.x, self.data.index, fontproperties=font, rotation=45) <NEW_LINE> plt.grid(b=False, axis='x') <NEW_LINE> if interpolate: <NEW_LINE> <INDENT> self.interpolate(length, method) <NEW_LINE> plt.xticks(self.newx, self.int_data.index, fontproperties=font, rotation=45) <NEW_LINE> plt.plot(self.x, self.data, 'o', self.newx, self.int_data, '-', linewidth=2) <NEW_LINE> plt.legend(self.keys, loc='best') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> plt.plot(self.x, self.data, linewidth=2) <NEW_LINE> plt.legend(self.keys, fontproperties=font) <NEW_LINE> <DEDENT> plt.tight_layout() <NEW_LINE> if len(output_dir) == 0: <NEW_LINE> <INDENT> output_dir = self.cwd <NEW_LINE> <DEDENT> plt.savefig(os.path.join(output_dir, 'fig.png'))
plot中可指定: 插值: interpolate=True 插值步长:length=3 插值方法: method='cubic' 具体参见类内方法interpolate
625941bcbe7bc26dc91cd4ee
def draw_HoughImageP(lines, img): <NEW_LINE> <INDENT> for element in range(len(lines)): <NEW_LINE> <INDENT> for x1, y1, x2, y2 in lines[element]: <NEW_LINE> <INDENT> cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), 2) <NEW_LINE> <DEDENT> <DEDENT> return(img)
:param lines: lines gotten from probabilistic HoughLines function :param img: image on which we want to draw those lines :return:
625941bc7d847024c06be1a1
def get_next_var(self): <NEW_LINE> <INDENT> var_name = "var" + str(self.var_counter) <NEW_LINE> var_ast = ast.Name(id=var_name) <NEW_LINE> self.var_counter += 1 <NEW_LINE> return var_ast, var_name
Returns the next variable AST node and name :return var_ast: New variable AST representation :return var_name: New variable name
625941bcd486a94d0b98e02e
def socket_index(apic_id): <NEW_LINE> <INDENT> if apic_id is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if cpuid(apic_id,0x0)[0] < 0xb: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> eax, ebx, ecx, edx = cpuid(apic_id,0xb,1) <NEW_LINE> x2apic_id = edx <NEW_LINE> socket_index = x2apic_id >> (eax & 0x1f); <NEW_LINE> return socket_index
Returns the socket portion of the APIC ID
625941bc507cdc57c6306bbd
def _create_deprecated_modules_files(): <NEW_LINE> <INDENT> for (new_module_name, deprecated_path, correct_import_path, _) in _DEPRECATED_MODULES: <NEW_LINE> <INDENT> relative_dots = deprecated_path.count(".") * "." <NEW_LINE> deprecated_content = _FILE_CONTENT_TEMPLATE.format( new_module_name=new_module_name, relative_dots=relative_dots, deprecated_path=deprecated_path, correct_import_path=correct_import_path) <NEW_LINE> with _get_deprecated_path(deprecated_path).open('w') as f: <NEW_LINE> <INDENT> f.write(deprecated_content)
Add submodules that will be deprecated. A file is created based on the deprecated submodule's name. When this submodule is imported a deprecation warning will be raised.
625941bc71ff763f4b549570
def start_service(serviceName): <NEW_LINE> <INDENT> run_service_command(serviceName, 'start')
Start Service.
625941bc9c8ee82313fbb65d
def __probe_for_device(self): <NEW_LINE> <INDENT> while not self.i2c.try_lock(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.i2c.writeto(self.device_address, b"") <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = bytearray(1) <NEW_LINE> self.i2c.readfrom_into(self.device_address, result) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> raise ValueError("No I2C device at address: 0x%x" % self.device_address) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.i2c.unlock()
Try to read a byte from an address, if you get an OSError it means the device is not there or that the device does not support these means of probing
625941bc1f037a2d8b9460e7
def name(self): <NEW_LINE> <INDENT> return _BLISS_swig.BLISS_vector_conjugate_sptr_name(self)
name(self) -> string
625941bcadb09d7d5db6c67a
def plot_pdfpages(filename, figs, save_single_figs = False, fig_names = None): <NEW_LINE> <INDENT> from matplotlib.backends.backend_pdf import PdfPages <NEW_LINE> pdf = PdfPages(filename) <NEW_LINE> for fig in figs: <NEW_LINE> <INDENT> pdf.savefig(fig) <NEW_LINE> <DEDENT> pdf.close() <NEW_LINE> if save_single_figs: <NEW_LINE> <INDENT> indp = filename.index('.') <NEW_LINE> cartnam = filename[:indp]+'_figures/' <NEW_LINE> if not os.path.exists(cartnam): <NEW_LINE> <INDENT> os.mkdir(cartnam) <NEW_LINE> <DEDENT> if fig_names is None: <NEW_LINE> <INDENT> fig_names = ['pag_{}'.format(i+1) for i in range(len(figs))] <NEW_LINE> <DEDENT> for fig,nam in zip(figs, fig_names): <NEW_LINE> <INDENT> fig.savefig(cartnam+nam+'.pdf') <NEW_LINE> <DEDENT> <DEDENT> return
Saves a list of figures to a pdf file.
625941bccc0a2c11143dcd79
def first_last_indices(df, tmzone=None): <NEW_LINE> <INDENT> df.sort_index(inplace=True) <NEW_LINE> if tmzone is None: <NEW_LINE> <INDENT> first_index = df.first_valid_index() <NEW_LINE> last_index = df.last_valid_index() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if df.index[0].utcoffset() is None: <NEW_LINE> <INDENT> first_index = df.first_valid_index().tz_localize(tmzone, ambiguous="NaT") <NEW_LINE> last_index = df.last_valid_index().tz_localize(tmzone, ambiguous="NaT") <NEW_LINE> <DEDENT> elif df.index[0].utcoffset().total_seconds() == 0.0: <NEW_LINE> <INDENT> first_index = df.first_valid_index().tz_convert(tmzone) <NEW_LINE> last_index = df.last_valid_index().tz_convert(tmzone) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> first_index = df.first_valid_index() <NEW_LINE> last_index = df.last_valid_index() <NEW_LINE> <DEDENT> <DEDENT> return first_index, last_index
Gets first and last index in a dataset; capable of considering time series with timezone information Args: df (pd.DataFrame): dataframe with indices tmzone (str): timzone code of data if timezone specified; defaults to None Returns: first index, last index
625941bc6e29344779a624fd
def _accuracy(self, y, yhat): <NEW_LINE> <INDENT> return np.sum(y == yhat) / len(y)
A utility function to compute the accuracy of the classifier
625941bc167d2b6e31218a7f
def test(): <NEW_LINE> <INDENT> from journal import help <NEW_LINE> return
Sanity check: verify that the channel is accessible
625941bc6fb2d068a760ef83
def HPBW(feedtaper,wavelength,diameter): <NEW_LINE> <INDENT> return (1.02 + 0.0135 * feedtaper) * wavelength/diameter
Half-power beamwidth estimate @param feedtaper : feed pattern amplitude at edge of primary, in dB @type feedtaper : float @param wavelength : in same units as diameter @type wavelength : float @param diameter : of main aperture, in same units as wavelength @type diameter : float @return: HPBW in radians (float)
625941bcd7e4931a7ee9de05
def test_private_key(self): <NEW_LINE> <INDENT> self.assertRaises(syml.exceptions.InvalidKeyException, syml.Sign, document, os.path.join(os.path.dirname(__file__), "keys", "public_key.pem") )
You can't sign with a public key
625941bc2c8b7c6e89b356ab
def test_get_token_invalid_token_get_new_from_refresh(self): <NEW_LINE> <INDENT> token1 = get_token() <NEW_LINE> last_verified = datetime.now() + timedelta(minutes=-11) <NEW_LINE> cache.set('token','invalis_token') <NEW_LINE> cache.set('last_verified', last_verified) <NEW_LINE> token2 = get_token() <NEW_LINE> refresh_token = cache.get('refresh') <NEW_LINE> logger.debug("new_token: %s", token2) <NEW_LINE> logger.debug("refresh_token: %s", refresh_token) <NEW_LINE> assert_false(token1 == token2) <NEW_LINE> assert_false(refresh_token)
create a new token, change the token and the last_verified. expect to use the refresh to get a new token and no referesh will be in the cache.
625941bcdc8b845886cb541d
def get_public_ip(): <NEW_LINE> <INDENT> canhaz = urlopen("http://icanhazip.com") <NEW_LINE> ip = canhaz.read().split("\n")[0] <NEW_LINE> return ip
Get public IP (outside NAT)
625941bcec188e330fd5a68d
def _generate_A_ops_implicit(sc, L, dt): <NEW_LINE> <INDENT> A_len = len(sc) <NEW_LINE> temp = [spre(c).data + spost(c.dag()).data for c in sc] <NEW_LINE> tempL = (L + np.sum([lindblad_dissipator(c, data_only=True) for c in sc], axis=0)) <NEW_LINE> out = [] <NEW_LINE> out += temp <NEW_LINE> out += [sp.eye(L.shape[0], format='csr') - 0.5*dt*tempL] <NEW_LINE> out += [tempL] <NEW_LINE> out1 = [out] <NEW_LINE> out1 += [[] for n in range(A_len - 1)] <NEW_LINE> return out1
pre-compute superoperator operator combinations that are commonly needed when evaluating the RHS of stochastic master equations
625941bc16aa5153ce362361
def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Monitor.V1>'
Provide a friendly representation :returns: Machine friendly representation :rtype: str
625941bc44b2445a33931f88
def draw_text(text,font,surface,x,y): <NEW_LINE> <INDENT> text_obj = font.render(text,True,TEXT_COLOR) <NEW_LINE> text_rect = text_obj.get_rect() <NEW_LINE> text_rect.topleft = (x,y) <NEW_LINE> surface.blit(text_obj,text_rect)
把文字绘制到指定平面的指定位置
625941bc462c4b4f79d1d5b9
def preprocess_data(image, nwidth, nheight): <NEW_LINE> <INDENT> image = image.resize((nwidth, nheight)) <NEW_LINE> image = np.array(image) <NEW_LINE> image = np.clip(image/255.0, 0.0, 1.0) <NEW_LINE> return image
This function creates normalized, square images, this is so that all images are the same shape, and normalize so that pixel values will be in the range [0,1]
625941bc0383005118ecf4cd
def get_single_eth_info(url, dict1, client): <NEW_LINE> <INDENT> print((PRINT_STYLE1) % ("Id", dict1["Id"])) <NEW_LINE> if "MACAddress" in dict1.keys(): <NEW_LINE> <INDENT> print((PRINT_STYLE1) % ("MACAddress", dict1["MACAddress"])) <NEW_LINE> <DEDENT> if "PermanentMACAddress" in dict1.keys(): <NEW_LINE> <INDENT> print((PRINT_STYLE1) % ("PermanentMACAddress", dict1["PermanentMACAddress"])) <NEW_LINE> <DEDENT> print((PRINT_STYLE1) % ("LinkStatus", dict1["LinkStatus"])) <NEW_LINE> print(PRINT_STYLE2) <NEW_LINE> get_ipv4addresses(dict1) <NEW_LINE> get_ipv6addresses(dict1) <NEW_LINE> get_vlans(url, client)
#========================================================================== # @Method: Export host Ethernet information functions. # @Param: url dict1, dictionary client, RedfishClient object # @Return: # @date: 2017.7.27 #==========================================================================
625941bc5fcc89381b1e15a6
def write_html(html: str, directory="news") -> str: <NEW_LINE> <INDENT> filename = str(uuid.uuid4()) <NEW_LINE> path = Path(directory) / filename <NEW_LINE> with path.open("w") as file: <NEW_LINE> <INDENT> file.write(html) <NEW_LINE> <DEDENT> return filename
write html to file Args: html: str html will be write directory: target directory for save file Returns: filename generated
625941bc6e29344779a624fe
def test_put_edit_invalid_access_token(self): <NEW_LINE> <INDENT> headers = {"Authorization": "Bearer 1234"} <NEW_LINE> u = {"username": "test", "password": "test_password"} <NEW_LINE> url = f'/users/user/{self.reg1["id"]}' <NEW_LINE> r = self.client.put(url, headers=headers, json=u) <NEW_LINE> self.assertEqual(r.status_code, 422) <NEW_LINE> keys = ("message", "message_type") <NEW_LINE> for i in keys: <NEW_LINE> <INDENT> self.assertIn(i, r.json) <NEW_LINE> <DEDENT> self.assertEqual(r.json[keys[0]], INVALID_TOKEN) <NEW_LINE> self.assertEqual(r.json[keys[1]], ERROR_INVALID_TOKEN)
Test the Put method of the User view. This test tries to edit a user providing an invalid access token, which shouldn't work.
625941bcd8ef3951e3243426
def addTable(self, table): <NEW_LINE> <INDENT> env = self <NEW_LINE> env.tables.append(table)
Inserta una nueva tabla
625941bc099cdd3c635f0b45
def merge(A,B,index1=0,index2=0,C=[]): <NEW_LINE> <INDENT> if( index1 == len(A) ): <NEW_LINE> <INDENT> if( index2 == len(B) ): <NEW_LINE> <INDENT> return C <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> C.append(B[index2]) <NEW_LINE> index2 +=1 <NEW_LINE> return merge(A,B,index1,index2,C) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if( index2 == len(B) ): <NEW_LINE> <INDENT> C.append(A[index1]) <NEW_LINE> index1 +=1 <NEW_LINE> return merge(A,B,index1,index2,C) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if(A[index1]<B[index2]): <NEW_LINE> <INDENT> C.append(A[index1]) <NEW_LINE> index1 += 1 <NEW_LINE> return merge(A,B,index1,index2,C) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> C.append(B[index2]) <NEW_LINE> index2 += 1 <NEW_LINE> return merge(A,B,index1,index2,C)
Objective : Merge two sorted lists - efficiently parameters : A : sorted list A B : sorted list B index1 : index tracker for list A index2 : index tracker for list B C : the merged list
625941bccdde0d52a9e52f19
def get_parent(self, children=None): <NEW_LINE> <INDENT> if children is None: <NEW_LINE> <INDENT> children = self <NEW_LINE> <DEDENT> while children["depth"] > 0: <NEW_LINE> <INDENT> children = Comment(construct_authorperm(children["parent_author"], children["parent_permlink"]), crea_instance=self.crea) <NEW_LINE> <DEDENT> return children
Returns the parent post with depth == 0
625941bcad47b63b2c509e69
def add_namespace(self, ns, path=None): <NEW_LINE> <INDENT> if ns not in self.namespaces: <NEW_LINE> <INDENT> self.namespaces.append(ns) <NEW_LINE> if self not in ns.apis: <NEW_LINE> <INDENT> ns.apis.append(self) <NEW_LINE> <DEDENT> if path is not None: <NEW_LINE> <INDENT> self.ns_paths[ns] = path <NEW_LINE> <DEDENT> <DEDENT> for r in ns.resources: <NEW_LINE> <INDENT> urls = self.ns_urls(ns, r.urls) <NEW_LINE> self.register_resource(ns, r.resource, *urls, **r.kwargs) <NEW_LINE> <DEDENT> for name, definition in six.iteritems(ns.models): <NEW_LINE> <INDENT> self.models[name] = definition <NEW_LINE> <DEDENT> if not self.blueprint and self.app is not None: <NEW_LINE> <INDENT> self._configure_namespace_logger(self.app, ns)
This method registers resources from namespace for current instance of api. You can use argument path for definition custom prefix url for namespace. :param Namespace ns: the namespace :param path: registration prefix of namespace
625941bc6fece00bbac2d625
def test_is_correct_offsets(self): <NEW_LINE> <INDENT> paths = ['path/1', 'path/2', 'path/3'] <NEW_LINE> topic = Topic('test') <NEW_LINE> with open(self.offsets) as f: <NEW_LINE> <INDENT> _offset = f.read() <NEW_LINE> <DEDENT> self.assertEqual('0', _offset)
is create_offset_file working
625941bc9c8ee82313fbb65e
def is_prime(num): <NEW_LINE> <INDENT> for i in range(2, int(num/2)+1): <NEW_LINE> <INDENT> if num % i == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Checks if num is prime or not :param num: :return: true if num is prime, else false
625941bccad5886f8bd26ecb
def load_data( ticker, n_steps=50, scale=True, shuffle=True, lookup_step=1, test_size=0.2, feature_columns=["adjclose", "volume", "open", "high", "low"], ): <NEW_LINE> <INDENT> if isinstance(ticker, str): <NEW_LINE> <INDENT> df = si.get_data(ticker) <NEW_LINE> <DEDENT> elif isinstance(ticker, pd.DataFrame): <NEW_LINE> <INDENT> df = ticker <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("ticker can be either a str or a `pd.DataFrame` instances") <NEW_LINE> <DEDENT> result = {} <NEW_LINE> result["df"] = df.copy() <NEW_LINE> for col in feature_columns: <NEW_LINE> <INDENT> assert col in df.columns, f"'{col}' does not exist in the dataframe." <NEW_LINE> <DEDENT> if scale: <NEW_LINE> <INDENT> column_scaler = {} <NEW_LINE> for column in feature_columns: <NEW_LINE> <INDENT> scaler = preprocessing.MinMaxScaler() <NEW_LINE> df[column] = scaler.fit_transform(np.expand_dims(df[column].values, axis=1)) <NEW_LINE> column_scaler[column] = scaler <NEW_LINE> <DEDENT> result["column_scaler"] = column_scaler <NEW_LINE> <DEDENT> df["future"] = df["adjclose"].shift(-lookup_step) <NEW_LINE> last_sequence = np.array(df[feature_columns].tail(lookup_step)) <NEW_LINE> df.dropna(inplace=True) <NEW_LINE> sequence_data = [] <NEW_LINE> sequences = deque(maxlen=n_steps) <NEW_LINE> for entry, target in zip(df[feature_columns].values, df["future"].values): <NEW_LINE> <INDENT> sequences.append(entry) <NEW_LINE> if len(sequences) == n_steps: <NEW_LINE> <INDENT> sequence_data.append([np.array(sequences), target]) <NEW_LINE> <DEDENT> <DEDENT> last_sequence = list(sequences) + list(last_sequence) <NEW_LINE> last_sequence = np.array(last_sequence) <NEW_LINE> result["last_sequence"] = last_sequence <NEW_LINE> X, y = [], [] <NEW_LINE> for seq, target in sequence_data: <NEW_LINE> <INDENT> X.append(seq) <NEW_LINE> y.append(target) <NEW_LINE> <DEDENT> X = np.array(X) <NEW_LINE> y = np.array(y) <NEW_LINE> X = X.reshape((X.shape[0], X.shape[2], X.shape[1])) <NEW_LINE> ( result["X_train"], result["X_test"], result["y_train"], result["y_test"], ) = train_test_split(X, y, test_size=test_size, shuffle=shuffle) <NEW_LINE> return result
Loads data from Yahoo Finance source, as well as scaling, shuffling, normalizing and splitting. Params: ticker (str/pd.DataFrame): the ticker you want to load, examples include AAPL, TESL, etc. n_steps (int): the historical sequence length (i.e window size) used to predict, default is 50 scale (bool): whether to scale prices from 0 to 1, default is True shuffle (bool): whether to shuffle the data, default is True lookup_step (int): the future lookup step to predict, default is 1 (e.g next day) test_size (float): ratio for test data, default is 0.2 (20% testing data) feature_columns (list): the list of features to use to feed into the model, default is everything grabbed from yahoo_fin
625941bca17c0f6771cbdf3c
def _CommonChecks(input_api, output_api): <NEW_LINE> <INDENT> results = [] <NEW_LINE> results.extend(_RunUnitTests(input_api, output_api)) <NEW_LINE> results.extend(_RunPyLint(input_api, output_api)) <NEW_LINE> return results
Does all presubmit checks for chekteamtags.
625941bcc432627299f04b2d
def get_cursor(self) -> sqlite3.Cursor: <NEW_LINE> <INDENT> return self._cur
カーソルを返す. sqlite3.Cursorオブジェクトを返す. :return: sqlite3.
625941bc07d97122c417876e
def initialize(context): <NEW_LINE> <INDENT> content.initialize(context)
Zope 2 initialize
625941bcd7e4931a7ee9de06
def test_writeSequence(self): <NEW_LINE> <INDENT> self.pp.writeSequence(['test ', 'data']) <NEW_LINE> self.assertEqual(self.session.conn.data[self.session], ['test data'])
When a sequence is passed to the writeSequence method, it should be joined together and sent to the session channel's write method.
625941bcff9c53063f47c0de
def setSparkiDebug(level): <NEW_LINE> <INDENT> if SPARKI_DEBUGS: <NEW_LINE> <INDENT> printDebug("Changing Sparki debug level to " + str(level), DEBUG_INFO) <NEW_LINE> level = int(constrain(level, DEBUG_ALWAYS, DEBUG_DEBUG)) <NEW_LINE> args = [level] <NEW_LINE> sendSerial(COMMAND_CODES["SET_DEBUG_LEVEL"], args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> printDebug("Setting sparki debug level is not available", DEBUG_ERROR)
Sets the debug (in Sparki) to level arguments: level - int between 0 and 5; greater numbers produce more output (many of Sparki's debug statements are turned off) returns: none
625941bc0fa83653e4656ea6
def distributed_function(input_iterator): <NEW_LINE> <INDENT> x, y, sample_weights = _prepare_feed_values( model, input_iterator, mode) <NEW_LINE> strategy = distribution_strategy_context.get_strategy() <NEW_LINE> outputs = strategy.experimental_run_v2( per_replica_function, args=(x, y, sample_weights)) <NEW_LINE> all_outputs = dist_utils.unwrap_output_dict( strategy, outputs, mode) <NEW_LINE> return all_outputs
A single step of the distributed execution across replicas.
625941bcf9cc0f698b1404e7
def read_count_matrices(input_filename, shuffle=False, skip=0, min_counts=0, min_as_counts=0, sample=0): <NEW_LINE> <INDENT> infiles = open_input_files(input_filename) <NEW_LINE> is_finished = False <NEW_LINE> count_matrix = [] <NEW_LINE> expected_matrix = [] <NEW_LINE> line_num = 0 <NEW_LINE> skip_num = 0 <NEW_LINE> while not is_finished: <NEW_LINE> <INDENT> is_comment = False <NEW_LINE> line_num += 1 <NEW_LINE> count_line = [] <NEW_LINE> expected_line = [] <NEW_LINE> num_as = 0 <NEW_LINE> for i in range(len(infiles)): <NEW_LINE> <INDENT> line = infiles[i].readline().strip() <NEW_LINE> if line.startswith("#") or line.startswith("CHROM"): <NEW_LINE> <INDENT> is_comment = True <NEW_LINE> <DEDENT> elif line: <NEW_LINE> <INDENT> if is_finished: <NEW_LINE> <INDENT> raise IOError("All input files should have same number of lines. " "LINE %d is present in file %s, but not in all input files\n" % (line_num, infiles[i].name)) <NEW_LINE> <DEDENT> if is_comment: <NEW_LINE> <INDENT> raise IOError("Comment and header lines should be consistent accross " "all input files. LINE %d is comment or header line in some input files " "but not in file %s" % (line_num, infiles[i].name)) <NEW_LINE> <DEDENT> new_snp = parse_test_snp(line.split(), shuffle=shuffle) <NEW_LINE> if new_snp.is_het(): <NEW_LINE> <INDENT> num_as += np.sum(new_snp.AS_target_ref) + np.sum(new_snp.AS_target_alt) <NEW_LINE> <DEDENT> count_line.append(new_snp.counts) <NEW_LINE> expected_line.append(new_snp.totals) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> is_finished = True <NEW_LINE> <DEDENT> <DEDENT> if not is_finished and not is_comment: <NEW_LINE> <INDENT> if skip_num < skip: <NEW_LINE> <INDENT> skip_num += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if(sum(count_line) >= min_counts and num_as >= min_as_counts): <NEW_LINE> <INDENT> count_matrix.append(count_line) <NEW_LINE> expected_matrix.append(expected_line) <NEW_LINE> <DEDENT> skip_num = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> count_matrix = np.array(count_matrix, dtype=int) <NEW_LINE> expected_matrix = np.array(expected_matrix, dtype=np.float64) <NEW_LINE> sys.stderr.write("count_matrix dimension: %s\n" % str(count_matrix.shape)) <NEW_LINE> sys.stderr.write("expect_matrix dimension: %s\n" % str(expected_matrix.shape)) <NEW_LINE> nrow = count_matrix.shape[0] <NEW_LINE> if (sample > 0) and (sample < count_matrix.shape[0]): <NEW_LINE> <INDENT> sys.stderr.write("randomly sampling %d target regions\n" % sample) <NEW_LINE> samp_index = np.arange(nrow) <NEW_LINE> np.random.shuffle(samp_index) <NEW_LINE> samp_index = samp_index[:sample] <NEW_LINE> count_matrix = count_matrix[samp_index,] <NEW_LINE> expected_matrix = expected_matrix[samp_index,] <NEW_LINE> sys.stderr.write("new count_matrix dimension: %s\n" % str(count_matrix.shape)) <NEW_LINE> sys.stderr.write("new expect_matrix dimension: %s\n" % str(expected_matrix.shape)) <NEW_LINE> <DEDENT> return count_matrix, expected_matrix
Given an input file that contains paths to input files for all individuals, and returns matrix of observed read counts, and matrix of expected read counts
625941bc07f4c71912b11370
def generate_index_map(nonzero_locs, shape): <NEW_LINE> <INDENT> r <NEW_LINE> logger.info('creating index map of non-zero values...') <NEW_LINE> x_c = sp.unravel_index(nonzero_locs, shape)[0].astype(sp.int16) <NEW_LINE> y_c = sp.unravel_index(nonzero_locs, shape)[1].astype(sp.int16) <NEW_LINE> z_c = sp.unravel_index(nonzero_locs, shape)[2].astype(sp.int16) <NEW_LINE> index_map = sp.stack((x_c, y_c, z_c), axis=1) <NEW_LINE> return index_map
Determines the i,j,k indicies of the flattened array
625941bc92d797404e304073
def __init__(self, node_or_str, children=None): <NEW_LINE> <INDENT> if children is None: return <NEW_LINE> list.__init__(self, children) <NEW_LINE> self.node = node_or_str
Construct a new tree. This constructor can be called in one of two ways: - C{Tree(node, children)} constructs a new tree with the specified node value and list of children. - C{Tree(s)} constructs a new tree by parsing the string C{s}. It is equivalent to calling the class method C{Tree.parse(s)}.
625941bcb545ff76a8913d07
@task.route('/polling/<id_>') <NEW_LINE> def polling_task(id_): <NEW_LINE> <INDENT> ws = request.environ.get('wsgi.websocket') <NEW_LINE> if not ws: <NEW_LINE> <INDENT> abort(400, "Expected WebSocket request") <NEW_LINE> <DEDENT> task = task_storage.storage.get_task(id_) <NEW_LINE> _send_task(ws, task) <NEW_LINE> while task and task.state != TaskState.DONE and task.state != TaskState.ERROR: <NEW_LINE> <INDENT> task_coroute = task_storage.storage.subscribe_task_change(id_) <NEW_LINE> task_coroute = asyncio.wait_for(task_coroute, 5) <NEW_LINE> try: <NEW_LINE> <INDENT> task = asyncio.run(task_coroute) <NEW_LINE> <DEDENT> except asyncio.TimeoutError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if task: <NEW_LINE> <INDENT> _send_task(ws, task) <NEW_LINE> <DEDENT> <DEDENT> return ('', 204)
Polling task changes until reach final state Use websocket connection to transfer task changes. End connection when the task is reach final state, e.g. DONE, ERROR. End connection immediately without send anydata if cannot get the task of specific id.
625941bc5fdd1c0f98dc011b
def less_verbose(loggers=None, level=None): <NEW_LINE> <INDENT> loggers = ["cwltool", "rdflib.term", "salad", "requests", "urllib3"] if loggers is None else loggers <NEW_LINE> level = "FATAL" if level is None else level <NEW_LINE> for logger_name in loggers: <NEW_LINE> <INDENT> logger = logging.getLogger(logger_name) <NEW_LINE> logger.setLevel(level)
For a list of loggers sets desired level
625941bca4f1c619b28aff29
def end_job(self, nzo): <NEW_LINE> <INDENT> if self.actives(grabs=False) < 2 and cfg.autodisconnect(): <NEW_LINE> <INDENT> if sabnzbd.downloader.Downloader.do: <NEW_LINE> <INDENT> sabnzbd.downloader.Downloader.do.disconnect() <NEW_LINE> <DEDENT> <DEDENT> if not nzo.deleted: <NEW_LINE> <INDENT> nzo.deleted = True <NEW_LINE> if nzo.precheck: <NEW_LINE> <INDENT> nzo.save_attribs() <NEW_LINE> enough, ratio = nzo.check_quality() <NEW_LINE> if enough: <NEW_LINE> <INDENT> workdir = nzo.downpath <NEW_LINE> self.cleanup_nzo(nzo, keep_basic=True) <NEW_LINE> self.send_back(nzo) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> Assembler.do.process((nzo, None))
Send NZO to the post-processing queue
625941bc1d351010ab855a06
def do_check(self, arg): <NEW_LINE> <INDENT> if arg: <NEW_LINE> <INDENT> self.check_mode = boolean(arg, strict=False) <NEW_LINE> display.v("check mode changed to %s" % self.check_mode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> display.display("Please specify check mode value, e.g. `check yes`")
Toggle whether plays run with check mode
625941bc07d97122c417876f
def test_tour_view_can_delete_booking(self): <NEW_LINE> <INDENT> response = self.client.delete( reverse('details-booking',kwargs={'pk': self.bookings.id}) ) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Test to assert if API can delete a booking successfully if user is an admin or owner
625941bcfb3f5b602dac357a
def test_snips_component_hermes_connection_default(fs, mocker): <NEW_LINE> <INDENT> config_file = '/etc/snips.toml' <NEW_LINE> fs.create_file(config_file, contents='[snips-common]\n') <NEW_LINE> mocker.patch('hermes_python.hermes.Hermes.connect') <NEW_LINE> mocker.patch('hermes_python.hermes.Hermes.loop_forever') <NEW_LINE> mocker.spy(SimpleHermesComponent, 'initialize') <NEW_LINE> component = SimpleHermesComponent() <NEW_LINE> assert component.snips.mqtt.broker_address == 'localhost:1883' <NEW_LINE> assert component.hermes.mqtt_options.broker_address == component.snips.mqtt.broker_address <NEW_LINE> assert component.hermes.loop_forever.call_count == 1 <NEW_LINE> assert component.initialize.call_count == 1
Test whether a `HermesSnipsComponent` object with the default MQTT connection settings sets up its `Hermes` object correctly.
625941bcbe383301e01b5375
def init_mlp(in_dim, out_dim, hidden_dim, num_layers, non_linearity): <NEW_LINE> <INDENT> dims = [in_dim] + [hidden_dim for _ in range(num_layers)] + [out_dim] <NEW_LINE> return MultilayerPerceptron(dims, nn.Tanh())
Initializes a MultilayerPerceptron. Args: in_dim: int out_dim: int hidden_dim: int num_layers: int non_linearity: differentiable function Returns: a MultilayerPerceptron with the architecture x -> Linear(in_dim, hidden_dim) -> non_linearity -> ... Linear(hidden_dim, hidden_dim) -> non_linearity -> Linear(hidden_dim, out_dim) -> y where num_layers = 0 corresponds to x -> Linear(in_dim, out_dim) -> y
625941bc16aa5153ce362362
def pfa_polar_coords(self, Position, SCP, times): <NEW_LINE> <INDENT> def project_to_image_plane(points): <NEW_LINE> <INDENT> offset = (SCP - points).dot(ipn)/fpn.dot(ipn) <NEW_LINE> if offset.ndim == 0: <NEW_LINE> <INDENT> return points + offset*fpn <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return points + numpy.outer(offset, fpn) <NEW_LINE> <DEDENT> <DEDENT> if self.IPN is None or self.FPN is None: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> ipn = self.IPN.get_array(dtype='float64') <NEW_LINE> fpn = self.FPN.get_array(dtype='float64') <NEW_LINE> if isinstance(times, (float, int)) or times.ndim == 0: <NEW_LINE> <INDENT> o_shape = None <NEW_LINE> times = numpy.array([times, ], dtype='float64') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> o_shape = times.shape <NEW_LINE> times = numpy.reshape(times, (-1, )) <NEW_LINE> <DEDENT> positions = Position.ARPPoly(times) <NEW_LINE> reference_position = Position.ARPPoly(self.PolarAngRefTime) <NEW_LINE> image_plane_positions = project_to_image_plane(positions) <NEW_LINE> image_plane_coa = project_to_image_plane(reference_position) <NEW_LINE> ip_x = image_plane_coa - SCP <NEW_LINE> ip_x /= numpy.linalg.norm(ip_x) <NEW_LINE> ip_y = numpy.cross(ip_x, ipn) <NEW_LINE> ip_range = image_plane_positions - SCP <NEW_LINE> ip_range /= numpy.linalg.norm(ip_range, axis=1)[:, numpy.newaxis] <NEW_LINE> k_a = -numpy.arctan2(ip_range.dot(ip_y), ip_range.dot(ip_x)) <NEW_LINE> range_vectors = positions - SCP <NEW_LINE> range_vectors /= numpy.linalg.norm(range_vectors, axis=1)[:, numpy.newaxis] <NEW_LINE> sin_graze = range_vectors.dot(fpn) <NEW_LINE> sin_graze_ip = ip_range.dot(fpn) <NEW_LINE> k_sf = numpy.sqrt((1 - sin_graze*sin_graze)/(1 - sin_graze_ip*sin_graze_ip)) <NEW_LINE> if o_shape is None: <NEW_LINE> <INDENT> return k_a[0], k_sf[0] <NEW_LINE> <DEDENT> elif len(o_shape) > 1: <NEW_LINE> <INDENT> return numpy.reshape(k_a, o_shape), numpy.reshape(k_sf, o_shape) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return k_a, k_sf
Calculate the PFA parameters necessary for mapping phase history to polar coordinates. Parameters ---------- Position : sarpy.io.complex.sicd_elements.Position.PositionType SCP : numpy.ndarray times : numpy.ndarray|float|int Returns ------- (numpy.ndarray, numpy.ndarray)|(float, float) `(k_a, k_sf)`, where `k_a` is polar angle, and `k_sf` is spatial frequency scale factor. The shape of the output array (or scalar) will match the shape of the `times` array (or scalar).
625941bc2c8b7c6e89b356ac
def test_get_angle(): <NEW_LINE> <INDENT> node0 = Node(x=0, y=0, label="node0") <NEW_LINE> node1 = Node(x=1, y=0, label="node1") <NEW_LINE> node2 = Node(x=1, y=1, label="node2") <NEW_LINE> assert node0._get_angle(node1) == deg2rad(0) <NEW_LINE> assert node0._get_angle(node2) == deg2rad(45) <NEW_LINE> assert node1._get_angle(node0) == deg2rad(180) <NEW_LINE> assert node2._get_angle(node0) == deg2rad(180 + 45)
test that we can measure angles between nodes
625941bcd4950a0f3b08c23b
def get_llvm_str(self): <NEW_LINE> <INDENT> self._sentry_cache_disable_inspection() <NEW_LINE> return str(self._final_module)
Get the human-readable form of the LLVM module.
625941bc4e696a04525c9336
def set_TopicArn(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'TopicArn', value)
Set the value of the TopicArn input for this Choreo. ((required, string) The ARN of the topic that has an access control policy you want to adjust.)
625941bcf7d966606f6a9eeb
def __hash__(self): <NEW_LINE> <INDENT> return hash((self.position, self.direction, self.molecule is None, self.is_rotating, tuple(self.flipflop_states.values())))
A waldo's run state is uniquely identified by its position, direction, whether it's holding a molecule, whether it's rotating, and its flip-flop states.
625941bcbaa26c4b54cb100c
def filtrado(): <NEW_LINE> <INDENT> archivo = open('mbox-corto.txt') <NEW_LINE> contar = 0 <NEW_LINE> for linea in archivo: <NEW_LINE> <INDENT> palabras = linea.split() <NEW_LINE> if len(palabras) == 0: continue <NEW_LINE> if palabras[0] != 'From': continue <NEW_LINE> contar += 1 <NEW_LINE> print(palabras[2]) <NEW_LINE> <DEDENT> print('En total', contar,'ocurrencias')
En este ejercicio se trata de filtrar el día en que fue enviado un correo. Para ello, cada línea del archivo con la información se divide en palabras, donde se busca solo las líneas que empiezen por 'From' (descartando el resto): if palabras[0] != 'From': continue y, de esas líneas, extraemos la palabra con índice 2 que es la que contiene el día de la semana en que se envió. Por ejemplo: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 si usamos el método split() en esa línea obtenemos la lista: ['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008'] donde el elemento con índice 2 corresponde a Sat. Además se ignoran las líneas en blanco mediante: if len(palabras) == 0: continue
625941bc73bcbd0ca4b2bf67
def libvlc_vlm_pause_media(p_instance, psz_name): <NEW_LINE> <INDENT> f = _Cfunctions.get('libvlc_vlm_pause_media', None) or _Cfunction('libvlc_vlm_pause_media', ((1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p) <NEW_LINE> if not __debug__: <NEW_LINE> <INDENT> global libvlc_vlm_pause_media <NEW_LINE> libvlc_vlm_pause_media = f <NEW_LINE> <DEDENT> return f(p_instance, psz_name)
Pause the named broadcast. @param p_instance: the instance. @param psz_name: the name of the broadcast. @return: 0 on success, -1 on error.
625941bc6fece00bbac2d626
def vn_encode(): <NEW_LINE> <INDENT> return MessageEncode("06vn00", "VN")
zd: Get panel software version information.
625941bca8370b771705278b
def test_version_is_locked_for_draft(self): <NEW_LINE> <INDENT> draft_version = factories.PollVersionFactory(state=constants.DRAFT) <NEW_LINE> self.assertTrue(hasattr(draft_version, 'versionlock'))
A version lock is present when a content version is in a draft state
625941bc4527f215b584c344
def ordenar(muestras, columna): <NEW_LINE> <INDENT> matriz = muestras[0] <NEW_LINE> etiquetas = muestras[1] <NEW_LINE> columna = [columna] <NEW_LINE> orden = np.lexsort(matriz.T[columna]) <NEW_LINE> return matriz[orden], etiquetas[orden]
Ordena de menor a mayor los elementos de la matriz según los valores de una sola columna . :param muestras: Tupla donde: ♣ [0] = Matriz N x M con valores númericos ♣ [1] = Vector tamaño N con las etiquetas de cada N_i de la matriz :param columna: Indíce de la columna :return: La misma matriz y etiquetas de entrada pero ordenados Ejemplo: >>> matriz = np.array([[ 1, 10, 3], ... [ 34, 56, 43], ... [123, 9, 120]]) >>> etiquetas = np.array(['ETIQ_1', ... 'ETIQ_2', ... 'ETIQ_3']) >>> matriz, etiquetas = ordenar((matriz, etiquetas), columna=1) >>> matriz array([[123, 9, 120], [ 1, 10, 3], [ 34, 56, 43]]) >>> etiquetas array(['ETIQ_3', 'ETIQ_1', 'ETIQ_2'], dtype='<U6')
625941bc96565a6dacc8f5b6
def map_equipment_load(self, load_info: LegacyLoadInfo) -> pe_commands.Command: <NEW_LINE> <INDENT> if isinstance(load_info, LegacyLabwareLoadInfo): <NEW_LINE> <INDENT> return self._map_labware_load(load_info) <NEW_LINE> <DEDENT> elif isinstance(load_info, LegacyInstrumentLoadInfo): <NEW_LINE> <INDENT> return self._map_instrument_load(load_info) <NEW_LINE> <DEDENT> elif isinstance(load_info, LegacyModuleLoadInfo): <NEW_LINE> <INDENT> return self._map_module_load(load_info)
Map a labware, instrument (pipette), or module load to a PE command.
625941bce5267d203edcdb8a
def _print_welcome(self): <NEW_LINE> <INDENT> cfg = self.config['SAL'] <NEW_LINE> persistence = cfg['PERSISTENCE'] <NEW_LINE> authentication = cfg['AUTHENTICATION'] <NEW_LINE> authorisation = cfg['AUTHORISATION'] <NEW_LINE> admin_enabled = cfg['ADMIN_USER_ENABLED'] <NEW_LINE> s = '\nSimple Access Layer (SAL) Server v{}\n' '{}\n\n' 'Configuration:\n' ' * API version: {}\n' ' * Persistence handler: {}\n' ' * Authentication handler: {}\n' ' * Authorisation handler: {}\n' ' * Administration user account: {}{}\n' <NEW_LINE> underline = '-' * (34 + len(RELEASE_VERSION)) <NEW_LINE> persistence_name = '{} (v{})'.format(persistence.NAME, persistence.VERSION) <NEW_LINE> if authentication: <NEW_LINE> <INDENT> authentication_name = '{} (v{})'.format(authentication.NAME, authentication.VERSION) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> authentication_name = 'None' <NEW_LINE> <DEDENT> if authorisation: <NEW_LINE> <INDENT> authorisation_name = '{} (v{})'.format(authorisation.NAME, authorisation.VERSION) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> authorisation_name = 'None' <NEW_LINE> <DEDENT> if admin_enabled: <NEW_LINE> <INDENT> admin_user_state = 'Enabled' <NEW_LINE> admin_user_warn = ' - WARNING!' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> admin_user_state = 'Disabled' <NEW_LINE> admin_user_warn = '' <NEW_LINE> <DEDENT> print(s.format( RELEASE_VERSION, underline, API_VERSION, persistence_name, authentication_name, authorisation_name, admin_user_state, admin_user_warn ))
Displays the server welcome text.
625941bc0a366e3fb873e701
def addSaveEntry(self, title, row=None, column=0, colspan=0, rowspan=0): <NEW_LINE> <INDENT> return self._entryMaker(title, row, column, colspan, rowspan, secret=False, label=False, kind="save")
adds an entry box with a button, that pops-up a save dialog
625941bc627d3e7fe0d68d38
def __init__(self, histograms, selection, **kwargs): <NEW_LINE> <INDENT> options = { 'nCols': 2, 'tooltips': 'pan,box_zoom, wheel_zoom,box_select,lasso_select,reset', 'y_axis_type': 'auto', 'x_axis_type': 'auto', 'plot_width': 400, 'plot_height': 400, 'bg_color': '#fafafa', 'color': "navy", 'line_color': "white" } <NEW_LINE> options.update(kwargs) <NEW_LINE> self.selectionList = parseWidgetString(selection) <NEW_LINE> self.histArray = histograms <NEW_LINE> self.sliderList = [] <NEW_LINE> self.sliderNames = [] <NEW_LINE> self.initSlider("") <NEW_LINE> WidgetBox = widgets.VBox(self.sliderList) <NEW_LINE> self.figure, self.handle, self.source = self.drawGraph(**options) <NEW_LINE> self.updateInteractive("") <NEW_LINE> display(WidgetBox)
:param histograms: TObjArray consists of multidimensional TTree's ( THnT ) for detailed info check: https://root.cern.ch/doc/master/classTObjArray.html https://root.cern.ch/doc/master/classTHnT.html :param selection: String, list of the histograms to draw. Separated by commas (,) Dimensions to draw must be included inside of parenthesis' as an integer. Ex: "hisdZ(3),hisdZ(0),hisPullZHM1(3),hisPullZCL(1)" :param options: -nCols :the number of columns -tooltips :tooltips to show -plot_width :the width of each plot -plot_height :the height of each plot -bg_color :Background color -color :Histogram color -line_color :Line color
625941bc187af65679ca5008
def test_verifyCryptedPassword(self): <NEW_LINE> <INDENT> password = "secret string" <NEW_LINE> salt = "salty" <NEW_LINE> crypted = crypt.crypt(password, salt) <NEW_LINE> self.assertTrue( checkers.verifyCryptedPassword(crypted, password), "{!r} supposed to be valid encrypted password for {!r}".format( crypted, password ), )
L{verifyCryptedPassword} returns C{True} if the plaintext password passed to it matches the encrypted password passed to it.
625941bc63b5f9789fde6fcf
def assertItemMethods(self, methods_self, methods_collection, **context): <NEW_LINE> <INDENT> with self._init_context(**context): <NEW_LINE> <INDENT> data_self = { '_id': 'item_id', '_links': {'self': {}} } <NEW_LINE> add_methods_to_item_links('fake', data_self) <NEW_LINE> self.assertItemsEqual(data_self['_links']['self']['methods'], methods_self) <NEW_LINE> data_all = { '_id': 'item_id', '_links': {'self': {}, 'parent': {}, 'collection': {}} } <NEW_LINE> add_methods_to_item_links('fake', data_all) <NEW_LINE> self.assertItemsEqual(data_all['_links']['self']['methods'], methods_self) <NEW_LINE> self.assertItemsEqual(data_all['_links']['collection']['methods'], methods_collection) <NEW_LINE> self.assertItemsEqual(data_all['_links']['parent']['methods'], self.home_methods)
Init context, add methods and compare all required results. First test the variant that only a self link exists (POST, PATCH) Then the variant with self, collection and parent links (GET) Use a default item with id 'item_id'. Home endpoint methods are always the same. (Only read.)
625941bc4f6381625f114927
def set_ResponseType(self, value): <NEW_LINE> <INDENT> super(DailyUVByCityInputSet, self)._set_input('ResponseType', value)
Set the value of the ResponseType input for this Choreo. ((optional, string) Results can be retrieved in either JSON or XML. Defaults to XML.)
625941bcab23a570cc25006a
def test_nonexistent_lob(self): <NEW_LINE> <INDENT> obj = self._add_llvmbuild_object() <NEW_LINE> with self.assertRaises(Exception): <NEW_LINE> <INDENT> obj.get_lob_path("oops") <NEW_LINE> <DEDENT> with self.assertRaises(Exception): <NEW_LINE> <INDENT> obj.save_lob("oops", "llvm_build_cant_handle_oops_lobs") <NEW_LINE> <DEDENT> with self.assertRaises(Exception): <NEW_LINE> <INDENT> obj.get_lob("oops", "llvm_build_cant_handle_oops_lobs") <NEW_LINE> <DEDENT> with self.assertRaises(Exception): <NEW_LINE> <INDENT> obj.del_lob("oops", "llvm_build_cant_handle_oops_lobs") <NEW_LINE> <DEDENT> self.assertEqual(obj.get_lob("result"), None)
Test if nonexistent lobs are handled correctly.
625941bcaad79263cf390927
def column2number(self, a): <NEW_LINE> <INDENT> seq = self[a] <NEW_LINE> indexmap = {} <NEW_LINE> j = 0 <NEW_LINE> for i in range(len(seq)): <NEW_LINE> <INDENT> if seq.sequence[i] == Alignment.gap: continue <NEW_LINE> indexmap[i] = j <NEW_LINE> j +=1 <NEW_LINE> <DEDENT> return indexmap
Maps alignment columns to sequence number for non-gap residues.
625941bc7cff6e4e81117870