code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_comic_by_id(comic_id): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> if comic_id is None: <NEW_LINE> <INDENT> return {'comic': None} <NEW_LINE> <DEDENT> if not isinstance(comic_id, int): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> comic_id = int(comic_id) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> lo...
Get comic by ID if it exists
625941ca6aa9bd52df036e4c
def UploadFileFTP(file_path_name, server_ip, remote_path, username, password): <NEW_LINE> <INDENT> filepath = getFileDir(file_path_name) <NEW_LINE> filename = getBaseName(file_path_name) <NEW_LINE> import ftplib <NEW_LINE> import os <NEW_LINE> import sys <NEW_LINE> print("POPUP: <p>Connecting to <strong>%s</strong> usi...
Upload a file to a robot through FTP
625941ca8c3a873295158463
@manager.command <NEW_LINE> def register(): <NEW_LINE> <INDENT> call('python %s register' % p.join(_basedir, 'setup.py'), shell=True)
Register package with PyPI
625941ca26238365f5f0ef16
def get(self, key): <NEW_LINE> <INDENT> for item in self.store: <NEW_LINE> <INDENT> if item[0] == key: <NEW_LINE> <INDENT> result = item <NEW_LINE> return result[1] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return -1
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key :type key: int :rtype: int
625941ca5fdd1c0f98dc02db
@app.callback(Output('total-coffees', 'children'), [Input('timestamp-slider', 'value')]) <NEW_LINE> def update_info(value): <NEW_LINE> <INDENT> global df <NEW_LINE> tc = sum(df.coffees.iloc[value[0]: value[-1]]) <NEW_LINE> return 'no of coffees in range: {}'.format(tc)
For user selections, return the relevant range
625941ca63d6d428bbe44598
def resolve(self, request): <NEW_LINE> <INDENT> path = request['PATH_INFO'] or "/" <NEW_LINE> for regex in self.routes.keys(): <NEW_LINE> <INDENT> reg = regex.match(path) <NEW_LINE> import ipdb; ipdb.set_trace() <NEW_LINE> if reg: <NEW_LINE> <INDENT> return self.routes[regex]
Yield view for request path :param request:
625941ca1b99ca400220ab5a
def allow_icmp(zone, icmp): <NEW_LINE> <INDENT> if icmp not in get_icmp_types(): <NEW_LINE> <INDENT> log.error('Invalid ICMP type') <NEW_LINE> return False <NEW_LINE> <DEDENT> if icmp not in list_icmp_block(zone): <NEW_LINE> <INDENT> log.info('ICMP Type is already permitted') <NEW_LINE> return 'success' <NEW_LINE> <DED...
Allow a specific ICMP type on a zone .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.allow_icmp zone echo-reply
625941ca925a0f43d2549f1f
def add_pre_run_connection_holder(self, pre_run_connection_holder): <NEW_LINE> <INDENT> self.__pre_run_connection_holders.append(pre_run_connection_holder)
Add a connection holder that will be filled in before run :param ConnectionHolder pre_run_connection_holder: The connection holder to be added
625941ca31939e2706e4cf14
def p_phrase(self, p): <NEW_LINE> <INDENT> pass
phrase : allExpression SEMICOLON | SEMICOLON
625941caa4f1c619b28b00e3
def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): <NEW_LINE> <INDENT> def export_as_csv(modeladmin, request, queryset): <NEW_LINE> <INDENT> opts = modeladmin.model._meta <NEW_LINE> field_names = [field.name for field in opts.fields] if not fields else f...
This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row.
625941ca3346ee7daa2b2e13
def generate_input_array(self, inputs) : <NEW_LINE> <INDENT> X = np.array([self.x0] + inputs[0]) <NEW_LINE> for a in range(1, len(inputs)) : <NEW_LINE> <INDENT> X = np.vstack((X, [self.x0] + inputs[a])) <NEW_LINE> <DEDENT> X.shape = (len(inputs), len(inputs[0]) + 1) <NEW_LINE> return X
"Creates and returns a NumPy array containing the x0 and the inputs
625941cad10714528d5ffd8b
def theme_input_text_color(color=None): <NEW_LINE> <INDENT> if color is not None: <NEW_LINE> <INDENT> set_options(input_text_color=color) <NEW_LINE> <DEDENT> return DEFAULT_INPUT_TEXT_COLOR
Sets/Returns the input element entry color (not the text but the thing that's displaying the text) :return: (str) - color string of the input element color currently in use :rtype: (str)
625941caab23a570cc25022b
def defaultRights(self): <NEW_LINE> <INDENT> mdtool = getToolByName(self, 'portal_metadata', None) <NEW_LINE> if mdtool is None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> for sid, schema in mdtool.listSchemas(): <NEW_LINE> <INDENT> for pid, policy in schema.listPolicies(typ=self.Type()): <NEW_LINE> <INDENT> if ...
Retrieve the default rights
625941ca2c8b7c6e89b3586a
def hpi_benchmark(): <NEW_LINE> <INDENT> df = ql.get('FMAC/HPI_USA', authtoken=api_key) <NEW_LINE> df.rename(columns={'Value': 'United States'}, inplace=True) <NEW_LINE> df['United States'] = (df['United States'] - df['United States'][0]) / df['United States'][0] * 100.0 <NEW_LINE> return df
Get a benchmark
625941ca7b25080760e39502
def evalf(self, prec=None, **options): <NEW_LINE> <INDENT> coords = [x.evalf(prec, **options) for x in self.args] <NEW_LINE> return Point3D(*coords, evaluate=False)
Evaluate the coordinates of the point. This method will, where possible, create and return a new Point where the coordinates are evaluated as floating point numbers to the precision indicated (default=15). Returns ======= point : Point Examples ======== >>> from sympy import Point3D, Rational >>> p1 = Point3D(Rati...
625941ca4f6381625f114ae3
def copy_urls(db, original_obj, clean_obj): <NEW_LINE> <INDENT> for url in original_obj.get_url_list(): <NEW_LINE> <INDENT> if url and not url.get_privacy(): <NEW_LINE> <INDENT> clean_obj.add_url(url)
Copies urls from one object to another - excluding references to private urls. :param db: Gramps database to which the references belongs :type db: DbBase :param original_obj: Object that may have urls :type original_obj: UrlBase :param clean_obj: Object that will have only non-private urls :type original_obj: UrlBase...
625941caf7d966606f6aa0ac
@app.route("/buy", methods=["GET", "POST"]) <NEW_LINE> @login_required <NEW_LINE> def buy(): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> quote = lookup(request.form.get("symbol")) <NEW_LINE> if quote == None: <NEW_LINE> <INDENT> return apology("invalid symbol") <NEW_LINE> <DEDENT> try: <NEW_LIN...
Buy shares of stock
625941ca3d592f4c4ed1d118
def _parse_get_string(string_vlaue: str): <NEW_LINE> <INDENT> raw_str = string_vlaue.strip() <NEW_LINE> if raw_str.startswith(("'",'"')) and raw_str.endswith(("'",'"')): <NEW_LINE> <INDENT> raw_str = raw_str[1:-1] <NEW_LINE> <DEDENT> return raw_str
Remove the surronding quotes of the string
625941ca0c0af96317bb8291
def nat(self, nictype, macaddr=None): <NEW_LINE> <INDENT> index = self.network_index() + 1 <NEW_LINE> nic = { "nic%d" % index: "nat", "nictype%d" % index: nictype, "nicpromisc%d" % index: "allow-all", } <NEW_LINE> _call("modifyvm", self.name, **nic) <NEW_LINE> return self.modify_mac(macaddr, index)
Configure NAT for the Virtual Machine.
625941caeab8aa0e5d26dc00
def __del__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> unbind(self.widget, self.sequence, self.call_id) <NEW_LINE> unbind(self.widget, self.DESTROY, self.del_id) <NEW_LINE> <DEDENT> except (tk.TclError, AttributeError): <NEW_LINE> <INDENT> pass
clean up bindings here
625941ca6aa9bd52df036e4d
def is_initialized(self, handle=None): <NEW_LINE> <INDENT> if handle is None: <NEW_LINE> <INDENT> if not hasattr(self, "handle"): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> handle = self.handle <NEW_LINE> <DEDENT> <DEDENT> self.out("Setting camera with handle %r as current:" % handle...
Return True if the handle is already initialized, else False. If no handle provided, check if the instance has a handle yet. If so, return True, else return False.
625941ca9f2886367277a936
def get_interface_mac(self, device, interface): <NEW_LINE> <INDENT> out = device.adb.shell("ifconfig %s" % interface) <NEW_LINE> completed = out.decode('utf-8').strip() <NEW_LINE> res = re.match(".* HWaddr (\S+).*", completed, re.S) <NEW_LINE> asserts.assert_true(res, 'Unable to obtain MAC address for interface %s' % i...
Get the HW MAC address of the specified interface. Returns the HW MAC address or raises an exception on failure. Args: device: The 'AndroidDevice' on which to query the interface. interface: The name of the interface to query. Returns: mac: MAC address of the interface.
625941ca96565a6dacc8f774
def get_sth_consistency(self, old_size, new_size): <NEW_LINE> <INDENT> if old_size > new_size: <NEW_LINE> <INDENT> raise InvalidRequestError( "old > new: %s >= %s" % (old_size, new_size)) <NEW_LINE> <DEDENT> if old_size < 0 or new_size < 0: <NEW_LINE> <INDENT> raise InvalidRequestError( "both sizes must be >= 0: %s, %s...
Retrieve a consistency proof. Args: old_size : size of older tree. new_size : size of newer tree. Returns: list of raw hashes (bytes) forming the consistency proof Raises: HTTPError, HTTPClientError, HTTPServerError: connection failed, or returned an error. HTTPClientError can happen when ...
625941ca01c39578d7e74ee4
def best_match(tf_data_list,freq_range=None,set_ref=0,ch_ref=0): <NEW_LINE> <INDENT> if tf_data_list.__class__.__name__ != 'TfDataList': <NEW_LINE> <INDENT> raise ValueError('Input data needs to be single <TfData> object') <NEW_LINE> <DEDENT> if freq_range == None: <NEW_LINE> <INDENT> freq_range_copy = tf_data_list[set...
Args: tf_data (<TfData> object): transfer function data freq_range: 2x1 numpy array to specify data segment to use
625941ca7d43ff24873a2d49
def get_columns(self, data, no_cols): <NEW_LINE> <INDENT> cols = [None] * no_cols <NEW_LINE> for key in data: <NEW_LINE> <INDENT> if key.startswith('col_select'): <NEW_LINE> <INDENT> if data[key] != 'None': <NEW_LINE> <INDENT> cols[int(key.split('_')[-1])] = data[key] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return cols
Run through the POST data to get all the column data. :param data: dict, request.POST data. :param no_cols: int, number of columns in table. :return: lst, lst of special columns.
625941ca462c4b4f79d1d77a
def calculate_distance(checkpoint_a, checkpoint_b): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lat1 = radians(float(checkpoint_a['lat'])) <NEW_LINE> lon1 = radians(float(checkpoint_a['lon'])) <NEW_LINE> lat2 = radians(float(checkpoint_b['lat'])) <NEW_LINE> lon2 = radians(float(checkpoint_b['lon'])) <NEW_LINE> <DEDENT...
Laskee kahden rastin välisen etäisyyden
625941ca004d5f362079a3dc
def data_encrypt(data): <NEW_LINE> <INDENT> if not isinstance(data, str): <NEW_LINE> <INDENT> data = str(data) <NEW_LINE> <DEDENT> ciphertext = Vault().process_bind_param(data, TEXT()) <NEW_LINE> return ciphertext.decode("utf8")
takes an input and returns a base64 encoded encryption reusing the Vault DB encryption module :param data: string :return: base64 ciphertext
625941cab7558d58953c4fbe
def get_image_path(self, name): <NEW_LINE> <INDENT> return self.get_path(name)
Overloadable method to compute the path to an image file. By overloading this, you can insert subdirs, etc.
625941ca30bbd722463cbe6f
def to_pixel(self, coords, asint=False): <NEW_LINE> <INDENT> if asint: <NEW_LINE> <INDENT> return np.asarray(to_2d_coords(coords), dtype=np.int32, order='C') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.asarray(to_2d_coords(coords), order='C')
returns the same (lon, lat) coords, but as an np.array, if they aren't already :param coords: The coords to project :type coords: Nx3 numpy array or compatible sequence (lon, lat, depth) :param asint: Flag to set whether to convert to a integer or not default is to leave it as the same type it came in, ...
625941ca32920d7e50b28279
def __init__(self, username=None, api_key=None, container=None, connection_kwargs=None, container_uri=None): <NEW_LINE> <INDENT> if username is not None: <NEW_LINE> <INDENT> self.username = username <NEW_LINE> <DEDENT> if api_key is not None: <NEW_LINE> <INDENT> self.api_key = api_key <NEW_LINE> <DEDENT> if container i...
Initializes the settings for the connection and container.
625941ca627d3e7fe0d68ef9
def sum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): <NEW_LINE> <INDENT> footprint = __make_footprint(input, size, footprint) <NEW_LINE> slicer = [slice(None, None, -1)] * footprint.ndim <NEW_LINE> return convolve(input, footprint[slicer], output, mode, cval, origin)
Calculates a multi-dimensional sum filter. Parameters ---------- input : array-like input array to filter size : scalar or tuple, optional See footprint, below footprint : array, optional Either `size` or `footprint` must be defined. `size` gives the shape that is taken from the input array, at every e...
625941cad4950a0f3b08c3f9
def divide_deck_into_hands(self, number_of_players: int) -> List[List[Card]]: <NEW_LINE> <INDENT> hand_list = [] <NEW_LINE> starting_index = 0 <NEW_LINE> while starting_index < 4: <NEW_LINE> <INDENT> hand_list.append(self.deck[starting_index::number_of_players]) <NEW_LINE> starting_index += 1 <NEW_LINE> <DEDENT> return...
Deals hands from the deck given the number of players
625941cabaa26c4b54cb11c9
def updateHand(hand, word): <NEW_LINE> <INDENT> uHand = dict(hand) <NEW_LINE> for let in word: <NEW_LINE> <INDENT> if let in uHand: <NEW_LINE> <INDENT> uHand[let] = uHand[let] - 1 <NEW_LINE> <DEDENT> <DEDENT> return uHand
Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does ...
625941ca56b00c62f0f14702
def _configure_optimizer(self, learning_rate): <NEW_LINE> <INDENT> if self.optimizer == 'adadelta': <NEW_LINE> <INDENT> optimizer = tf.train.AdadeltaOptimizer( learning_rate, rho=self.adadelta_rho, epsilon=self.opt_epsilon) <NEW_LINE> <DEDENT> elif self.optimizer == 'adagrad': <NEW_LINE> <INDENT> optimizer = tf.train.A...
Configures the optimizer used for training. Args: learning_rate: A scalar or `Tensor` learning rate. Returns: An instance of an optimizer. Raises: ValueError: if FLAGS.optimizer is not recognized.
625941ca92d797404e304233
@task <NEW_LINE> def clear(): <NEW_LINE> <INDENT> local("find . -name '~*' -or -name '*.pyo' -or -name '*.pyc' " "-or -name 'Thubms.db' | xargs -I {} rm -v '{}'")
Delete unnecessary and cached files
625941ca60cbc95b062c65ec
def build_parser(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) <NEW_LINE> parser.add_argument("--test_gct_path", "-t", required=True, help="path to input gct file") <NEW_LINE> parser.add_argument("--bg_gct_path", "-b", required=True,...
Build argument parser.
625941ca50812a4eaa59c3cc
def set_http_proxy(): <NEW_LINE> <INDENT> juju_environment = env_proxy_settings() <NEW_LINE> if juju_environment and not juju_environment.get('disable-juju-proxy'): <NEW_LINE> <INDENT> upper = ['HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY'] <NEW_LINE> lower = list(map(str.lower, upper)) <NEW_LINE> keys = upper + lower <NEW_L...
Check if we have any values for juju_http*_proxy and apply them.
625941cab7558d58953c4fbf
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 9 <NEW_LINE> (_x.cmd, _x.velocity, _x.timeout,) = _struct_B2f.unpack(str[start:end]) <NEW_LINE> return self <NEW_LINE> <DEDENT> except struct.error as e: <NEW_LINE>...
unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module
625941ca57b8e32f52483544
def le(a, b, rel_tol=1e-09, abs_tol=0.0): <NEW_LINE> <INDENT> return not gt(a, b, rel_tol=rel_tol, abs_tol=abs_tol)
Test `a`(-ish) <= `b`(-ish) Arguments: a {float} -- value b {float} -- another value Keyword Arguments: rel_tol {float} -- relative tolerance (default: {1e-09}) abs_tol {float} -- absolute tolerance (default: {0.0}) Returns: bool -- `a` is less than/similar to `b`
625941ca004d5f362079a3dd
def test_index_url(self): <NEW_LINE> <INDENT> assert reverse("newsletter:index") == "/newsletter/" <NEW_LINE> assert resolve("/newsletter/").view_name == "newsletter:index"
Test newsletter index url
625941caff9c53063f47c29d
def test_export_org_logs(self): <NEW_LINE> <INDENT> pass
Test case for export_org_logs
625941ca3539df3088e2e3f4
def test13_copy_contructor(self): <NEW_LINE> <INDENT> import cppyy <NEW_LINE> four_vector = cppyy.gbl.four_vector <NEW_LINE> t1 = four_vector(1., 2., 3., -4.) <NEW_LINE> t2 = four_vector(0., 0., 0., 0.) <NEW_LINE> t3 = four_vector(t1) <NEW_LINE> assert t1 == t3 <NEW_LINE> assert t1 != t2 <NEW_LINE> for i in range(4): ...
Test copy constructor
625941cad58c6744b4257d0a
def power_new(a, b): <NEW_LINE> <INDENT> result = 1 <NEW_LINE> b_bin = bin(b)[2:] <NEW_LINE> reverse_b_bin = b_bin[::-1] <NEW_LINE> for bit in reverse_b_bin: <NEW_LINE> <INDENT> if int(bit) % 2 == 1: <NEW_LINE> <INDENT> result *= a <NEW_LINE> <DEDENT> a = a*a <NEW_LINE> <DEDENT> return result
computes a**b using iterated squaring
625941cacc0a2c11143dcf3a
def get_points_of_interest(source, dest): <NEW_LINE> <INDENT> src_coord = Coordinates(*get_geocoded_address(source)) <NEW_LINE> dest_coord = Coordinates(*get_geocoded_address(dest)) <NEW_LINE> route_json_result = json.loads(urllib2.urlopen(URL_dir.replace('__SRC__', googlemaps.convert.latlng(src_coord)).replace('__DEST...
Return major points of interest and rest stops between a given source and destination
625941ca8e7ae83300e4b076
def __init__(self, parameters=None, on_open_callback=None): <NEW_LINE> <INDENT> self.callbacks = callback.CallbackManager() <NEW_LINE> if on_open_callback: <NEW_LINE> <INDENT> self.add_on_open_callback(on_open_callback) <NEW_LINE> <DEDENT> self.params = parameters or ConnectionParameters() <NEW_LINE> self._init_connect...
Connection initialization expects a ConnectionParameters object and a callback function to notify when we have successfully connected to the AMQP Broker. :param parameters: Connection parameters :type parameters: pika.connection.ConnectionParameters :param on_open_callback: The method to call when the connection is op...
625941ca8e05c05ec3eea41e
def subtract(operands): <NEW_LINE> <INDENT> if operands: <NEW_LINE> <INDENT> result = get_value(operands[0]) <NEW_LINE> newoperands = operands[1:] <NEW_LINE> for each_operand in newoperands: <NEW_LINE> <INDENT> each_value = get_value(each_operand) <NEW_LINE> if each_value is not None: <NEW_LINE> <INDENT> result -= each...
Compute the difference of the operands specified if they are all numbers. If any operand is not a valid number, the function returns None. :param operands: list of strings :return: (int or float) the sum of the operands specified if all of them are valid numbers or None if an invalid number is encountered.
625941cad10714528d5ffd8c
def last_vertex(self): <NEW_LINE> <INDENT> if len(self.vertices): <NEW_LINE> <INDENT> return self.vertices[-1] <NEW_LINE> <DEDENT> return None
Returns the last vertex id in the path :return: a vertex id if the path is not empty otherwise None
625941caa934411ee375173e
def get_identity(self, id, mid, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = self.get_identity.metadata["url"] <NEW_LINE> path_format_arguments = { "id": self._serialize.url("id", id, "str"), "mid": self._serialize.url("mid", mid, "str"), } <NEW_LINE> url = self._client.format_url(url,...
Gets a module identity on the device. :param id: The unique identifier of the device. :type id: str :param mid: The unique identifier of the module. :type mid: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :pa...
625941ca29b78933be1e5757
def fermat_test(p, nbits): <NEW_LINE> <INDENT> for _ in range(5): <NEW_LINE> <INDENT> a = rand_less_than(p, nbits) <NEW_LINE> if not pow(a, p - 1, p) == 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Fermat primality test
625941ca10dbd63aa1bd2c4d
def seis2cat(sfile, authority='local', inventory_object=None, default_network='UK', default_channel='BH', verbose=False): <NEW_LINE> <INDENT> so = Seisob(**locals()) <NEW_LINE> cat = so.seis2cat(sfile) <NEW_LINE> return cat
Function to convert an s-file, or directory of s-files, to obspy catalog object Parameters --------- sfile : str Path to an s-file (nordic format) or directory of s-files authority : str Default authority for resource IDs inventory_object : None, obspy.station.Inventory or path to such If not None, an inv...
625941ca85dfad0860c3af05
def cross_validation_ridge_super(y, phi, k_indices, k, lambda_, degree, not_poly_features): <NEW_LINE> <INDENT> train_indices = np.delete(k_indices , k , 0).reshape((k_indices.shape[0]-1) * k_indices.shape[1]) <NEW_LINE> x_test = phi[k_indices[k],:] <NEW_LINE> x_train = phi[train_indices,:] <NEW_LINE> y_test = y[k_indi...
Return the proportion of correct classifications of ridge/linear regression in a step of k-fold cross-validation.
625941caf8510a7c17cf97a6
def _on_copy_selected(self, item): <NEW_LINE> <INDENT> pass
called when move is selected
625941ca16aa5153ce362522
def source_ranges_match(original_file_dict, diff_dict, original_result_diff_dict, modified_result_diff_dict, renamed_files): <NEW_LINE> <INDENT> for file_name in original_file_dict: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> original_total_diff = (diff_dict[file_name] + original_result_diff_dict[file_name]) <NEW_LINE...
Checks whether the SourceRanges of two results match :param original_file_dict: Dict of lists of file contents before changes :param diff_dict: Dict of diffs describing the changes per file :param original_result_diff_dict: diff for each file for this result :param modified_result_diff_dict: guess :param rena...
625941ca187af65679ca51c8
def pack(o, default=encode, encoding='latin1', unicode_errors='strict', use_single_float=False, autoreset=1, use_bin_type=1): <NEW_LINE> <INDENT> return Packer(default=default, encoding=encoding, unicode_errors=unicode_errors, use_single_float=use_single_float, autoreset=autoreset, use_bin_type=use_bin_type).pack(o)
Pack an object and return the packed bytes.
625941ca851cf427c661a5b9
def __del__(self): <NEW_LINE> <INDENT> self.hFile.close()
Destructor :return: None
625941ca1f5feb6acb0c4bfb
def insere(a, b, sa, pb): <NEW_LINE> <INDENT> pa = pred[a, sa] <NEW_LINE> sb = succ[b, pb] <NEW_LINE> succ[a, pa] = b <NEW_LINE> succ[a, b] = sa <NEW_LINE> pred[a, sa] = b <NEW_LINE> pred[a, b] = pa <NEW_LINE> pred[b, sb] = a <NEW_LINE> pred[b, a] = pb <NEW_LINE> succ[b, pb] = a <NEW_LINE> succ[b, a] = sb
Insère l'arête (a, b), avec sa et pb les points tels qu'à la fin de l'opération, succ[a, b] = sa et pred[b, a] = pb.
625941ca82261d6c526ab549
def read_file(reader): <NEW_LINE> <INDENT> helper = LayerHelper('read_file') <NEW_LINE> out = [ helper.create_variable_for_type_inference( stop_gradient=True, dtype='float32') for _ in range(len(reader.desc.shapes())) ] <NEW_LINE> helper.append_op( type='read', inputs={'Reader': [reader]}, outputs={'Out': out}) <NEW_LI...
:api_attr: Static Graph Execute the given reader and get data via it. A reader is also a Variable. It can be a raw reader generated by `fluid.layers.open_files()` or a decorated one generated by `fluid.layers.double_buffer()` . Args: reader(Variable): The reader to execute. Returns: Tuple[Variable]: Da...
625941cab57a9660fec3392e
def refresh(systems): <NEW_LINE> <INDENT> output = [generate_sidepanel(sys, i) for i, sys in enumerate(systems)] <NEW_LINE> if output == []: <NEW_LINE> <INDENT> return display() <NEW_LINE> <DEDENT> return html.Div( [html.Ul(output, className="list-group")], className="scrollable-list" )
Return a html for rendering the display in the read-only spin-system section.
625941ca435de62698dfdcf7
def bindSequence(self, path=None): <NEW_LINE> <INDENT> raise NotImplementedError
**Purpose** Bind genome fasta files so that this genome object will recognise the sequence. This step is required if you want to use fastalists and genome.getSequence() **Arguments** path path specifying the locations of the FASTA files that make up the sequence data. They usually come in the form "chr1.fa" ...
625941ca1f5feb6acb0c4bfc
def __init__(self, *args): <NEW_LINE> <INDENT> _itkFixedArrayPython.itkFixedArrayB3_swiginit(self,_itkFixedArrayPython.new_itkFixedArrayB3(*args))
__init__(self, itkFixedArrayB3 arg0) -> itkFixedArrayB3 __init__(self) -> itkFixedArrayB3 __init__(self, bool r) -> itkFixedArrayB3 __init__(self, bool r) -> itkFixedArrayB3
625941ca0c0af96317bb8292
def fetch(bank, key): <NEW_LINE> <INDENT> c_key = "{}/{}".format(bank, key) <NEW_LINE> try: <NEW_LINE> <INDENT> _, value = api.kv.get(c_key) <NEW_LINE> if value is None: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> return salt.payload.loads(value["Value"]) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <I...
Fetch a key value.
625941ca26068e7796caed88
def max_unpool1d(input, indices, kernel_size, stride=None, padding=0, output_size=None): <NEW_LINE> <INDENT> kernel_size = _single(kernel_size) <NEW_LINE> if stride is not None: <NEW_LINE> <INDENT> _stride = _single(stride) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _stride = kernel_size <NEW_LINE> <DEDENT> padding ...
Computes a partial inverse of :class:`MaxPool1d`. See :class:`~torch.nn.MaxUnpool1d` for details.
625941ca6fece00bbac2d7e8
def parse(self,text,element_store=None,context='block', environ=None, preprocess=True): <NEW_LINE> <INDENT> if element_store is None: <NEW_LINE> <INDENT> element_store = {} <NEW_LINE> <DEDENT> if not isinstance(context,list): <NEW_LINE> <INDENT> if context == 'block': <NEW_LINE> <INDENT> top_level_elements = self.diale...
Returns a Genshi Fragment (basically a list of Elements and text nodes). :parameters: text The text to be parsed. context This is useful for marco development where (for example) supression of paragraph tags is desired. Can be 'inline', 'block', or a list of WikiElement objects (use with caution). ...
625941cafff4ab517eb2f4e6
def delete_user(self, user_id): <NEW_LINE> <INDENT> if self.database is None: <NEW_LINE> <INDENT> raise Exception("No database.") <NEW_LINE> <DEDENT> if user_id is None or len(user_id) == 0: <NEW_LINE> <INDENT> raise Exception("Bad parameter.") <NEW_LINE> <DEDENT> user_devices = self.database.retrieve_user_devices(user...
Removes a user from the database.
625941ca6fb2d068a760f147
def testGetHostsForProgram(self): <NEW_LINE> <INDENT> host = profile_utils.seedNDBUser() <NEW_LINE> program_one = program_utils.seedProgram(host=host) <NEW_LINE> program_two = program_utils.seedProgram() <NEW_LINE> hosts = set([host.key]) <NEW_LINE> for _ in range(3): <NEW_LINE> <INDENT> user_entity = profile_utils.see...
Tests if a correct user entities are returned.
625941ca925a0f43d2549f21
def get_collaborator(self, collaborator_id): <NEW_LINE> <INDENT> return Collaborator( self._client.get( "organizations/{}/collaborators/{}".format(self.id, collaborator_id) ), organization=self, client=self._client, )
get collaborator by id
625941ca1b99ca400220ab5c
def test_redundant_returns_correct_num_of_entrie(self): <NEW_LINE> <INDENT> temp_length = register('a', 'b', 'c') <NEW_LINE> self.assertEqual( len(temp_length), 6, msg='All three fields in register need to be filled out')
method to ensure variables are not added to list automagically
625941cadc8b845886cb55df
def mock_monitor(serial_number: int) -> MagicMock: <NEW_LINE> <INDENT> monitor = mock_with_listeners() <NEW_LINE> monitor.serial_number = serial_number <NEW_LINE> monitor.voltage = 120.0 <NEW_LINE> monitor.pulse_counters = [mock_pulse_counter() for i in range(0, 4)] <NEW_LINE> monitor.temperature_sensors = [mock_temper...
Create a mock GreenEye Monitor.
625941ca26068e7796caed89
def nitems_written(self, *args, **kwargs): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_stretch_ff_sptr_nitems_written(self, *args, **kwargs)
nitems_written(self, unsigned int which_output) -> uint64_t
625941cac4546d3d9de72ade
def _get_target(self, ghid): <NEW_LINE> <INDENT> gobdlite = await_coroutine_threadsafe( coro = self.librarian.summarize(ghid), loop = self.nooploop._loop ) <NEW_LINE> return gobdlite.target
Figure out what is being targeted by the dynamic ghid.
625941ca23e79379d52ee60f
def _apply_terms(self, *terms: Any) -> None: <NEW_LINE> <INDENT> if self._insert_table is None: <NEW_LINE> <INDENT> raise AttributeError("'Query' object has no attribute '%s'" % "insert") <NEW_LINE> <DEDENT> if not terms: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not isinstance(terms[0], (list, tuple, set)): <N...
Handy function for INSERT and REPLACE statements in order to check if terms are introduced and how append them to `self._values`
625941cab545ff76a8913ec1
def change_list_value(lst, idx, new_val): <NEW_LINE> <INDENT> print("Original list: " + str(lst)) <NEW_LINE> print("Set idx " + str(idx) + " to " + str(new_val)) <NEW_LINE> lst[idx] = new_val <NEW_LINE> return lst
Updates the value of lst at the idx.
625941ca63f4b57ef00011c5
def exportTopicTree(moduleName = None, rootTopicName=None, rootTopic=None, bak='bak', moduleDoc=None): <NEW_LINE> <INDENT> if rootTopicName: <NEW_LINE> <INDENT> rootTopic = _topicMgr.getTopic(rootTopicName) <NEW_LINE> <DEDENT> if rootTopic is None: <NEW_LINE> <INDENT> rootTopic = getDefaultRootAllTopics() <NEW_LINE> <D...
Export the topic tree to a string and return the string. The export only traverses the children of rootTopic. Notes: - If moduleName is given, the string is also written to moduleName.py in os.getcwd() (the file is overwritten). If bak is not None, the module file is first copied to moduleName.py.bak. - If rootTo...
625941ca956e5f7376d70f18
def find_no_ini(base) : <NEW_LINE> <INDENT> no_ini = [ ] <NEW_LINE> for p, subdirs, files in os.walk(base) : <NEW_LINE> <INDENT> has_ini = False <NEW_LINE> for f in files : <NEW_LINE> <INDENT> has_ini |= f.endswith(".ini") <NEW_LINE> if has_ini: break <NEW_LINE> <DEDENT> if not has_ini : <NEW_LINE> <INDENT> no_ini.appe...
find all subdirectories having no ini file
625941cad10714528d5ffd8d
def validate_main(models, images, masks, output): <NEW_LINE> <INDENT> print("started validation") <NEW_LINE> os.makedirs(output, exist_ok=True) <NEW_LINE> handle = open(os.path.join(output, "dice.csv"), "w") <NEW_LINE> handle.write("model,image,dice\n") <NEW_LINE> best_dice = 0 <NEW_LINE> best_model = None <NEW_LINE> f...
Validates a u-net given a pair of corresponding images and segmentation masks. Selects the model with the best accuracy and saves it as "best-model". Parameters: models (str): a path to directory of model checkpoints images (str): a string storing the path to the validation image directory masks (str): a ...
625941ca71ff763f4b549735
def validate_user_input(self, player): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> d = self.DeckList[len(self.DeckList) - 1] <NEW_LINE> user_inp = int(input("Enter Player " + player.PlayingMark + " move:")) <NEW_LINE> if user_inp < 0 or user_inp > 8: <NEW_LINE> <INDENT> print("invalid m...
validate user's input :param player: player's object who is currently playing :return:
625941cafb3f5b602dac373d
@task <NEW_LINE> def dev(): <NEW_LINE> <INDENT> server = 'graph.dev.lincolnloop.com' <NEW_LINE> env.roledefs = { 'web': [server], 'db': [server], } <NEW_LINE> env.system_users = {server: 'www-data'} <NEW_LINE> env.virtualenv_dir = '/srv/www/{project_name}'.format(**env) <NEW_LINE> env.project_dir = '{virtualenv_dir}/sr...
Use the development deployment environment.
625941caab23a570cc25022d
def find(grants): <NEW_LINE> <INDENT> pass
Return the specified `IAccessArtifactGrant`s if they exist. :param grants: a collection of (`IAccessArtifact`, grantee `IPerson`) pairs.
625941caa79ad161976cc1f0
def revision_tree(self): <NEW_LINE> <INDENT> raise NotImplementedError(self.revision_tree)
Return the tree that was just committed. After calling commit() this can be called to get a RevisionTree representing the newly committed tree. This is preferred to calling Repository.revision_tree() because that may require deserializing the inventory, while we already have a copy in memory.
625941ca3346ee7daa2b2e16
def flags(self, index): <NEW_LINE> <INDENT> column = index.column() <NEW_LINE> if column==PluginFileCol: <NEW_LINE> <INDENT> flag = super(FileModel, self).flags(index) <NEW_LINE> return flag | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable <NEW_LINE> <DEDE...
flag描述了view中数据项的状态信息
625941ca15fb5d323cde0bba
def get_hdrs(jsondoc): <NEW_LINE> <INDENT> hdr_lst = [(x["id"], x["parent"], x["relation"]) for x in jsondoc['root'] if x["id"] != 0] <NEW_LINE> return hdr_lst
get hdr description for each doc
625941ca5fdd1c0f98dc02de
def mountPoint(self): <NEW_LINE> <INDENT> return QUrl()
static QUrl Soprano.Vocabulary.Xesam.mountPoint()
625941ca566aa707497f4614
def test_pages_routing_and_rendering(): <NEW_LINE> <INDENT> app = create_ctfd() <NEW_LINE> with app.app_context(): <NEW_LINE> <INDENT> html = """##The quick brown fox jumped over the lazy dog""" <NEW_LINE> route = "test" <NEW_LINE> title = "Test" <NEW_LINE> gen_page(app.db, title, route, html) <NEW_LINE> with app.test_...
Test that pages are routing and rendering
625941caeab8aa0e5d26dc02
def callback_progress(blocks, block_size, total_size, bar_function): <NEW_LINE> <INDENT> global __current_size <NEW_LINE> width = 100 <NEW_LINE> if sys.version_info[:3] == (3, 3, 0): <NEW_LINE> <INDENT> if blocks == 0: <NEW_LINE> <INDENT> __current_size = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> __current_size +...
callback function for urlretrieve that is called when connection is created and when once for each block draws adaptive progress bar in terminal/console use sys.stdout.write() instead of "print,", because it allows one more symbol at the line end without linefeed on Windows :param blocks: number of blocks transferre...
625941ca91f36d47f21ac59d
def add_renderer_globals(event): <NEW_LINE> <INDENT> request = event.get('request') <NEW_LINE> if request is None: <NEW_LINE> <INDENT> request = get_current_request() <NEW_LINE> <DEDENT> globs = { 'url': route_url, 'h':None, } <NEW_LINE> if request is not None: <NEW_LINE> <INDENT> tmpl_context = request.tmpl_context <N...
A subscriber to the ``pyramid.events.BeforeRender`` events. Updates the :term:`renderer globals` with values that are familiar to Pylons users.
625941ca30bbd722463cbe70
def init_args(args): <NEW_LINE> <INDENT> watchercfg = {} <NEW_LINE> if args.enc_whitelist_file: <NEW_LINE> <INDENT> log.info("Watching encounter whitelist file {} for changes.".format(args.enc_whitelist_file)) <NEW_LINE> watchercfg['enc_whitelist'] = (args.enc_whitelist_file, None) <NEW_LINE> <DEDENT> args.webhook_whit...
Initialize commandline arguments after parsing. Some things need to happen after parsing. :param args: The parsed commandline arguments
625941ca711fe17d82542417
def get_logger(name): <NEW_LINE> <INDENT> logger = logging.getLogger(name) <NEW_LINE> logger.setLevel(logging.DEBUG) <NEW_LINE> rotate_handler = RotatingFileHandler(PROJECT_HOME+"/logs/"+name+".log", 'a', 1024*1024*5, 5) <NEW_LINE> formatter = logging.Formatter('[%(levelname)s]-%(asctime)s-%(filename)s:%(lineno)s:%(mes...
Args: name(str):생성할 log 파일명입니다. Returns: 생성된 logger객체를 반환합니다.
625941ca287bf620b61d3b0f
def test_event_delete_date_api_delete_method_fail(self): <NEW_LINE> <INDENT> self.create_event() <NEW_LINE> headers = self.create_auth_header(token=self.token) <NEW_LINE> if constants.SESSION_NAME == os.environ.get('APP_ADMIN') or constants.SESSION_NAME == os.environ.get('EVENT_EDITOR'): <NEW_LINE> <INDENT> r...
Tests Delete Event Date Delete Method Fail
625941ca97e22403b379d044
def twoSum(self, nums, target): <NEW_LINE> <INDENT> for i in range(0,len(nums)): <NEW_LINE> <INDENT> second_number = target - nums[i] <NEW_LINE> try: <NEW_LINE> <INDENT> j= nums.index(second_number,i+1) <NEW_LINE> break <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT...
:type nums: List[int] :type target: int :rtype: List[int]
625941ca66656f66f7cbc256
def decision_function(self, X, method='most-wins'): <NEW_LINE> <INDENT> X = _check_2d_inp(X, reshape = True) <NEW_LINE> if method == 'most-wins': <NEW_LINE> <INDENT> return self._decision_function_winners(X) <NEW_LINE> <DEDENT> elif method == 'goodness': <NEW_LINE> <INDENT> return self._decision_function_goodness(X) <N...
Calculate a 'goodness' distribution over labels Note ---- Predictions can be calculated either by counting which class wins the most pairwise comparisons (as in [1] and [2]), or - for classifiers with a 'predict_proba' method - by taking into account also the margins of the prediction difference for one class over the...
625941ca32920d7e50b2827a
def gen_min_interval_slots(data_frame: DataFrame, window: float, min_ratio: float, final_window: float, confidence: float, start: int, end: int, num_sim_runs: int = 1000, queue: deque = None) -> Union[None, List[SimulationResults]]: <NEW_LINE> <INDENT> if num_sim_runs <= 0: <NEW_LINE> <INDENT> raise ValueError('Invalid...
Get the optimal patient schedule. Throws an error if num sim runs is <= 0 :param data_frame: Stochastic arrivals generator :param window: the time in which an arrival must be processed by, and if not is considered overdue. Must correspond to the same time unit as the rate of arrivals time. :param min_ratio: The...
625941ca50812a4eaa59c3cd
def limit(self, rows): <NEW_LINE> <INDENT> node = copy.deepcopy(self.node) <NEW_LINE> params = self.to_dict() <NEW_LINE> params.update({ "node": node, "rows": rows }) <NEW_LINE> return SolrQueryManager(**params)
Specify the number of documents returned.
625941ca796e427e537b0671
def GetRank(self): <NEW_LINE> <INDENT> return _itkFastApproximateRankImageFilterPython.itkFastApproximateRankImageFilterIUC2IUC2_GetRank(self)
GetRank(self) -> float
625941ca627d3e7fe0d68efa
@app_views.route('/states', methods=["GET"], strict_slashes=False) <NEW_LINE> @app_views.route('/states/<state_id>', methods=["GET"], strict_slashes=False) <NEW_LINE> def state(state_id=None): <NEW_LINE> <INDENT> if state_id is None: <NEW_LINE> <INDENT> states = storage.all("State") <NEW_LINE> my_states = [value.to_dic...
retrieves a list of all states
625941cab7558d58953c4fc0
@login_required(login_url=settings.LOGIN_URL) <NEW_LINE> @cache_control(no_cache=True, must_revalidate=True, no_store=True) <NEW_LINE> @require_http_methods(['GET', 'POST']) <NEW_LINE> def create_session(request): <NEW_LINE> <INDENT> request = userApi.has_admin_access(request) <NEW_LINE> if request.method == 'POST': <N...
Create a session
625941ca30c21e258bdfa548
def preprocess(path_in, path_train, path_val, delta_vec, delta_map, label_map): <NEW_LINE> <INDENT> batch = 1 <NEW_LINE> pointer = 1 + BATCH_SIZE * 2 <NEW_LINE> stop = False <NEW_LINE> while not stop: <NEW_LINE> <INDENT> print("\nNow loading batch", batch, "...") <NEW_LINE> stop, data = load_data(path_in, pointer, BATC...
Make and store vectors that a neural network can use.
625941ca3317a56b86939d05
def test_duplicate_missing_check(self): <NEW_LINE> <INDENT> initial = { "comment": "This is a valid comment", "duplicate": False, "same_as_ticket": 1, } <NEW_LINE> form = CloseTicketForm( data=initial, instance=self.comment, ticket=self.ticket, user=self.user, action="closed", ) <NEW_LINE> self.assertFalse(form.is_vali...
throw an error if a ticket number is provided but the duplicate check box if left blank.
625941cabde94217f3682e9d
def __init__(self): <NEW_LINE> <INDENT> pass
empty constructor
625941ca60cbc95b062c65ee
@applies_to_released <NEW_LINE> def validate_existing_tags(deliv, context): <NEW_LINE> <INDENT> for release in deliv.releases: <NEW_LINE> <INDENT> LOG.debug('checking {}'.format(release.version)) <NEW_LINE> for project in release.projects: <NEW_LINE> <INDENT> if project.repo.is_retired: <NEW_LINE> <INDENT> LOG.info('%s...
Ensure tags that exist point to the SHAs listed.
625941cade87d2750b85fe3e
def __assert(self): <NEW_LINE> <INDENT> if(not isinstance(self.dl_src, list)): <NEW_LINE> <INDENT> return (False, "self.dl_src is not list as expected.") <NEW_LINE> <DEDENT> if(len(self.dl_src) != 6): <NEW_LINE> <INDENT> return (False, "self.dl_src is not of size 6 as expected.") <NEW_LINE> <DEDENT> if(not isinstance(s...
Sanity check
625941ca293b9510aa2c3342