code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def shipments_create(self, body, x_rmg_auth_token, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.shipments_create_with_http_info(body, x_rmg_auth_token, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.s...
Create Shipment # noqa: E501 Use to generate the final delivery label for your packages.<br /> <br />The request is split into several sections:<br /> <br />**Shipper** - who and where the parcel is coming from - optional if the posting location is to be used.<br />**Destination** - who and wher...
625941e4f548e778e58cd982
def route(self, pattern): <NEW_LINE> <INDENT> super_decorator = super(KlausApplication, self).route(pattern) <NEW_LINE> def decorator(callback): <NEW_LINE> <INDENT> @wraps(callback) <NEW_LINE> def wrapper(env, **kwargs): <NEW_LINE> <INDENT> if hasattr(self, 'custom_host'): <NEW_LINE> <INDENT> env['HTTP_HOST'] = self.cu...
Extends `NanoApplication.route` by multiple features: - Overrides the WSGI `HTTP_HOST` by `self.custom_host` (if set) - Tries to use the keyword arguments returned by the view function to render the template called `<class>.html` (<class> being the name of `self`'s class). Raising `Response` can be used to skip ...
625941e463f4b57ef0001511
def _generate_cutouts(self): <NEW_LINE> <INDENT> for tile in self.tiles: <NEW_LINE> <INDENT> gc.collect() <NEW_LINE> da = rioxr.open_rasterio(tile).astype("float32") <NEW_LINE> if self.bands is not None: <NEW_LINE> <INDENT> if type(self.bands) is not list: <NEW_LINE> <INDENT> da = da.sel(band=[self.bands]) <NEW_LINE> <...
Iterate over (a selection of) the tiles yielding all cutouts for each of them.
625941e40c0af96317bb85eb
def graph_demo(): <NEW_LINE> <INDENT> tf_a = tf.constant(10) <NEW_LINE> tf_b = tf.constant(20) <NEW_LINE> sum_tfab = tf_a + tf_b <NEW_LINE> print('sum_tfab is:', sum_tfab) <NEW_LINE> print('方法1查看默认图', tf.get_default_graph()) <NEW_LINE> print('方法2查看默认图tf_a.graph:', tf_a.graph) <NEW_LINE> print('方法2查看默认图tf_b.graph:', tf_...
图栗
625941e4fb3f5b602dac3a9b
def test_get_all_translatable_content_for_text_input_answer_groups(self): <NEW_LINE> <INDENT> state = state_domain.State.create_default_state('state_1') <NEW_LINE> state_answer_group = [ state_domain.AnswerGroup( state_domain.Outcome( 'destination', state_domain.SubtitledHtml( 'feedback_1', '<p>state outcome html</p>')...
Get all the translatable fields for answer group.
625941e4435de62698dfe050
def __init__(self): <NEW_LINE> <INDENT> MinifierBackend.__init__(self, 'slimit') <NEW_LINE> from ply import yacc <NEW_LINE> def __getitem__(self, n): <NEW_LINE> <INDENT> if isinstance(n, slice): <NEW_LINE> <INDENT> return self.__getslice__(n.start, n.stop) <NEW_LINE> <DEDENT> if n >= 0: <NEW_LINE> <INDENT> return self....
Initializes the slimit library. This will fix an error in current version of ply. See https://github.com/rspivak/slimit/issues/64#issuecomment-38801874 for details.
625941e4d99f1b3c44c6798b
def hours_to_hms(h): <NEW_LINE> <INDENT> sign = math.copysign(1.0, h) <NEW_LINE> (hf, h) = math.modf(abs(h)) <NEW_LINE> (mf, m) = math.modf(hf * 60.0) <NEW_LINE> s = mf * 60.0 <NEW_LINE> check_hms_ranges(h, m, s) <NEW_LINE> return (float(sign * h), int(sign * m), sign * s)
Convert any parseable hour value (see: parse_hours) into an ``(hour, minute, second)`` tuple.
625941e430dc7b7665901d65
def motifs_to_file_retro(motifs, motifs_file_name): <NEW_LINE> <INDENT> with open("{0}.csv".format(motifs_file_name), "w") as file: <NEW_LINE> <INDENT> file.write("{0}\n".format(motifs_file_name)) <NEW_LINE> for i in motifs: <NEW_LINE> <INDENT> file.write("{0}\n".format(i))
Write a list of motifs into an old school motifs file.
625941e4d8ef3951e3243941
def auth(store=None, api_key=None, password=None): <NEW_LINE> <INDENT> store = store or CONFIG_MAIN["store"] <NEW_LINE> api_key = api_key or CONFIG_MAIN["api_key"] <NEW_LINE> password = password or CONFIG_MAIN["password"] <NEW_LINE> shop_url = "https://%s:%s@%s/admin" % (api_key, password, store) <NEW_LINE> shopify.Sho...
Set authentication details for shopify.
625941e482261d6c526ab8a9
def btn_new_function(self): <NEW_LINE> <INDENT> pass
Function that executes on new game button press.
625941e463d6d428bbe448f4
def __init__(self, app, handler): <NEW_LINE> <INDENT> super(GroupsController, self).__init__( "Group", 'groups', 'group', 'groups', app, handler )
Constructor :param Flask app: Flask application :param handler: Tenant config handler
625941e4377c676e912725aa
def localized(self): <NEW_LINE> <INDENT> return self.filter(language=translation.get_language())
Returns a queryset with all salutations aviable in the current language
625941e4287bf620b61d3e65
def testSubscriptionTerminated(self): <NEW_LINE> <INDENT> event = blpapi.test.createEvent(blpapi.Event.SUBSCRIPTION_STATUS) <NEW_LINE> schema = blpapi.test.getAdminMessageDefinition( blpapi.Name("SubscriptionTerminated")) <NEW_LINE> formatter = blpapi.test.appendMessage(event, schema) <NEW_LINE> content = { "reason": {...
Sample SubscriptionTerminated message
625941e4925a0f43d254a27e
def unpack_transition(self, transition_tensors, transition_type): <NEW_LINE> <INDENT> self.transition = collections.OrderedDict() <NEW_LINE> for element, element_type in zip(transition_tensors, transition_type): <NEW_LINE> <INDENT> self.transition[element_type.name] = element <NEW_LINE> <DEDENT> self.states = self.tran...
Unpacks the given transition into member variables. Args: transition_tensors: tuple of tf.Tensors. transition_type: tuple of ReplayElements matching transition_tensors.
625941e4293b9510aa2c3695
def print_leftright_only(dcmp, leftright = 'left'): <NEW_LINE> <INDENT> if leftright == 'left': <NEW_LINE> <INDENT> leftrightonlys = dcmp.left_only <NEW_LINE> <DEDENT> elif leftright == 'right': <NEW_LINE> <INDENT> leftrightonlys = dcmp.right_only <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('leftrigh...
Takes a Cmpfile.dircmp object and return all files or directories that are under the left (or right) and are not under the right (or left) directory in the comparison. INPUT: dcmp --- Cmpfile.dircmp object that compares two directories leftright --- 'left' ('right') to return files and directories that ar...
625941e497e22403b379d39f
def _compute_dtypes(self): <NEW_LINE> <INDENT> def dtype_builder(df): <NEW_LINE> <INDENT> return df.apply(lambda col: find_common_type(col.values), axis=0) <NEW_LINE> <DEDENT> map_func = self._build_mapreduce_func(0, lambda df: df.dtypes) <NEW_LINE> reduce_func = self._build_mapreduce_func(0, dtype_builder) <NEW_LINE> ...
Compute the dtypes via MapReduce. Returns ------- The data types of this dataframe.
625941e4b545ff76a8914219
def append(self, value): <NEW_LINE> <INDENT> parent = self._self_xl_parent <NEW_LINE> last_idx = self.length() + 1 <NEW_LINE> if parent.cols: <NEW_LINE> <INDENT> self.Cells(last_idx, 1).Value = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Cells(1, last_idx).Value = value
Append an item to the end of the list.
625941e46aa9bd52df0371aa
def receive_event(self, event): <NEW_LINE> <INDENT> raise NotImplementedError()
The method receiving events. @param event: The event object of type Event containing the information about the event.
625941e4be7bc26dc91cd9fc
def _add_station(self, station): <NEW_LINE> <INDENT> self.stations.append(station)
Add a station to a particular reserve zone
625941e44c3428357757c729
def Ubulge(self, r): <NEW_LINE> <INDENT> return -self.G*self.Mbulge/(r+self.abulge)
Bulge contribution to potential divided by system mass
625941e43539df3088e2e74f
def update_pb_framr_host(old_host, new_host): <NEW_LINE> <INDENT> configs = [] <NEW_LINE> config_path = EDIT_FILES['pb_framr_pages'] <NEW_LINE> custom_config_path = f'{custom_path}/{config_path}' <NEW_LINE> with open(custom_config_path, 'r') as file: <NEW_LINE> <INDENT> configs = pyjson.load(file) <NEW_LINE> for c in c...
Updates framr config to use changed host name :old_host: old host that shall be replaced :new_host: host that will be the new target
625941e4d7e4931a7ee9e323
def get_table_rows(url): <NEW_LINE> <INDENT> response = requests.get(url) <NEW_LINE> soup = bs4.BeautifulSoup(response.text) <NEW_LINE> return soup.select('tr')
Returns soup elements with 'tr' tags str -> soup
625941e45fcc89381b1e1ac5
def dual(self): <NEW_LINE> <INDENT> return self
Simply laced Cartan types are self-dual, so return ``self``. EXAMPLES:: sage: CartanType(["A", 3]).dual() ['A', 3] sage: CartanType(["A", 3, 1]).dual() ['A', 3, 1] sage: CartanType(["D", 3]).dual() ['D', 3] sage: CartanType(["D", 4, 1]).dual() ['D', 4, 1] sage: CartanType(["E", 6])...
625941e4442bda511e8be816
def __init__(self, batched_env, model, min_episodes=1, min_steps=1, drop_states=False): <NEW_LINE> <INDENT> self.min_episodes = min_episodes <NEW_LINE> self.min_steps = min_steps <NEW_LINE> self._env_mask = None <NEW_LINE> super().__init__(batched_env, model, 0, drop_states=drop_states)
Create a new EpisodeRoller. Args: batched_env: a BatchedEnv to interact with. model: a Model to use for interaction. min_episodes: the minimum number of episodes to rollout. min_steps: the minimum number of timesteps to rollout, across all environments. drop_states: if True, set model_outs['states'] ...
625941e4a8ecb033257d34cf
def example14_1(): <NEW_LINE> <INDENT> bm = converter.parse("tinynotation: 4/4 f8 a c' a g c' e g").flat <NEW_LINE> bm.notes[0].articulations.append(articulations.Accent()) <NEW_LINE> bm.notes[2].articulations.append(articulations.Accent()) <NEW_LINE> bm.notes[4].articulations.append(articulations.Accent()) <NEW_LINE> ...
>>> from music21.braille import test >>> from music21.braille import translate >>> print(translate.partToBraille(test.example14_1(), inPlace=True, ... showFirstMeasureNumber=False)) ⠀⠀⠀⠀⠀⠀⠀⠀⠣⠼⠙⠲⠀⠀⠀⠀⠀⠀⠀ ⠨⠦⠐⠛⠊⠨⠦⠙⠊⠨⠦⠓⠨⠙⠨⠦⠐⠋⠓
625941e4cad5886f8bd273dd
def _calcRankings(self): <NEW_LINE> <INDENT> if not self._graphCalculated: self._calcPaths() <NEW_LINE> candidates = self._graph._candidates.copy() <NEW_LINE> while len(candidates) > 0: <NEW_LINE> <INDENT> weakest = [] <NEW_LINE> for c in candidates: <NEW_LINE> <INDENT> remove = True <NEW_LINE> for challenger in candid...
Determine rankings based on the strongest path matrix.
625941e4f7d966606f6aa40d
def is_logged_in(view_func): <NEW_LINE> <INDENT> def new_view_func(request): <NEW_LINE> <INDENT> if request.session.get('logged_in', False): <NEW_LINE> <INDENT> return view_func(request) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return JsonResponse({'Error': 'User not logged in'}) <NEW_LINE> <DEDENT> <DEDENT> retur...
This decorator checks whether the request comes from an authenticated user, If yes, returns to the view function, else returns an error response.
625941e49b70327d1c4e11db
def stop(self, val, t=None): <NEW_LINE> <INDENT> self.is_manual = False <NEW_LINE> self.displacement += abs(val - self.history[-1][1]) <NEW_LINE> if self.displacement <= self.drag_threshold: <NEW_LINE> <INDENT> self.velocity = 0 <NEW_LINE> <DEDENT> return super(StiffScrollEffect, self).stop(val, t)
Work out whether I've been flung.
625941e4507cdc57c63070e7
def getVazelsPath(): <NEW_LINE> <INDENT> return os.path.join( config.getSettings("global")['basedir'], config.getSettings("control_centre")["vazels_dir"], )
Grab the path to the vazels installation directory. :returns: Absolute path to the vazels install directory. :rtype: ``str``
625941e430dc7b7665901d66
def _add_logger_level(levelname, level, *, func_name=None): <NEW_LINE> <INDENT> func_name = func_name or levelname.lower() <NEW_LINE> setattr(logging, levelname, level) <NEW_LINE> logging.addLevelName(level, levelname) <NEW_LINE> _func_prototype = "def {logger_func_name}(self, message, *args, **kwargs):\n" " ...
:type levelname: str The reference name of the level, e.g. DEBUG, WARNING, etc :type level: int Numeric logging level :type func_name: str The name of the logger function to log to a level, e.g. "info" for log.info(...)
625941e421bff66bcd684d52
def prior_squared_error(y_true, y_pred, prior): <NEW_LINE> <INDENT> pr = pr_one_unlabeled(y_true, y_pred) <NEW_LINE> if pr == 0.0: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (pr - prior) ** 2
This will evaluate how many of the unlabeled data are pos_label and see as a percentage how far away it is from the prior Assumption: label -1 == unlabeled, 0 == negative, 1 == positive
625941e4e64d504609d74c44
def posterior(self, variable): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.letterboxes[variable][0].content <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> print("{} not found in variables, try to makeInference on the object.".format(variable)) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <IN...
retourne la distribution de la variable sous la forme d'un `gum.Potential`
625941e43d592f4c4ed1d466
def count(self, status: TinkModelResultStatus): <NEW_LINE> <INDENT> cnt = sum(e.status == status for e in self.results) <NEW_LINE> return cnt
Count all elements having the given status. :param status: Reference to an instance of the Enum class TinkResultStatus. :return: The number of elements in the list self.result with the requested status.
625941e49c8ee82313fbbb7a
def get_args(): <NEW_LINE> <INDENT> p = argparse.ArgumentParser( description="Start the FedAvg server for the PlantVillage with " "the train and validation data-folders provided.\n") <NEW_LINE> p.add_argument("--train-data-path", help="The path to the train data.", type=str, required=False) <NEW_LINE> p.add_argument("-...
Parse the arguments for running the FedAvg server for PlantVillage dataset.
625941e4cc40096d61595d53
def _make_grid_points(self): <NEW_LINE> <INDENT> xsize, ysize = self.imgsize <NEW_LINE> self._xsteps = int(xsize / self.sep[0]) + 1 <NEW_LINE> self._ysteps = int(ysize / self.sep[1]) <NEW_LINE> grid = np.mgrid[0:self._xsteps, 0:self._ysteps] <NEW_LINE> self.grid_points = grid.T.reshape((-1, 2)) * self.sep <NEW_LINE> po...
Generate grid points in a bird view.
625941e4fbf16365ca6f65d0
@scopes.add_arg_scope <NEW_LINE> def batch_norm(inputs, decay=0.999, center=True, scale=False, epsilon=0.001, moving_vars='moving_vars', activation=None, is_training=True, trainable=True, restore=True, scope=None, reuse=None): <NEW_LINE> <INDENT> inputs_shape = inputs.get_shape() <NEW_LINE> with tf.variable_scope(scope...
Adds a Batch Normalization layer. Args: inputs: a tensor of size [batch_size, height, width, channels] or [batch_size, channels]. decay: decay for the moving average. center: If True, subtract beta. If False, beta is not created and ignored. scale: If True, multiply by gamma. If False, gamma is n...
625941e499fddb7c1c9de793
def add_ant(self, x, y, speed, angle, awareness_radius): <NEW_LINE> <INDENT> ant = Ant(x, y, speed, angle, awareness_radius) <NEW_LINE> self.ants.append(ant)
Add ant to the Environment
625941e407d97122c4178c98
@web.route('/search') <NEW_LINE> def search(): <NEW_LINE> <INDENT> form = SearchForm(request.args) <NEW_LINE> books = BookCollectionViewModel() <NEW_LINE> if form.validate(): <NEW_LINE> <INDENT> q = form.q.data.strip() <NEW_LINE> page = form.page.data <NEW_LINE> isbn_or_key = is_isbn_or_key(q) <NEW_LINE> yushu_book = Y...
:q keyword or isbn :page 分页 :return:
625941e450485f2cf553d19f
def _round_linestring_coords(ls, precision): <NEW_LINE> <INDENT> return LineString([[round(x, precision) for x in c] for c in ls.coords])
Round the coordinates of a shapely LineString to some decimal precision. Parameters ---------- ls : shapely.geometry.LineString the LineString to round the coordinates of precision : int decimal precision to round coordinates to Returns ------- shapely.geometry.LineString
625941e48e71fb1e9831dbac
def parse(stats): <NEW_LINE> <INDENT> table = {} <NEW_LINE> data = json.loads(stats) <NEW_LINE> for item in data: <NEW_LINE> <INDENT> portnum = item["portnum"] <NEW_LINE> txrate = item["txrate"] <NEW_LINE> rxrate = item["rxrate"] <NEW_LINE> table[portnum] = {"txrate": txrate, "rxrate": rxrate} <NEW_LINE> <DEDENT> retur...
Create a JSON formatted data table from Packetmaster port stats.
625941e429b78933be1e5aab
def test06_validate_pi_request_failure_lot_with_untracked_product(self): <NEW_LINE> <INDENT> req = { 'location_id': self.test_location_01.id, 'inventory_adjustments': [ { 'product_id': self.apple.id, 'package_name': self.package_one.name, 'quantity': 1, 'lot_name': 'awesome_lot' } ] } <NEW_LINE> with self.assertRaisesR...
Errors if the request contains an inventory adjustment entry for an untracked product with a lot name specified
625941e4c4546d3d9de72e3b
def my_sort(func=None, array=list(), reversed=False) -> list: <NEW_LINE> <INDENT> if any([type(array) is not list, type(reversed) is not bool, func and not callable(func)]): <NEW_LINE> <INDENT> raise TypeError("Incorrect arguments pass: '{f}', '{a}', '{r}'".format( f=func, a=array, r=reversed) ) <NEW_LINE> <DEDENT> if ...
Custom sort function :param func: key-function for sorting (None, by default) :param array: one-dimensional array of data of the same type :param reversed: reverse output data, if True (False, by default) :return: sorted data array in list format
625941e4bd1bec0571d90a33
def node_throw(node): <NEW_LINE> <INDENT> for child in postorder(node, Node): <NEW_LINE> <INDENT> if isinstance(child, Exception): <NEW_LINE> <INDENT> raise child <NEW_LINE> <DEDENT> <DEDENT> return node
Raise an error, if one exists in the results (AST trees are traversed). Otherwise, the results are returned (invoke with ``>>``).
625941e4293b9510aa2c3696
def toCanvasCoordinates(self, xp, yp): <NEW_LINE> <INDENT> a = self.top_left[0] <NEW_LINE> b = self.top_left[1] <NEW_LINE> _, height = Window.size[0], Window.size[1] <NEW_LINE> bp = height - b <NEW_LINE> x = xp + a <NEW_LINE> y = height - up - bp <NEW_LINE> return int(x), int(y)
convert pixel coordinates to canvas coordinate where the origin is the lower left of the canvas (window)
625941e4b57a9660fec33c8e
def header_loader(self, callback): <NEW_LINE> <INDENT> self.header_callback = callback <NEW_LINE> return callback
This sets the callback for loading a user from a header value. The function you set should take an authentication token and return a user object, or `None` if the user does not exist. :param callback: The callback for retrieving a user object.
625941e491f36d47f21ac8fb
def test_arg_name(self): <NEW_LINE> <INDENT> response = "An argument name is required or the use of the '-l' option." <NEW_LINE> with self.assertRaises(validate.ValidateException) as cm: <NEW_LINE> <INDENT> validate.arg_name(None) <NEW_LINE> <DEDENT> message = cm.exception.message <NEW_LINE> self.assertTrue(string.find...
Test validation for argument names.
625941e4009cb60464c637b2
def curseur_droite(self): <NEW_LINE> <INDENT> if self.curseur_x == min(len(self.valeur), self.longueur_totale): <NEW_LINE> <INDENT> self.minitel.bip() <NEW_LINE> return False <NEW_LINE> <DEDENT> self.curseur_x = self.curseur_x + 1 <NEW_LINE> if self.curseur_x > self.decalage + self.longueur_visible: <NEW_LINE> <INDENT>...
Déplace le curseur d’un caractère sur la droite Si le curseur ne peut pas être déplacé, un bip est émis. Si le curseur demande à se déplacer dans une partie du champ non encore visible, un décalage s’opère. :returns: True si le curseur a subi un déplacement, False sinon.
625941e44c3428357757c72a
def open_file(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file_object = open(filename, "r") <NEW_LINE> return file_object <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return None
Returns a file stream if filename found, otherwise None
625941e4fff4ab517eb2f842
def compute_cost(Z3, Y): <NEW_LINE> <INDENT> cost = tf.div(tf.abs(tf.subtract(Y, Z3)), Y) <NEW_LINE> cost = tf.reduce_mean(cost) <NEW_LINE> return cost
Computes the cost Arguments: Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples) Y -- "true" labels vector placeholder, same shape as Z3 Returns: cost - Tensor of the cost function
625941e46fb2d068a760f4a8
def generate_openbis_name(path): <NEW_LINE> <INDENT> cleaned_name = fstools.clean_filename(path) <NEW_LINE> try: <NEW_LINE> <INDENT> barcode = extract_barcode(cleaned_name) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> logger.warn("No or more than one barcode in file: %s. Trying to find respective rule.", ...
Generate a sane file name from the input file. Copy the barcode to the front and remove invalid characters. Raise ValueError if the filename does not contain a barcode. Example ------- >>> path = "stüpid\tname(<QJFDC010EU.).>ä.raW" >>> generate_openbis_name(path) 'QJFDC010EU_stpidname.raw'
625941e45fdd1c0f98dc0639
def get_net_income(state, gross_income): <NEW_LINE> <INDENT> state_taxes = {'NY': 0.05, 'Alabama': 0.10, 'Florida': 0.20, 'Kentucky': 0.33} <NEW_LINE> fed_tax = 0.10 <NEW_LINE> if state in state_taxes: <NEW_LINE> <INDENT> state_tax = state_taxes[state] <NEW_LINE> net_income = gross_income - gross_income * (state_tax + ...
Calculate the net income based on the state and gross income :param state: the state name :param gross_income_orig: amount of gross income :return: net income after deducting the taxes
625941e41f037a2d8b946601
def toe_positions(self): <NEW_LINE> <INDENT> torso_frame = self.named.data.xmat['torso'].reshape(3, 3) <NEW_LINE> torso_pos = self.named.data.xpos['torso'] <NEW_LINE> torso_to_toe = self.named.data.xpos[_TOES] - torso_pos <NEW_LINE> return torso_to_toe.dot(torso_frame)
Returns toe positions in egocentric frame.
625941e4099cdd3c635f105d
def __getattr__(self, name): <NEW_LINE> <INDENT> data = self.__dict__['data'] <NEW_LINE> if name == 'data': <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> if name in data: <NEW_LINE> <INDENT> return data[name] <NEW_LINE> <DEDENT> raise AttributeError('unknown attribute: ' + name)
Get attribute.
625941e421a7993f00bc80fb
def train_linear_regression(X_train, y_train, max_iter, learning_rate, fit_intercept=False): <NEW_LINE> <INDENT> if fit_intercept: <NEW_LINE> <INDENT> intercept = np.ones((X_train.shape[0], 1)) <NEW_LINE> X_train = np.hstack((intercept, X_train)) <NEW_LINE> <DEDENT> weights = np.zero(X_train.shape[0], 1) <NEW_LINE> for...
Train a linear regression model with graddient descent Args: X_train, y_train (numpy.ndarray, training data set) max_iter (int, number of iterations) learning_rate (float) fit_intercept (bbol, with an intercept w0 or not) Returns: numpyt.ndarray, learned weights
625941e48a349b6b435e8577
def start(**kwargs): <NEW_LINE> <INDENT> chain = kwargs.get("chain", None) <NEW_LINE> text = kwargs.get("text", None) <NEW_LINE> parameters = kwargs.get("parameters", {}) <NEW_LINE> if not chain: <NEW_LINE> <INDENT> raise ValueError("MarkovChain instance is required") <NEW_LINE> <DEDENT> if not text: <NEW_LINE> <INDENT...
Start of generation. Args: **chain (MarkovChain instance) **text (list): text for MarkovChain init. **parameters (dict): parameters for generation.
625941e463d6d428bbe448f5
def test_to_dict_class_dates(self): <NEW_LINE> <INDENT> b1 = Amenity() <NEW_LINE> dic = b1.to_dict() <NEW_LINE> self.assertEqual(dic["__class__"], "Amenity") <NEW_LINE> self.assertEqual(type(dic["created_at"]), str) <NEW_LINE> self.assertEqual(type(dic["updated_at"]), str)
Checks for correct dictionary conversion
625941e4d6c5a10208144453
def iterate_blocks(self, layer="terrain"): <NEW_LINE> <INDENT> br = self.rect.bottomright <NEW_LINE> for b in self.world.iterate_blocks(self.rect.x, self.rect.y, *br, layer=layer): <NEW_LINE> <INDENT> yield b
:return: Generator for all terrain tiles in the building space
625941e42eb69b55b151ccb9
def get_repo_branch(self, repo, branch): <NEW_LINE> <INDENT> return helper(add_query(urlbuilder(self._url[:-1], 'repos', self._user, repo, branch), self._token))
Gets repo branch by branch id. Args: repo: repo name , as string. branch: branch name, as string.
625941e41f5feb6acb0c4f4e
def readFiles(): <NEW_LINE> <INDENT> corpusroot = './presidential_debates' <NEW_LINE> documents = {} <NEW_LINE> documentCount = 0 <NEW_LINE> for filename in os.listdir(corpusroot): <NEW_LINE> <INDENT> file = open(os.path.join(corpusroot, filename), "r", encoding='UTF-8') <NEW_LINE> doc = file.read() <NEW_LINE> file.clo...
Reads files provided in corpus. Returns: Normalized dict of TF-IDF vector for each document. The second parameter is total no. files read.
625941e40c0af96317bb85ec
def split_member_name(name_member): <NEW_LINE> <INDENT> name_of_author_return, hashtag_atrelada = name_member.split('#') <NEW_LINE> hashtag_atrelada = hashtag_atrelada <NEW_LINE> return name_of_author_return
split_member_name Quebra o nome do usuário a partir do "#" retornando somente o nome
625941e41d351010ab855f1f
def monitor_event(params): <NEW_LINE> <INDENT> expected_event_src = params.get("expected_event_src") <NEW_LINE> expected_event_target = params.get("expected_event_target") <NEW_LINE> remote_pwd = params.get("migrate_dest_pwd") <NEW_LINE> remote_ip = params.get("migrate_dest_host") <NEW_LINE> remote_user = params.get("r...
Monitor event on source/target host :param params: dict, used to setup the connection :return: virsh session and remote virsh session to catch events
625941e4046cf37aa974d148
def crop_img(img, bboxes): <NEW_LINE> <INDENT> return list(map(lambda x: create_crop_data(img, np.array(x)), list(bboxes)))
Crop image according to bounding boxes
625941e47b25080760e3985b
def test_n_dimensional_ICtCp_to_RGB(self): <NEW_LINE> <INDENT> ICtCp = np.array([0.07351364, 0.00475253, 0.09351596]) <NEW_LINE> RGB = ICtCp_to_RGB(ICtCp) <NEW_LINE> ICtCp = np.tile(ICtCp, (6, 1)) <NEW_LINE> RGB = np.tile(RGB, (6, 1)) <NEW_LINE> np.testing.assert_almost_equal(ICtCp_to_RGB(ICtCp), RGB, decimal=7) <NEW_L...
Test :func:`colour.models.rgb.ictcp.ICtCp_to_RGB` definition n-dimensional support.
625941e40a50d4780f66729a
def isTooLate(self): <NEW_LINE> <INDENT> secondsSince1970 = (datetime.now() - self.epochStart).total_seconds <NEW_LINE> if secondsSince1970 > self.getNotAfter()/1000: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Check if the certificate end date is in the past :return: True if the certificate has expired :rtype: boolean
625941e44e4d5625662d47d7
def testBasic(self): <NEW_LINE> <INDENT> config = self.makePfsConfig() <NEW_LINE> dirName = os.path.splitext(__file__)[0] <NEW_LINE> if not os.path.exists(dirName): <NEW_LINE> <INDENT> os.makedirs(dirName) <NEW_LINE> <DEDENT> filename = os.path.join(dirName, config.filename) <NEW_LINE> if os.path.exists(filename): <NEW...
Test basic operation of PfsConfig
625941e4a05bb46b383ecc22
def shutdown(self, timeout=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super().shutdown(timeout) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.drmaa_session.close()
Cleanup DRMAA session and call shutdown of parent.
625941e416aa5153ce36287c
def hasObject(self,objetType): <NEW_LINE> <INDENT> for objetInstance in self.__objects: <NEW_LINE> <INDENT> if isinstance(objetInstance,objetType): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False
Methode de verification d'un type d'objet dans la liste self.__objects :return: True or False
625941e463b5f9789fde74ea
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> cache.delete(FactoidType.FACTS_IDS % self.type.id) <NEW_LINE> super(Factoid, self).save(*args, **kwargs)
Clean the cache when a factoid has been modified or created
625941e43346ee7daa2b3173
def aggregate_counts(points, counts, bins, right=False): <NEW_LINE> <INDENT> points, counts, bins = np.array(points), np.array(counts), np.array(bins) <NEW_LINE> if points.shape != counts.shape: <NEW_LINE> <INDENT> raise ValueError('points and counts must have the same shape') <NEW_LINE> <DEDENT> if (len(bins.shape) !=...
Make a histogram of hit counts. This is a good way to dilute the bin boundaries of a histogram if the new boundaries do not coincide with the old ones. Note that a histogram has one more edges than the number of points listed in the hit counts. :param points: observed values, shape (n,) :param counts: number of occurre...
625941e430c21e258bdfa8a5
def __init__(self, A_init={}, B_init={}, pi_init={}, tags=[], words=[], obs_lst=[], mode='train'): <NEW_LINE> <INDENT> self.mode = mode <NEW_LINE> if self.mode == 'test': <NEW_LINE> <INDENT> self.load() <NEW_LINE> self.get_log_hmm() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.A = A_init <NEW_LINE> self.B = B_ini...
This is initializer function for HMM tagger. If mode is train then it accepts initial trasition probabilities, initial emission probabilities and initial state distribution to initialize an HMM. IF mode is test then it loads parameters from presaved model and converts it into log space to do viterbi decoding.
625941e494891a1f4081beb0
def p_global_modifier_opt_empty(p): <NEW_LINE> <INDENT> p[0] = []
global-modifier-opt : empty
625941e46fece00bbac2db48
def reverse(self, x): <NEW_LINE> <INDENT> if x <= 2**31 -1 and x >= -2**31: <NEW_LINE> <INDENT> strx = str(x)[::-1] <NEW_LINE> if strx[-1] == '-':strx = '-' + strx[:-1] <NEW_LINE> if int(strx) <= 2**31 -1 and int(strx) >= -2**31:return int(strx) <NEW_LINE> else:return 0 <NEW_LINE> <DEDENT> else:return 0
:type x: int :rtype: int
625941e4283ffb24f3c55d02
def multifileSMA(reg,basedir,subjects='all',windowsz=1,gravity=9.81): <NEW_LINE> <INDENT> fileprefix = './data/SMA' <NEW_LINE> smafiles = {} <NEW_LINE> vectorfiles = {} <NEW_LINE> for subject,files in reg.items(): <NEW_LINE> <INDENT> if subjects != 'all': <NEW_LINE> <INDENT> if subject not in subjects: <NEW_LINE> <INDE...
for files in rdf, perhaps limited to subject , calculate the SMA values per window size (Secs) output to disk
625941e48e05c05ec3eea77c
def api_last_tested_repo_post_with_http_info(self, params, **kwargs): <NEW_LINE> <INDENT> all_params = ['params'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> p...
Get the last tested repo since a specific time (optionally for a CI job), and add an "in progress" entry in the CI job table for this. If a job_id is specified, the order of precedence for the repo returned is: - The last tested repo within that timeframe for that CI job. - The last tested repo within that timeframe...
625941e4be8e80087fb21041
def _job_resume(self, job): <NEW_LINE> <INDENT> if job._state in [c.DONE, c.FAILED, c.CANCELED, c.NEW, c.RUNNING]: <NEW_LINE> <INDENT> raise rse.IncorrectState._log(self._logger, "Could not resume job %s [%s]" % (job._id, job._state)) <NEW_LINE> <DEDENT> rm, pid = self._adaptor.parse_id(job._id) <NEW_LINE> ret, out...
Attempt to resume a job with commandline scontrol. Raise exception when unsuccessful.
625941e4cc0a2c11143dd296
def yiq2rgb(imYIQ): <NEW_LINE> <INDENT> inv_yiq = np.linalg.inv(YIQ) <NEW_LINE> r = np.inner(imYIQ, inv_yiq[CHAN_1]) <NEW_LINE> g = np.inner(imYIQ, inv_yiq[CHAN_2]) <NEW_LINE> b = np.inner(imYIQ, inv_yiq[CHAN_3]) <NEW_LINE> return np.dstack((r, g, b))
Converts a YIQ grayscale image to RGB color image :param imYIQ: An array containing the original image data :return: An array containing the modified image data
625941e456b00c62f0f14a60
def pexpire(self, name, time, callback=None): <NEW_LINE> <INDENT> if isinstance(time, datetime.timedelta): <NEW_LINE> <INDENT> ms = int(time.microseconds / 1000) <NEW_LINE> time = time.seconds + time.days * 24 * 3600 * 1000 + ms <NEW_LINE> <DEDENT> self._execute_command('PEXPIRE', name, time, callback=callback)
Set an expire flag on key ``key`` for ``time`` milliseconds. ``time`` can be represented by an integer or a Python timedelta object.
625941e4be7bc26dc91cd9fd
def update(self): <NEW_LINE> <INDENT> self.distance += self.speed <NEW_LINE> self.x_pos += math.cos(math.radians(360-self.angle)) * self.speed <NEW_LINE> self.y_pos += math.sin(math.radians(360-self.angle)) * self.speed <NEW_LINE> self.center = [int(self.x_pos + 50), int(self.y_pos + 50)] <NEW_LINE> self.rotate_surface...
Updates the car itself
625941e4cc0a2c11143dd297
def test_not_in_navigation_num_queries(self): <NEW_LINE> <INDENT> a = create_page('A', 'nav_playground.html', 'en', published=True, in_navigation=True, reverse_id='a') <NEW_LINE> b = create_page('B', 'nav_playground.html', 'en', parent=a, published=True, in_navigation=True) <NEW_LINE> c = create_page('C', 'nav_playgrou...
Test for issue 521 Build the following tree: A |-B |-C \-D (not in nav)
625941e44f6381625f114e40
def iou(a, b): <NEW_LINE> <INDENT> a, b = set(a.lower().strip()), set(b.lower().strip()) <NEW_LINE> return len(a & b) / len(a | b)
Crude character vector overlap measure of string similarity >>> iou('Hello', 'World') 0.285...
625941e4442bda511e8be817
def synthesize(self, phonemes_list : List[str]) -> bytes: <NEW_LINE> <INDENT> pho_list = PhonemeList([]) <NEW_LINE> for pho in phonemes_list: <NEW_LINE> <INDENT> if pho in self.voice.phonems.VOWELS: <NEW_LINE> <INDENT> new_phoneme = Phoneme(name=pho, duration=int(torch.normal(*self.stats.consonants_stats[pho]["duration...
converts a list of phonemes (only their names) to a wav file
625941e4d164cc6175783154
def get_login_info(xml_file_path): <NEW_LINE> <INDENT> login_info = {} <NEW_LINE> tree = ET.parse(xml_file_path) <NEW_LINE> root = tree.getroot() <NEW_LINE> login_info['RestURL'] = root.findtext('Storage/RestURL').strip() <NEW_LINE> for key in ['UserName', 'UserPassword']: <NEW_LINE> <INDENT> node = root.find('Storage/...
Get login IP, user name and password from config file.
625941e445492302aab5e6cc
def crosses(D, ep): <NEW_LINE> <INDENT> a, b, c, d = [D.index(v) for v in (ep[0][0], ep[0][1], ep[1][0], ep[1][1])] <NEW_LINE> return (a < c < b < d) or (b < c < a < d) or (a < d < b < c) or (b < d < a < c) or (c < a < d < b) or (d < a < c < b) or (c < b < d < a) or (d < b < c < a)
checks if edge-pair ep crosses in drawing D
625941e415baa723493c437d
def getLeft(self): <NEW_LINE> <INDENT> return self.left
:return:
625941e4ff9c53063f47c5f6
def fill_assignment(self, assignment): <NEW_LINE> <INDENT> raise NotImplementedError()
@brief Fill assignment with data if it has proper ID The function actually gets assignment by ID :param assignment: :return:
625941e4fb3f5b602dac3a9c
def make_pdf_fprime_black_swaption( init_swap_rate, swap_annuity, option_maturity, vol): <NEW_LINE> <INDENT> assert(vol > 0.0) <NEW_LINE> def pdf_fprime(option_strike): <NEW_LINE> <INDENT> return function.black_payers_swaption_value_third_by_strike( init_swap_rate=init_swap_rate, option_strike=option_strike, swap_annui...
make_pdf_fprime_black_swaption return first derivative of p.d.f. of black swaption. See :py:func:`make_pdf_black_swaption`. .. math:: \Phi_{S}^{\prime}(k) := \frac{\partial^{3}}{\partial K^{3}} V_{\mathrm{payers}}(0, S; K, A, T) where :math:`S` is `init_swap_rate`, :math:`S` is `swap_annuity`, :math:`...
625941e44527f215b584c857
def doChangeDDL(self, operator_id, deadline): <NEW_LINE> <INDENT> if self.progress <= 0: <NEW_LINE> <INDENT> raise Exception("Project is not in progress!") <NEW_LINE> <DEDENT> current_phase = self.current_phase() <NEW_LINE> current_phase.deadline_date = deadline <NEW_LINE> self.deadline_date = deadline <NEW_LINE> if de...
change the current ddl.
625941e463f4b57ef0001512
def myint(s): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> v = int(s) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> v = s <NEW_LINE> <DEDENT> return v
Protected version of int()
625941e4851cf427c661a911
def extract_rows_csr(matrix, rows): <NEW_LINE> <INDENT> if not isinstance(matrix, csr_matrix): <NEW_LINE> <INDENT> matrix = csr_matrix(matrix) <NEW_LINE> <DEDENT> if len(rows) == 0: <NEW_LINE> <INDENT> return csr_matrix(matrix.shape) <NEW_LINE> <DEDENT> indptr = np.zeros(matrix.indptr.shape, dtype=np.int32) <NEW_LINE> ...
Parameters ---------- matrix : (sparse) csr_matrix rows : list of row ids Returns ------- matrix_: (sparse) csr_matrix Transformed by extracting the desired rows from `matrix`
625941e4004d5f362079a736
def lookup_tvdb(self, searchtitle, channel, manual_select=False, tempmanualselect=False): <NEW_LINE> <INDENT> tvdb_match = None <NEW_LINE> searchtitle = searchtitle.lower() <NEW_LINE> tvdb_result = self._mutils.thetvdb.search_series(searchtitle, True) <NEW_LINE> searchchannel = channel.lower().split("hd")[0].replace(" ...
helper to select a match on tvdb
625941e4656771135c3ebc78
def read(self): <NEW_LINE> <INDENT> f = open(self._capem, "r") <NEW_LINE> try: <NEW_LINE> <INDENT> return f.read() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> f.close()
Read CA.pem file and return content
625941e4d4950a0f3b08c74e
def post(self, request): <NEW_LINE> <INDENT> form_data = request.POST <NEW_LINE> measurement_form = forms.IngestionMeasurementForm(form_data) <NEW_LINE> if not measurement_form.is_valid(): <NEW_LINE> <INDENT> for error in measurement_form.errors: <NEW_LINE> <INDENT> return JsonResponse({'status': "ERROR", 'message': me...
Valid a form using POST data and return any error messages Validates an IngestionMeasurementForm and returns any errors
625941e4be8e80087fb21042
def check_if_user_has_finished(): <NEW_LINE> <INDENT> ok_to_finish = True <NEW_LINE> user_input_accepted = False <NEW_LINE> while not user_input_accepted: <NEW_LINE> <INDENT> user_input = input("Do you want to finish (y/n): ").lower() <NEW_LINE> if user_input == 'y': <NEW_LINE> <INDENT> user_input_accepted = True <NEW_...
checks that the user wants to finish or not. Perform some verification of the input.
625941e4a17c0f6771cbe455
def test_flow_aggregate_threshold_pass(self): <NEW_LINE> <INDENT> result = flow_aggregate_threshold() <NEW_LINE> self.assertTrue(result)
Test Flow Aggregate Threshold
625941e45fcc89381b1e1ac6
def getCurrentLatLong(): <NEW_LINE> <INDENT> currentLocation = getJSONFromDataFile('location.data') <NEW_LINE> if str(currentLocation['track']) == 'nan' or str(currentLocation['altitude']) == 'nan' or str(currentLocation['longitude']) == '0.0' or str(currentLocation['latitude']) == '0.0' or str(currentLocation['climb']...
get the current lat/long from location data
625941e423849d37ff7b3491
def SolvePositionConstraints(self, *args): <NEW_LINE> <INDENT> return _Box2D.b2LineJoint_SolvePositionConstraints(self, *args)
SolvePositionConstraints(b2LineJoint self, float32 baumgarte) -> bool
625941e416aa5153ce36287d
def test_sql_interp_string(self): <NEW_LINE> <INDENT> full_name = 'John Doe' <NEW_LINE> sql, bind = self.sqli.interp("SELECT * FROM table WHERE full_name =", self.sqli.esc(full_name)) <NEW_LINE> self.assertEquals(sql, "SELECT * FROM table WHERE full_name = ?") <NEW_LINE> self.assertEquals(bind, ('John Doe',))
Test interpolating a string.
625941e40a366e3fb873ec23
def validate_name(name, MAX_LEN_NAME=255): <NEW_LINE> <INDENT> if len(name) > MAX_LEN_NAME: <NEW_LINE> <INDENT> raise InputError("Name exceeds limit of %d chars." % MAX_LEN_NAME)
raises an InputError in case of invalid name
625941e44d74a7450ccd45c9
def __init__(self): <NEW_LINE> <INDENT> super(Memento, self).__init__() <NEW_LINE> self._object = None
Constructor of Memento and default values will be initialised.
625941e4b545ff76a891421a
def RenderShadowCompareBefore(shadowMapID, textureMatrix): <NEW_LINE> <INDENT> glEnable(GL_TEXTURE_2D) <NEW_LINE> glBindTexture(GL_TEXTURE_2D, shadowMapID) <NEW_LINE> glEnable(GL_TEXTURE_GEN_S) <NEW_LINE> glEnable(GL_TEXTURE_GEN_T) <NEW_LINE> glEnable(GL_TEXTURE_GEN_R) <NEW_LINE> glEnable(GL_TEXTURE_GEN_Q) <NEW_LINE> g...
eval where draw shadows using ARB extension
625941e482261d6c526ab8ab