code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def is_password(value): <NEW_LINE> <INDENT> return True
Maybe not necesary
625941e126068e7796caf097
def get_server_status_code(url): <NEW_LINE> <INDENT> pcs = urlparse.urlparse(url) <NEW_LINE> try: <NEW_LINE> <INDENT> conn = httplib.HTTPConnection(host=pcs.hostname, port=pcs.port) <NEW_LINE> conn.request('HEAD', pcs.path) <NEW_LINE> return conn.getresponse().status <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <IN...
Download just the header of a URL and return the server's status code.
625941e1e64d504609d74bf2
def __init__(self, name, playtime, killcount, killedcount): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.playtime = playtime <NEW_LINE> self.killcount = killcount <NEW_LINE> self.killedcount = killedcount <NEW_LINE> self.starttime = 0
Instantiate a Player statistics tracker. Arguments: name - Name of the player. playtime - Accumulated play time in seconds. killcount - Number of kills the player has made. killedcount - Number of deaths the player has experienced.
625941e1a8ecb033257d347e
def heuristic(position, goal): <NEW_LINE> <INDENT> return np.sum(goal - position)
Heuristic is Manhattan Distance (sum of number of rows + columns between location and goal)
625941e16e29344779a629c3
def lambda_handler(event, context): <NEW_LINE> <INDENT> print(json.dumps(event)) <NEW_LINE> return { "exit_code": 0, "message": "This function has finished successfully.", "result_detail": { "return1": "returned_value1", "return2": "returned_value2" } }
Sample Lambda function placed into a Step Function State Machine. Parameters ---------- event: dict, required context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ Custom Output Format: dict ...
625941e14a966d76dd5513c5
def __init__(self, format_name=None): <NEW_LINE> <INDENT> self._format_name = None <NEW_LINE> if format_name: <NEW_LINE> <INDENT> self.format_name = format_name
Set the default *format_name*.
625941e1d58c6744b4258011
def ask_subtraction_levelUp(handler_input): <NEW_LINE> <INDENT> random_state = get_random_state(data_1.SUBTRACTION_LIST) <NEW_LINE> random_property = get_random_state_property() <NEW_LINE> attr = handler_input.attributes_manager.session_attributes <NEW_LINE> attr["quiz_item"] = random_state <NEW_LINE> attr["quiz_attr"]...
Get a random state and property, return question about it.
625941e191af0d3eaac9bdcf
def test_parseDefaultFilename(self): <NEW_LINE> <INDENT> conf = inetdconf.ServicesConf() <NEW_LINE> conf.defaultFilename = self.servicesFilename1 <NEW_LINE> conf.parseFile() <NEW_LINE> self.assertEqual(conf.services, { ("http", "tcp"): 80, ("http", "udp"): 80, ("http", "sctp"): 80, ("www", "tcp"): 80, ("www", "udp"): 8...
Services are parsed from default filename.
625941e294891a1f4081be5e
def replace_leading_tabs(data): <NEW_LINE> <INDENT> wrong = [('------', '------'*4), ('wrong'.rjust(12), ' lines'), ('------', '------'*4)] <NEW_LINE> out = [] <NEW_LINE> for key, line in enumerate(data.splitlines()): <NEW_LINE> <INDENT> if not line.lstrip(): <NEW_LINE> <INDENT> out.append('') <NEW_LINE> continue <NEW_...
-replace leading tabs to spaces, and detect if number of spaces is divided by 4 -whitesign-lines are converted to newlines
625941e10a50d4780f667248
def __delete__(self, inst): <NEW_LINE> <INDENT> raise NotDeletableError(self.name())
Delete our property
625941e2d6c5a10208144401
def jsonable(self): <NEW_LINE> <INDENT> return [self.method, self.call_count, self.non_call_count, [x for x in self.children.values() if not x.ignore]]
Helper method for returning the object in form suitable for conversion to JSON in format expected by the data collector. Any children which are being ignored due to having been pruned are discarded at this point.
625941e292d797404e30453e
def get_param_as_bool(self, name, required=False, store=None, blank_as_true=False): <NEW_LINE> <INDENT> params = self._params <NEW_LINE> if name in params: <NEW_LINE> <INDENT> val = params[name] <NEW_LINE> if isinstance(val, list): <NEW_LINE> <INDENT> val = val[-1] <NEW_LINE> <DEDENT> if val in TRUE_STRINGS: <NEW_LINE>...
Return the value of a query string parameter as a boolean The following boolean strings are supported:: TRUE_STRINGS = ('true', 'True', 'yes', '1', 'on') FALSE_STRINGS = ('false', 'False', 'no', '0', 'off') Args: name (str): Parameter name, case-sensitive (e.g., 'detailed'). Keyword Args: required (...
625941e2009cb60464c63762
def add_meta(self, rule_name, name, value, meta_type=None): <NEW_LINE> <INDENT> self._no_rule_name_exception_handler(rule_name) <NEW_LINE> if not meta_type: <NEW_LINE> <INDENT> if value is True or value is False: <NEW_LINE> <INDENT> meta_type = "bool" <NEW_LINE> <DEDENT> elif isinstance(value, int): <NEW_LINE> <INDENT>...
Add a meta key/value pair to the specified rule_name Args: rule_name (str): the rule_name to add the meta to name (str): the name of the meta key value (str/int/bool): the value to go in the metadata meta_type (str, optional): the type of the meta data, which will be determined by the fu...
625941e2bde94217f36831a0
def write(self): <NEW_LINE> <INDENT> self.data.append(self.current) <NEW_LINE> if self.renew: <NEW_LINE> <INDENT> if self.file!=None: <NEW_LINE> <INDENT> self.file.close() <NEW_LINE> <DEDENT> self.file=file(self.name,"w") <NEW_LINE> self.writer=csv.DictWriter(self.file,self.headers) <NEW_LINE> self.writer.writerows(sel...
Writes a line to disk and starts a new one
625941e2462c4b4f79d1da82
def compile_args(self, c_fname): <NEW_LINE> <INDENT> return self.cflags + ['-c', c_fname]
Construct args for compile command.
625941e2ad47b63b2c50a331
def validate_sample_sheet(sample_sheet_file): <NEW_LINE> <INDENT> csv_reader = common.get_csv_reader(sample_sheet_file) <NEW_LINE> v_res = model.ValidationResult() <NEW_LINE> all_data_headers_found = False <NEW_LINE> data_sect_found = False <NEW_LINE> header_sect_found = False <NEW_LINE> reads_sect_found = False <NEW_L...
Checks if the given sample_sheet_file can be parsed Requires [Header] because it contains Workflow Requires [Data] for creating Sample objects and requires Sample_ID, Sample_Name, Sample_Project and Description table headers arguments: sample_sheet_file -- path to SampleSheet.csv returns ValidationResult ...
625941e2cc0a2c11143dd245
def get_efmtool_efms(inputfile): <NEW_LINE> <INDENT> ifile = open(inputfile, "r") <NEW_LINE> compressed_efms = [] <NEW_LINE> for line in ifile: <NEW_LINE> <INDENT> cmp_efm = [float(val) for val in line.strip().split()] <NEW_LINE> compressed_efms.append(cmp_efm) <NEW_LINE> <DEDENT> return compressed_efms
Entry point for get_data for efmtool. Reads efmtool output file and stores compressed efms in a list of lists. :param inputfile: efmtool output file :return: list compressed_efms
625941e2de87d2750b860149
def addSuccess(self, msg): <NEW_LINE> <INDENT> self.result.addInfo(self, msg)
Register a success message to the test result. Args: msg (str): success message to add to the result.
625941e2be383301e01b5832
def charger_dune_chaine(self, chaine): <NEW_LINE> <INDENT> for vieux_pats in self.id_patrouilleurs: <NEW_LINE> <INDENT> self.id_patrouilleurs[vieux_pats] = None <NEW_LINE> <DEDENT> numero_de_ligne = 0 <NEW_LINE> patrouilleur = False <NEW_LINE> for information_quart in chaine.split("\n"): <NEW_LINE> <INDENT> if informat...
Vide le damier actuel et le remplit avec les informations reçues dans une chaîne de caractères. Le format de la chaîne est expliqué dans la documentation de la méthode convertir_en_chaine. Args: chaine (str): La chaîne de caractères.
625941e2711fe17d82542716
def list_batch(id_or_name=None): <NEW_LINE> <INDENT> batches = DataStore.get_batch_list(id_or_name) <NEW_LINE> if batches is None: <NEW_LINE> <INDENT> print("No batches idendified by {} could be found in the database...".format(id_or_name)) <NEW_LINE> exit() <NEW_LINE> <DEDENT> if batches: <NEW_LINE> <INDENT> print('--...
List Details of Batches from local database
625941e2be8e80087fb20ff1
@register_object_checker() <NEW_LINE> def show_discipline_groups_permission(permission, user, view): <NEW_LINE> <INDENT> discipline = view.get_discipline() <NEW_LINE> if not discipline.was_group_provided and user != discipline.teacher: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if user in discipline.students....
Permission that allows only students, monitors and teacher of specific discipline to see discipline groups features.
625941e2ff9c53063f47c5a5
def __init__(self, env): <NEW_LINE> <INDENT> Callback.__init__(self, env) <NEW_LINE> self._cb_type_string = "tuning" <NEW_LINE> self._cb_set_function = _internal._procedural.settuningcallbackfunc
non-public
625941e2293b9510aa2c3645
def by_id(self, id: int) -> object: <NEW_LINE> <INDENT> return Detection(self._get_by_id('detections', id))
Searches for detection by id Parameters -------- id : int detection id
625941e29b70327d1c4e118a
def __enter__(self): <NEW_LINE> <INDENT> self.start() <NEW_LINE> return self
Enters server context manager.
625941e2097d151d1a22320b
def endEric4ApiParams(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.project.pdata["DOCUMENTATIONPARMS"]["ERIC4API"] = self.stack[-1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass
Handler method for the "Eric4ApiParams" end tag.
625941e2187af65679ca54d4
def random_regression(N, dim): <NEW_LINE> <INDENT> X_train = numpy.empty((N, dim)) <NEW_LINE> X_train[:, :] = rand(N, dim)[:, :] <NEW_LINE> eps = (randn(N, dim) - 0.5) / 4 <NEW_LINE> X_train_eps = X_train + eps <NEW_LINE> y_train = X_train_eps.sum( axis=1) + numpy.power(X_train_eps / 3, 2).sum(axis=1) <NEW_LINE> return...
Returns data for a binary classification problem (linear) with *N* observations and *dim* features. @param N number of observations @param dim number of features @return *X, y* .. runpython:: :showcode: from pymlbenchmark.datasets import random_regression X, y = random_regre...
625941e2bf627c535bc13583
def plot_station(station,POtype,**kwarg): <NEW_LINE> <INDENT> plt.figure(figsize=(17,8)) <NEW_LINE> ax=plt.subplot(2,3,(1,3)) <NEW_LINE> ax.errorbar(station.PO.index.to_pydatetime(), station.PO, yerr=station.POunc, ecolor="black", elinewidth=1, fmt="b-o", markersize=6, label="Obs.", zorder=1) <NEW_LINE> ax.plot_date(st...
Plot the time series obs & recons, the scatter plot obs/recons, the intrinsic PO and the contribution of the sources/species.
625941e2aad79263cf390dfa
def knapsack_01(values, weights, W): <NEW_LINE> <INDENT> n = len(values) <NEW_LINE> dp = [[0 for i in range(W+1)] for j in range(n+1)] <NEW_LINE> for i in range(1,n+1): <NEW_LINE> <INDENT> for j in range(W+1): <NEW_LINE> <INDENT> if weights[i-1] > j: <NEW_LINE> <INDENT> dp[i][j] = dp[i-1][j] <NEW_LINE> <DEDENT> else: <...
Parameters ---------- values : list of ints value of every item. weights : list of ints weight of item. W : int total weight of knapsack. - all int values are >= 0 Returns int ------- Returns maximum possible value of subset which total weight should be <= W.
625941e207f4c71912b11838
def test_rate_limit_failure(self): <NEW_LINE> <INDENT> self.log.debug("Testing rate limit failure...") <NEW_LINE> api = self.injectors["api"]["malformed_limits"] <NEW_LINE> network = self.injectors["network"]["malformed_limits"] <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> twitter( keys=self.retriev...
Failure to retrieve a rate limit is fatal.
625941e23d592f4c4ed1d417
def int_to_physical(self, i): <NEW_LINE> <INDENT> return self.evaluator.int_to_physical(i)
Evaluate computation method INT ==> PHYS Parameters ---------- x: int or float, scalar or array
625941e25e10d32532c5f2d9
def singleNumber(self, nums): <NEW_LINE> <INDENT> unique_nums = set() <NEW_LINE> unique_nums.add(nums[0]) <NEW_LINE> for n in nums[1:]: <NEW_LINE> <INDENT> if n in unique_nums: <NEW_LINE> <INDENT> unique_nums.remove(n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unique_nums.add(n) <NEW_LINE> <DEDENT> <DEDENT> return ...
:type nums: List[int] :rtype: int
625941e2eab8aa0e5d26df0d
def libvlc_audio_equalizer_get_preamp(p_equalizer): <NEW_LINE> <INDENT> f = _Cfunctions.get('libvlc_audio_equalizer_get_preamp', None) or _Cfunction('libvlc_audio_equalizer_get_preamp', ((1,),), None, ctypes.c_float, AudioEqualizer) <NEW_LINE> return f(p_equalizer)
Get the current pre-amplification value from an equalizer. @param p_equalizer: valid equalizer handle, must not be None. @return: preamp value (Hz). @version: LibVLC 2.2.0 or later.
625941e24e696a04525c9800
def expire_broadcast(self, cutoff=None, **kwargs): <NEW_LINE> <INDENT> point_strings = [] <NEW_LINE> cutoff_point = None <NEW_LINE> if cutoff is not None: <NEW_LINE> <INDENT> cutoff_point = get_point(str(cutoff)) <NEW_LINE> <DEDENT> with self.lock: <NEW_LINE> <INDENT> for point_string in self.broadcasts: <NEW_LINE> <IN...
Clear all broadcasts targeting cycle points earlier than cutoff.
625941e27b180e01f3dc4baa
def get_open_url( session: ClientSession, goptions: GOptions, datatype: str, element: str) -> str: <NEW_LINE> <INDENT> opener: Union[str, Callable] = OPEN_URL.get(datatype) <NEW_LINE> if opener is None: <NEW_LINE> <INDENT> raise BadDingo(f"Unsupported type for open: {datatype}") <NEW_LINE> <DEDENT> if callable(opener):...
Given a client configuration, datatype, and element identifier, produce a URL referencing the hub or topdir path for that record. :param session: an active koji client session :param goptions: koji client options :param datatype: name of the data type :param element: identifier for an element of the given data type...
625941e266673b3332b92445
def cleanGames(_games): <NEW_LINE> <INDENT> _games = _games.loc[np.abs(_games['GameVegasLine']) <= 50] <NEW_LINE> _games.rename(inplace=True, columns={ 'GameDate': 'dataPriorTo' }) <NEW_LINE> _games['dataPriorTo'] = pd.to_datetime(_games['dataPriorTo']) <NEW_LINE> _games['Tm_isHome'] = np.where(_games['TmLoc'] == 'H', ...
De-dupes game records, keeping only home teams and lower-name neutral games, rename a few columns, remove outlier lines, and change datatypes. Args: _games (DataFrame): game data Returns: DataFrame: Cleaned game data
625941e2460517430c394530
def filter_bears(language): <NEW_LINE> <INDENT> return list(apply_filters({'language': (language,)}, None)[0]['cli'])
Filter bears by language. :param language: The language to filter with. :return: A list of bears.
625941e2de87d2750b86014a
@sensitive_variables() <NEW_LINE> def sign_data(data_string): <NEW_LINE> <INDENT> message = bytes(data_string, 'utf-8') <NEW_LINE> secret = bytes(settings.CS_SECRET_KEY, 'utf-8') <NEW_LINE> hash = hmac.new(secret, message, hashlib.sha256) <NEW_LINE> return base64.b64encode(hash.digest())
Sign with HMAC sha256 and base64 encode
625941e28e05c05ec3eea72c
def Set_5GNR_TM(self, file): <NEW_LINE> <INDENT> self.query(f'SOUR1:BB:NR5G:SETT:TMOD:DL "{file}";*OPC?')
NR-FR1-TM1_1__FDD_100MHz_30kHz
625941e215fb5d323cde0ec8
def default_render_failure(request, message, status=403, template_name='fboauth/failure.html'): <NEW_LINE> <INDENT> data = render_to_string( template_name, dict(message=message), context_instance=RequestContext(request)) <NEW_LINE> return HttpResponse(data, status=status)
Render an error page to the user
625941e2e8904600ed9f22e6
def get_placeholder(self): <NEW_LINE> <INDENT> val = self.bus.read_byte_data( self.device_address, self.REGISTER_PLACEHOLDER ) <NEW_LINE> return val
An 8-bit register
625941e221a7993f00bc80aa
def read_hostfile(f="hosts.txt"): <NEW_LINE> <INDENT> env.hosts = open(f, 'r').readlines()
get the env.hosts from hosts.txt file in the same directory
625941e2b545ff76a89141c9
def get_section(lst, name): <NEW_LINE> <INDENT> begin = lst.index("\\section*{{{}}}".format(name)) <NEW_LINE> item_start = begin+lst[begin:].index("\\item ") <NEW_LINE> item_end = item_start+lst[item_start:].index("\\end{list}") <NEW_LINE> section = lst[item_start:item_end] <NEW_LINE> if "\\newpage" in section: <NEW_LI...
Grab a named section and split into pages and items.
625941e2090684286d50f09e
def mandelbrot(c): <NEW_LINE> <INDENT> real, imag = mapc((c[1], c[0])) <NEW_LINE> depth = 0 <NEW_LINE> z_real = 0 <NEW_LINE> z_imag =0 <NEW_LINE> c_real = real <NEW_LINE> c_imag = imag <NEW_LINE> dist = z_real * z_real + z_imag * z_imag <NEW_LINE> while (depth < args.recurse_depth) and (dist < 4): <NEW_LINE> <INDENT> d...
mandelbrot Calculate the number of iterations until we are certain that the value real + imag * i will diverge to infinity (real^2 + imag^2 > 4). If maximum recursion depth is exceeded, return the number of iterations so far. This function is implemented iteratively for performance reasons. Python has a relatively l...
625941e229b78933be1e5a5b
def set_alpha(self, *args, **kwargs): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_pll_carriertracking_cc_sptr_set_alpha(self, *args, **kwargs)
set_alpha(self, float alpha) Set the loop gain alpha. Set's the loop filter's alpha gain parameter. This value should really only be set by adjusting the loop bandwidth and damping factor.
625941e22c8b7c6e89b35b72
@main.route("/<project_id>/invite", methods=["GET", "POST"]) <NEW_LINE> def invite(): <NEW_LINE> <INDENT> form = InviteForm() <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> if form.validate(): <NEW_LINE> <INDENT> message_body = render_localized_template("invitation_mail") <NEW_LINE> message_title = _( "You...
Send invitations for this particular project
625941e256b00c62f0f14a10
def validation(self, obj, input_line, regex, orientation, errormsg): <NEW_LINE> <INDENT> criteria = Restriction(regex, orientation) <NEW_LINE> if criteria.validate(input_line): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.input_error(self, obj, errormsg) <NEW_LINE> return False
Validate a line of input given a regex and orientation for a Restriction and an error message to print on failure.
625941e28a43f66fc4b54415
def facingEast(self): <NEW_LINE> <INDENT> raise NotImplementedError("facingEast not yet implemented.")
Return true if this robot is facing east.
625941e232920d7e50b28587
def receive(self, receivedBytes): <NEW_LINE> <INDENT> byteQueue = collections.deque(receivedBytes) <NEW_LINE> while len(byteQueue) > 0 and self.state != WebSocketClient.WebSocketRecvState.STATE_DONE: <NEW_LINE> <INDENT> b = byteQueue.popleft() <NEW_LINE> if self.state == WebSocketClient.WebSocketRecvState.STATE_TYPE: <...
Processes some bytes into this object. Returns the unprocessed bytes. This operates as a state machine on the bytes as though they are an array. It processes each byte individually and changes the state depending on the value of the byte. In the case where there aren't enough bytes to complete a receive sequence (goin...
625941e296565a6dacc8fa7f
def test_decode_properties(self): <NEW_LINE> <INDENT> pdu = A_ASSOCIATE_AC() <NEW_LINE> pdu.decode(a_associate_ac) <NEW_LINE> assert pdu._reserved_aec == b'ECHOSCU ' <NEW_LINE> assert pdu._reserved_aet == b'ANY-SCP ' <NEW_LINE> assert pdu.calling_ae_title == b'ECHOSCU ' <NEW_LINE> assert pdu.cal...
Check decoding produces the correct property values.
625941e27c178a314d6ef81a
def evaluate(prev_node, nodes): <NEW_LINE> <INDENT> best = nodes[0] <NEW_LINE> best_index = abs(best.node_index - prev_node.node_index) <NEW_LINE> for n in nodes: <NEW_LINE> <INDENT> node_diff = abs(n.node_index - prev_node.node_index) <NEW_LINE> if node_diff < best_index and node_diff > 0: <NEW_LINE> <INDENT> best = n...
Try to pick the node with the lowest non zero distance away from previous NOTE: Problem if the first node is 0 distance
625941e255399d3f05588a6a
def predict_proba(self, X): <NEW_LINE> <INDENT> if getattr(X, "dtype", None) != DTYPE or X.ndim != 2: <NEW_LINE> <INDENT> X = array2d(X, dtype=DTYPE) <NEW_LINE> <DEDENT> n_samples, n_features = X.shape <NEW_LINE> if self.tree_ is None: <NEW_LINE> <INDENT> raise Exception("Tree not initialized. Perform a fit first.") <N...
Predict class probabilities of the input samples X. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The...
625941e245492302aab5e67c
def meshgrid(*args, **kwargs): <NEW_LINE> <INDENT> return tensorflow.meshgrid(*args, **kwargs)
See https://www.tensorflow.org/api_docs/python/tf/meshgrid .
625941e2adb09d7d5db6cb42
def run(self, *args, **kwargs): <NEW_LINE> <INDENT> logger.info('running jobs in a build sequence.') <NEW_LINE> for job in self.stage: <NEW_LINE> <INDENT> logger.info('running {0}'.format(job[0].__name__)) <NEW_LINE> job[0](*job[1]) <NEW_LINE> <DEDENT> return True
Runs all jobs in :class:~stages.BuildSteps` in the order they were added to the object. Ignores all arguments.
625941e260cbc95b062c68f8
def get_front(self): <NEW_LINE> <INDENT> return self.left.get()[:self.channel//2]+ self.right.get()[:self.channel//2]
Front Sensor are 1, 2, 3 ...
625941e2379a373c97cfaefb
def __init__(self, root: Optional[object], left: Optional['BinaryTree'], right: Optional['BinaryTree']) -> None: <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> self._root, self._left, self._right = None, None, None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._root = root <NEW_LINE> self._left, self._ri...
Initialise a new binary tree with the given values. If <root> is None, this represents an empty BinaryTree (<left> and <right> are ignored in this case). Precondition: if <root> is not None, then neither <left> nor <right> are None.
625941e29f2886367277ac3f
def test_calling(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> r = Rectangle() <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> r = Rectangle(1) <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> r = Rectangle(1, 2, 3, 4, 5, 6)
Checks the calling of Rectangle
625941e2be7bc26dc91cd9ae
def report(self, differencers=None, truncate_to=0): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for a in self._added: <NEW_LINE> <INDENT> results.append("Added {}.".format(a)) <NEW_LINE> <DEDENT> for r in self._removed: <NEW_LINE> <INDENT> results.append("Removed {}.".format(r)) <NEW_LINE> <DEDENT> for c in self._chang...
Returns a string report of diffs. Additions and removals are identified by proto path. Changes in value are reported as path: old_value -> new_value by default, though this can be customized via the differencers argument. Args: differencers: Iterable of callable(path, proto_a, proto_b) -> str or None If a strin...
625941e28e7ae83300e4b382
def set_random_glcolor(n): <NEW_LINE> <INDENT> if ( "gl_color" in n.knobs() and not n["gl_color"].value() and not n.name().startswith("_") ): <NEW_LINE> <INDENT> color = colorsys.hsv_to_rgb(random.random(), 0.8, 1) <NEW_LINE> color = tuple(int(i * 255) for i in color) <NEW_LINE> n["gl_color"].setValue(color[0] << 24 | ...
Set glcolor of node to a hue random color. Args: n (nuke.Node): Node to manipulate.
625941e257b8e32f52483852
def merge_info_from(self, docnames, other, app): <NEW_LINE> <INDENT> docnames = set(docnames) <NEW_LINE> for docname in docnames: <NEW_LINE> <INDENT> self.all_docs[docname] = other.all_docs[docname] <NEW_LINE> if docname in other.reread_always: <NEW_LINE> <INDENT> self.reread_always.add(docname) <NEW_LINE> <DEDENT> sel...
Merge global information gathered about *docnames* while reading them from the *other* environment. This possibly comes from a parallel build process.
625941e223e79379d52ee913
def load_collisions(self, dict_processes): <NEW_LINE> <INDENT> plist = [self.add_process(**p) for p in dict_processes] <NEW_LINE> for key, item in self.target.iteritems(): <NEW_LINE> <INDENT> item.ensure_elastic() <NEW_LINE> <DEDENT> return plist
Loads the set of collisions from the list of processes. Loads a list of dictionaries containing processes. Parameters ---------- dict_processes : List of dictionary or dictionary-like elements. The processes to add to this solver class. See :method:`solver.add_process` for the required fields of each of t...
625941e2596a897236089e70
def do_substitutions(line, iLine=-1): <NEW_LINE> <INDENT> iLineSub = 0 <NEW_LINE> while iLineSub < MAX_SUBSTITUTIONS_PER_LINE: <NEW_LINE> <INDENT> m = re.search("[{]{1,2}[^{}:]+[}]{1,2}", line) <NEW_LINE> iLineSub += 1 <NEW_LINE> if m is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> s = m.start() <NEW_LINE> e = m...
Search for call of function, i.e. to rescale.
625941e2b5575c28eb68e3b8
def edit_SO2_zrak(self, x): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = float(x) <NEW_LINE> zrak = self.doc.get_cistiZrak(self.aktivniZrak) <NEW_LINE> zrak.set_maxSO2(value) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> logging.warning(str(err), exc_info=True) <NEW_LINE> QtGui.QMessageBox.wa...
Callback za promjenu naziva maxSO2 generatora cistog zraka.
625941e271ff763f4b549a46
def set_error_threshold(self): <NEW_LINE> <INDENT> if self.err_thresh is None: <NEW_LINE> <INDENT> self.err_thresh = self.thresh_perc * np.mean( np.abs(np.array(self.training_data['forces']) * self.force_conv)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return
Set threshold for predictive std to be compared against
625941e23d592f4c4ed1d418
def size(self): <NEW_LINE> <INDENT> return _fife.CameraVector_size(self)
size(CameraVector self) -> std::vector< FIFE::Camera * >::size_type
625941e291af0d3eaac9bdd0
def arrange(self): <NEW_LINE> <INDENT> car_list = list(self.judge.car_info.values()) <NEW_LINE> car_list.sort(key=lambda x: x.speed, reverse=True) <NEW_LINE> mytime = 1 <NEW_LINE> count = 0 <NEW_LINE> runinglist = [] <NEW_LINE> start_time = time.time() <NEW_LINE> self.judge.result = 0 <NEW_LINE> self.judge.tick = 0 <NE...
:return:
625941e2e1aae11d1e74a06f
def example_choice(choice_check: str = 'A') -> None: <NEW_LINE> <INDENT> print(choice_check)
Demonstrate example choice. Parameters ---------- choice_check: str, {'A', 'B', 'C'} example choice
625941e23539df3088e2e6ff
def heap_sort(e_list): <NEW_LINE> <INDENT> def shift_down(e_list, elem, begin, end): <NEW_LINE> <INDENT> current_index = begin <NEW_LINE> current_son = current_index*2+1 <NEW_LINE> while(current_son <= end): <NEW_LINE> <INDENT> current_left = current_son <NEW_LINE> current_right = current_left+1 <NEW_LINE> if current_r...
基于最大堆
625941e26e29344779a629c4
def __init__(self, *args): <NEW_LINE> <INDENT> _simuPOP_la.floatListFunc_swiginit(self, _simuPOP_la.new_floatListFunc(*args))
Usage: floatListFunc(func)
625941e2d18da76e2353288f
def cancel_cb(self, goal_handle): <NEW_LINE> <INDENT> self.get_logger().info(f'{ACTION_NAME} received a cancel request!') <NEW_LINE> return CancelResponse.ACCEPT
Callback that's called when an action cancellation is requested
625941e2796e427e537b097d
def repo_is_dirty(repo): <NEW_LINE> <INDENT> output = sh.check_output('git -C "{}" status --porcelain'.format(repo), shell=True) <NEW_LINE> return output != b''
Returns True if there are unstaged changes in the specified repo
625941e273bcbd0ca4b2c42a
def rescan_virtual_machines(self): <NEW_LINE> <INDENT> vms = self._get_objects(vim.VirtualMachine) <NEW_LINE> for vm in vms: <NEW_LINE> <INDENT> if not self._vms.has_key(vm.name): <NEW_LINE> <INDENT> self._vms[vm.name] = VirtualMachine(vm, self.service_instance)
Refreshes the *VirtualMachines* list associated to server.
625941e2fff4ab517eb2f7f2
def _get_filter_op_name_and_values(directive): <NEW_LINE> <INDENT> args = get_uniquely_named_objects_by_name(directive.arguments) <NEW_LINE> if "op_name" not in args: <NEW_LINE> <INDENT> raise AssertionError( "op_name not found in filter directive arguments!" "Validation should have caught this: {}".format(directive) )...
Extract the (op_name, operator_params) tuple from a directive object.
625941e2566aa707497f4918
def test_create_vertex_batch(): <NEW_LINE> <INDENT> init_graph() <NEW_LINE> query = "graph.schema().propertyKey('name').asText().ifNotExist().create();" "graph.schema().propertyKey('age').asInt().ifNotExist().create();" "graph.schema().propertyKey('date').asDate().ifNotExist().create();" ...
没有索引 + 添加数据 + 字段(Text、int、date)
625941e2d164cc6175783104
def countBits(self, num): <NEW_LINE> <INDENT> res = [] <NEW_LINE> dpDict = {} <NEW_LINE> res.append(0) <NEW_LINE> dpDict[0] = 1 <NEW_LINE> left = 0 <NEW_LINE> right = 1 <NEW_LINE> for num in range(1,num + 1): <NEW_LINE> <INDENT> if num == left: <NEW_LINE> <INDENT> res.append(1) <NEW_LINE> dpDict[num] = 1 <NEW_LINE> <DE...
:type num: int :rtype: List[int]
625941e2a8370b7717052c52
def _convert_files(files): <NEW_LINE> <INDENT> if hasattr(files, "iteritems"): <NEW_LINE> <INDENT> files = files.iteritems() <NEW_LINE> <DEDENT> elif hasattr(files, "items"): <NEW_LINE> <INDENT> files = files.items() <NEW_LINE> <DEDENT> for param, val in files: <NEW_LINE> <INDENT> file_name, content_type, fobj = (None,...
Files can be passed in a variety of formats: * {"fieldname": open("bla.f", "rb")} * {"fieldname": ("filename", open("bla.f", "rb"))} * {"fieldname": ("filename", "content-type", open("bla.f", "rb"))} * Anything that has iteritems method, e.g. MultiDict: MultiDict([(name, open()), (name, open())] Our goal is to stan...
625941e2fff4ab517eb2f7f3
def BeginInvoke(self,sender,e,callback,object): <NEW_LINE> <INDENT> pass
BeginInvoke(self: DownloadDataCompletedEventHandler,sender: object,e: DownloadDataCompletedEventArgs,callback: AsyncCallback,object: object) -> IAsyncResult
625941e215baa723493c432d
def y2mat_Pq_r1A(yp, q, y): <NEW_LINE> <INDENT> return np.sqrt(4.0*np.pi/(2*q+1)) * y2mat_Y1qk(yp, q, 0, y)
gives matrix elemtn of P_q(w_1A) A is on positive z-axis
625941e20a50d4780f66724a
def btn_compress(self): <NEW_LINE> <INDENT> text = self.original_entry.get('1.0', tk.END) <NEW_LINE> if text[-1] == chr(10): <NEW_LINE> <INDENT> text = text[:-1] <NEW_LINE> <DEDENT> if not text: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> original_bin = tools.str_to_bin(text) <NEW_LINE> compressed, code = huffman.co...
Método accionado al presionar el botón de comprimir
625941e26fece00bbac2daf7
def find_first_peak(corr): <NEW_LINE> <INDENT> ind = corr.argmax() <NEW_LINE> s = corr.shape[1] <NEW_LINE> i = ind // s <NEW_LINE> j = ind % s <NEW_LINE> return i, j, corr.max()
Find row and column indices of the first correlation peak. Parameters ---------- corr : np.ndarray the correlation map Returns ------- i : int the row index of the correlation peak j : int the column index of the correlation peak corr_max1 : int the value of the correlation peak Origina...
625941e250812a4eaa59c6d3
def create(self): <NEW_LINE> <INDENT> self.m = self.new_menu(name='Menu') <NEW_LINE> self.m.addItem(text='Exit', onSelect=self.exit, shortcut='e') <NEW_LINE> self.check_me = self.add(npyscreen.Pager) <NEW_LINE> self.check_me.autowrap = True
Create the form.
625941e28e71fb1e9831db5d
def get_backup_vault_access_policy(BackupVaultName=None): <NEW_LINE> <INDENT> pass
Returns the access policy document that is associated with the named backup vault. See also: AWS API Documentation Exceptions :example: response = client.get_backup_vault_access_policy( BackupVaultName='string' ) :type BackupVaultName: string :param BackupVaultNam...
625941e263d6d428bbe448a5
def _render_val_with_prev(self, w, n, current_val, symbol_len): <NEW_LINE> <INDENT> sl = symbol_len-1 <NEW_LINE> if len(w) > 1: <NEW_LINE> <INDENT> out = self._revstart <NEW_LINE> if current_val != self.prior_val: <NEW_LINE> <INDENT> out += self._x + hex(current_val).rstrip('L').ljust(sl)[:sl] <NEW_LINE> <DEDENT> elif ...
Return a string encoding the given value in a waveform. :param w: The WireVector we are rendering to a waveform :param n: An integer from 0 to segment_len-1 :param current_val: the value to be rendered :param symbol_len: and integer for how big to draw the current value Returns a string of printed length symbol_len t...
625941e23617ad0b5ed682ab
def main(root_path, output_path): <NEW_LINE> <INDENT> print("Start analyzing classes...") <NEW_LINE> print('Root Path: ', root_path) <NEW_LINE> print('Output Path: ', output_path) <NEW_LINE> G = Digraph('image', engine='dot', strict=True, format='pdf') <NEW_LINE> G.graph_attr['label'] = 'Project Digraph' <NEW_LINE> G.l...
主函数
625941e224f1403a92600f18
@history.track_history <NEW_LINE> def norm_to_max_val(wrp): <NEW_LINE> <INDENT> if not isinstance(wrp, wrappers.HistoWrapper): <NEW_LINE> <INDENT> raise WrongInputError( "norm_to_max_val needs argument of type HistoWrapper. wrp: " + str(wrp) ) <NEW_LINE> <DEDENT> max_val = wrp.histo.GetBinContent(wrp.histo.GetMaximumBi...
Applies to HistoWrapper. Returns HistoWrapper. >>> from ROOT import TH1F >>> h1 = TH1F("h1", "", 2, .5, 2.5) >>> h1.Fill(1, 4) 1 >>> h1.Fill(2, 2) 2 >>> w1 = wrappers.HistoWrapper(h1, lumi=2.) >>> w1.histo.Integral() 6.0 >>> w2 = norm_to_max_val(w1) >>> w2.histo.Integral() 1.5
625941e2cc0a2c11143dd246
def getMinGpus(self): <NEW_LINE> <INDENT> result = 0 <NEW_LINE> for layer in self.__layers: <NEW_LINE> <INDENT> if layer.data.min_gpus > result: <NEW_LINE> <INDENT> result = layer.data.min_gpus <NEW_LINE> <DEDENT> <DEDENT> return result
Gets the layer min gpus.
625941e2a17c0f6771cbe404
def __str__(self): <NEW_LINE> <INDENT> return "{}, {} Typing, Reflection={}, First appeared in {}".format(self.name, self.typing, self.reflection, self.year)
Return a string of ProgrammingLanguage fields
625941e26aa9bd52df03715b
def set_hostname_verification(self, enable): <NEW_LINE> <INDENT> if (enable != True and enable != False): <NEW_LINE> <INDENT> return self.fail_response(13001, "NaServer::set_hostname_verification: invalid argument " + str(enable) + " specified") <NEW_LINE> <DEDENT> if (self.need_server_auth == False): <NEW_LINE> <INDEN...
Enables or disables hostname verification during server certificate verification. Hostname (CN) verification is enabled by default during server certificate verification.
625941e238b623060ff0b1a2
def is_equal(self, other): <NEW_LINE> <INDENT> return SedBase.is_equal(self, other) and self.kisao_id == other.kisao_id and self.new_value == other.new_value
Determine if parameter changes are equal Args: other (:obj:`AlgorithmParameterChange`): another parameter change Returns: :obj:`bool`: :obj:`True`, if two parameter changes are equal
625941e27cff6e4e81117d3a
def check_file_existence(filename): <NEW_LINE> <INDENT> assert filename is not None, "File to check is not specified" <NEW_LINE> assert os.path.exists(filename), "The file {} does not exist".format(filename)
Check whether the specified file exists.
625941e2cc0a2c11143dd247
def get_follower_to_like_random(self): <NEW_LINE> <INDENT> now_time = datetime.now() <NEW_LINE> if self.bot.follow_time > 0: <NEW_LINE> <INDENT> cut_off_time = now_time - timedelta(seconds=self.bot.follow_time) - timedelta(seconds=self.bot.follow_time) <NEW_LINE> <DED...
Gets random follower who was created earlier than 2 * follow_time and has zero unfollow_count
625941e2507cdc57c6307098
def _getCharacterIndexFromListWidget(self, character): <NEW_LINE> <INDENT> ListWidget = self.frbCharacterAssetListWidget <NEW_LINE> for i in range(ListWidget.count()): <NEW_LINE> <INDENT> if not ListWidget.item(i).text() == character: continue <NEW_LINE> return i <NEW_LINE> <DEDENT> return None
Iterates through the items in the Character List, and returns the index of the item with the matching text passed in.
625941e2a219f33f34628d1a
def copy(self: "MicroBitImage") -> "MicroBitImage": <NEW_LINE> <INDENT> return MicroBitImage()
Return a copy of the this image.
625941e2442bda511e8be7c8
def my_pfn(orig_path): <NEW_LINE> <INDENT> if execution_env == 'psc_bridges': <NEW_LINE> <INDENT> return PFN('scp://centos@141.142.209.167/' + orig_path, site='local') <NEW_LINE> <DEDENT> elif execution_env != 'condor_pool' and re.search(r'sites/ua-mac/', orig_path): <NEW_LINE> <INDENT> path = re.sub(r'.*ua-mac/', 'go:...
Depending on the execution environment, use either file:// or go:// PFNs
625941e2a8ecb033257d3481
def test_labels(self): <NEW_LINE> <INDENT> labels = ['tests.test_unit_integration.TestCollection'] <NEW_LINE> cmdline = ['python', '-m', 'cricket.unittest.executor', '-t'] + labels <NEW_LINE> runner = subprocess.Popen( cmdline, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, ) <NEW_LINE> output...
Test that the command-line API is respecting the labels being targetted for testing
625941e22ae34c7f2600d4e6
def set_hemis(self, shemis): <NEW_LINE> <INDENT> lat_axis = self.data.uwnd.shape.index(self.data.lat.shape[0]) <NEW_LINE> if self.data.uwnd.shape.count(self.data.lat.shape[0]) > 1: <NEW_LINE> <INDENT> self.log.info( 'ASSUMING LAT DIM IS: {} ({})'.format(lat_axis, self.data.uwnd.shape) ) <NEW_LINE> <DEDENT> self.hemis =...
Select hemisphere data. This function sets `self.hemis` to be an length N list of slices such that only the desired hemisphere is selected with N-D data (e.g. uwind and ipv) along all other axes. It also returns the latitude for the selected hemisphere, an index to select the hemisphere in output arrays, and the extre...
625941e2de87d2750b86014b
def _vertical_out_wipe ( self, g, image_0, image_1, i, x, y, x0, x1, y0, dy ): <NEW_LINE> <INDENT> ddy2 = (dy / 2) - (y0 / 2) <NEW_LINE> yt = y0 + ddy2 <NEW_LINE> dx10 = x1 - x0 <NEW_LINE> g.blit( x + x0, y, dx10, ddy2, image_0, x0, 0, dx10, ddy2 ) <NEW_LINE> g.blit( x + x0, y + yt, dx10, dy - yt, image_0, x0, yt, dx...
Handles a vertical out wipe effect.
625941e29c8ee82313fbbb2b
def __init__(self, strategy_setter): <NEW_LINE> <INDENT> super(StrategyCallLoop, self).__init__(strategy_setter) <NEW_LINE> self._count = 1
_StrategyCall initializer @type strategy_setter: callable @param strategy_setter: The callable used to set new strategy
625941e2379a373c97cfaefc
def delete_targets( self, references=None, ids=None, names=None, async_req=False, _return_http_data_only=False, _preload_content=True, _request_timeout=None, ): <NEW_LINE> <INDENT> kwargs = dict( ids=ids, names=names, async_req=async_req, _return_http_data_only=_return_http_data_only, _preload_content=_preload_content,...
Delete the connection to the target for replication. Args: references (list[FixedReference], optional): A list of references to query for. Overrides ids and names keyword arguments. ids (list[str], optional): A list of resource IDs. If after filtering, there is not at least one resource ...
625941e2d7e4931a7ee9e2d4
def cipher(text, shift, encrypt=True): <NEW_LINE> <INDENT> alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' <NEW_LINE> new_text = '' <NEW_LINE> for c in text: <NEW_LINE> <INDENT> index = alphabet.find(c) <NEW_LINE> if index == -1: <NEW_LINE> <INDENT> new_text += c <NEW_LINE> <DEDENT> else: <NEW_LINE> <...
Caesar cipher is an encryption techniques. Each letter is replaced by a letter some fixed number of positions down the alphabet. Parameters ---------- text: str A string of text that people would like to encrypt or decrypt shift: int A interger for shifts incidating the number of digits that people would like ...
625941e27d43ff24873a3058
def setMimeType(self, mimetype): <NEW_LINE> <INDENT> pass
setMimeType(mimetype)--Sets the listitem's mimetype if known. mimetype : string or unicode - mimetype. *If known prehand, this can avoid xbmc doing HEAD requests to http servers to figure out file type.
625941e2711fe17d82542718