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=i... | 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 ... | 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(S... | 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> ... | 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_qnode... | 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> c... | :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/stat... | 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> <... | 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 co... | 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... | 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... | 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) ... | 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_LIN... | 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 ele... | 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_LI... | 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> s... | 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.as... | 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'] == 'vp... | 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> <INDEN... | 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... | 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> els... | 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 ... | 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... | 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> ar... | 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... | 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_m... | 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 & 0x... | 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... | 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.rea... | 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: <NE... | 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> <INDE... | 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_t... | 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], f... | 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... | #==========================================================================
# @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.statu... | 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> el... | 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> <DED... | 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> <... | 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> ... | 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): wheth... | 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_LIN... | 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_... | 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> w... | 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(no... | 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... | 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) <... | 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_L... | 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_... | 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... | 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.o... | 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` ... | 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_... | 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... | 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 ... | 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>... | 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 en... | 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... | 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{}... | 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... | :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: ... | 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']['sel... | 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>... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.