code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def read_log_mode(ac_id, filename): <NEW_LINE> <INDENT> f = open(filename, 'r') <NEW_LINE> pattern = re.compile("(\S+) "+ac_id+" PPRZ_MODE (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)") <NEW_LINE> list_meas = [] <NEW_LINE> while True: <NEW_LINE> <INDENT> line = f.readline().strip() <NEW_LINE> if line == '': <NEW_LINE> <INDENT> ...
Extracts mode values from a log.
625941ce23849d37ff7b31c9
def phantomjs_factory(user_agent='chrome', **kwargs): <NEW_LINE> <INDENT> if 'desired_capabilities' not in kwargs: <NEW_LINE> <INDENT> caps = dict(DesiredCapabilities.PHANTOMJS) <NEW_LINE> caps['phantomjs.page.settings.userAgent'] = getattr(UserAgents, user_agent, UserAgents.chrome)() <NEW_LINE> kwargs['desired_capabil...
reduce log level service_args=["--webdriver-loglevel=SEVERE"] remove logging service_log_path=os.path.devnull
625941ce377c676e912722e3
def convert_to_json(self): <NEW_LINE> <INDENT> return [self.species_board_index, self.card_to_replace_index, self.replacement_card_index]
Convert this ReplaceTraitAction into its respective JSON representation :return: RT as specified in http://www.ccs.neu.edu/home/matthias/4500-s16/r_remote.html
625941cecc40096d61595a8a
def add_arguments(parser): <NEW_LINE> <INDENT> parser.register("type", "bool", lambda v: v.lower() == "true") <NEW_LINE> parser.add_argument("--windows", type="bool", default="False", help="whether the script is being run on windows or linux/unix") <NEW_LINE> parser.add_argument("--input-training-data-path", type=str, ...
Build ArgumentParser
625941cea8370b77170529d9
def sep(self, text='', **kwargs): <NEW_LINE> <INDENT> self.meth_defaults['sep'].setdefault('sep', '-') <NEW_LINE> self.meth_defaults['sep'].setdefault('width', 2) <NEW_LINE> opts = self._method_push(self.options, 'sep', kwargs) <NEW_LINE> opts.setdefault('_callframe', inspect.currentframe().f_back) <NEW_LINE> formatted...
Print a short horizontal line, possibly with some text following, of the desired width. Useful as a separator for different parts of output.
625941cebaa26c4b54cb1259
def get_blogs(self): <NEW_LINE> <INDENT> blogs = BlogPost.objects.filter( pub_date__lte = timezone.now() ).order_by('-pub_date') <NEW_LINE> for blog in blogs: <NEW_LINE> <INDENT> self.num_comments[blog.id] = len(Comment.objects.filter(blog_post = blog.id)) <NEW_LINE> <DEDENT> return blogs
Returns the published blog posts.
625941ceff9c53063f47c32d
def _norm_to_list_of_layers(maybe_layers): <NEW_LINE> <INDENT> return (maybe_layers if isinstance(maybe_layers[0], (list,)) else [maybe_layers])
Normalizes to a list of layers. Args: maybe_layers: A list of data[1] or a list of list of data. Returns: List of list of data. [1]: A Functional model has fields 'inbound_nodes' and 'output_layers' which can look like below: - ['in_layer_name', 0, 0] - [['in_layer_is_model', 1, 0], ['in_layer_is_model', 1, 1]] ...
625941ceadb09d7d5db6c8c9
def parse_tags(item): <NEW_LINE> <INDENT> return {'tag': [tagdef['name'] for tagdef in item.get('tags', {}).itervalues() if isinstance(tagdef.get('name', {}), unicode)]}
Parse the tags
625941cee1aae11d1e749df1
def finished_subtitles(self, request, session_pk, subtitles=None, new_title=None, completed=None, forked=False, throw_exception=False, new_description=None, task_id=None, task_notes=None, task_approved=None, task_type=None): <NEW_LINE> <INDENT> session = SubtitlingSession.objects.get(pk=session_pk) <NEW_LINE> if not re...
Called when a user has finished a set of subtitles and they should be saved. TODO: Rename this to something verby, like "finish_subtitles".
625941ce96565a6dacc8f805
def __init__(self, element, elk, elk_data): <NEW_LINE> <INDENT> super().__init__(element, elk, elk_data) <NEW_LINE> self._elk = elk <NEW_LINE> self._changed_by_keypad = None <NEW_LINE> self._changed_by_time = None <NEW_LINE> self._changed_by_id = None <NEW_LINE> self._changed_by = None <NEW_LINE> self._state = None
Initialize Area as Alarm Control Panel.
625941ce5510c4643540f51e
def encode_manifest(manifest_string): <NEW_LINE> <INDENT> manifest = json.loads(manifest_string, object_pairs_hook=collections.OrderedDict) <NEW_LINE> manifest_minified = json.dumps(manifest) <NEW_LINE> return base64.urlsafe_b64encode(manifest_minified)
Creates a URL-safe-base-64-encoded manifest string from a full manifest. Raises a ValueError if the string is not valid JSON.
625941ce7b180e01f3dc4937
def delete_hosts( self, references=None, authorization=None, x_request_id=None, names=None, async_req=False, _return_http_data_only=False, _preload_content=True, _request_timeout=None, ): <NEW_LINE> <INDENT> kwargs = dict( authorization=authorization, x_request_id=x_request_id, names=names, async_req=async_req, _return...
Deletes an existing host. All volumes that are connected to the host, either through private or shared connections, must be disconnected from the host before the host can be deleted. The `names` query parameter is required. Args: references (list[FixedReference], optional): A list of references to query fo...
625941ce442bda511e8be552
def testInitialize(self): <NEW_LINE> <INDENT> configuration = libyal.ReleaseExeVSProjectConfiguration() <NEW_LINE> self.assertEqual(configuration.output_type, '1') <NEW_LINE> self.assertEqual(configuration.whole_program_optimization, '1') <NEW_LINE> self.assertEqual(configuration.link_incremental, '1') <NEW_LINE> self....
Tests the __init__ function.
625941ce8c0ade5d55d3eaf5
def begin(): <NEW_LINE> <INDENT> messagebox.showinfo("Hello!", "This is the beginning of your story!") <NEW_LINE> firstchoice = simpledialog.askinteger("First choice:", "Your walking home, and there are 2 paths."+ " Which do you take?"+ " 1 for the shady alley"+ ", 2 for the sidewalk") <NEW_LINE> if firstchoice == 1: <...
First Decision
625941ce94891a1f4081bbe4
def number_class(self, a): <NEW_LINE> <INDENT> a = _convert_other(a, raiseit=True) <NEW_LINE> return a.number_class(context=self)
Returns an indication of the class of the operand. The class is one of the following strings: -sNaN -NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.number_class(Decimal('Infinity')) '+Infinity' >>> c...
625941ce8da39b475bd650ae
def file_response(self, context, target_path): <NEW_LINE> <INDENT> finfo = os.stat(target_path) <NEW_LINE> context.add_header("Content-Length", str(finfo.st_size)) <NEW_LINE> context.add_header("Last-Modified", str(params.FullDate.from_unix_time(finfo.st_mtime))) <NEW_LINE> context.start_response() <NEW_LINE> bleft = f...
Returns a file from the file system target_path The system file path of the file to be returned. The Content-Length header is set from the file size, the Last-Modified date is set from the file's st_mtime and the file's data is returned in chunks of :attr:`MAX_CHUNK` in the response. The status is *not* set and ...
625941ce2ae34c7f2600d26b
def track_time_change(self, action, year=None, month=None, day=None, hour=None, minute=None, second=None, utc=False): <NEW_LINE> <INDENT> if any((val is not None for val in (year, month, day, hour, minute, second))): <NEW_LINE> <INDENT> pmp = _process_match_param <NEW_LINE> year, month, day = pmp(year), pmp(month), pmp...
Adds a listener that will fire if UTC time matches a pattern.
625941ce462c4b4f79d1d80b
def update_to_es(self, sender, id, body, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.pop('signal') <NEW_LINE> print(sender, id, body) <NEW_LINE> return self.update_doc(sender, id, body, *args, **kwargs)
在es的索引库中更新指定id的记录 :param sender: index索引库名 :param id: doc的id :param body: DSL表达式 :param kwargs: 额外参数 :return: code, result
625941ce090684286d50ee20
def get_bottleneck_path(image_lists, index, bottleneck_dir, category): <NEW_LINE> <INDENT> return get_image_path(image_lists, index, bottleneck_dir, category) + '.txt'
"Returns a path to a bottleneck file for a label at the given index. Args: image_lists: Dictionary of training images for each label. index: Integer offset of the image we want. This will be moduloed by the available number of images for the label, so it can be arbitrarily large. bottleneck_dir: Folder string ...
625941ce5fcc89381b1e17fa
def lua_get_function_param_opt(func_name, arg_expr, body_locals, lua_fname): <NEW_LINE> <INDENT> value_sim = lua_get_exp_value_opt("call:"+func_name, arg_expr, body_locals, lua_fname) <NEW_LINE> return value_sim
Converts one argument of a function call to ValueSim, optimizing it
625941ce76d4e153a657ec6b
def size(self): <NEW_LINE> <INDENT> return len(self.data)
:return: Sample size
625941cefff4ab517eb2f576
def get_full_description(self): <NEW_LINE> <INDENT> return self.long_description
Return str long description of location.
625941cebf627c535bc1330a
def doughnut_chart(data, title): <NEW_LINE> <INDENT> labels = data[0] <NEW_LINE> values = data[1] <NEW_LINE> slice_labels = ['{} ({:,})'.format(l, v) for l, v in zip(labels, values)] <NEW_LINE> colours = colour_list(len(labels)) <NEW_LINE> explode = [0.05 for _ in range(len(labels))] <NEW_LINE> plot.figure('WhatStats -...
Show doughnut chart of data tuple (labels, values).
625941ce1f037a2d8b946338
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Attraction): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941ceadb09d7d5db6c8ca
def assign_priors(gt_boxes, gt_labels, corner_form_priors, iou_threshold): <NEW_LINE> <INDENT> ious = iou_of(gt_boxes.unsqueeze(0), corner_form_priors.unsqueeze(1)) <NEW_LINE> best_target_per_prior, best_target_per_prior_index = ious.max(1) <NEW_LINE> best_prior_per_target, best_prior_per_target_index = ious.max(0) <NE...
Assign ground truth boxes and targets to priors. Args: gt_boxes (num_targets, 4): ground truth boxes. gt_labels (num_targets): labels of targets. priors (num_priors, 4): corner form priors Returns: boxes (num_priors, 4): real values for priors. labels (num_priros): labels for priors.
625941ce3eb6a72ae02ec619
def get(self, template): <NEW_LINE> <INDENT> cached = self._cache.get(template) <NEW_LINE> if cached: <NEW_LINE> <INDENT> return deepcopy(cached) <NEW_LINE> <DEDENT> template_path = os.path.join(self._path, '%s.template' % template) <NEW_LINE> with open(template_path) as template_in: <NEW_LINE> <INDENT> loaded = json.l...
Load raw template. :param template: Template name. :return: JSON-decoded template.
625941ce30c21e258bdfa5d8
def greet_user(usernames): <NEW_LINE> <INDENT> for username in usernames: <NEW_LINE> <INDENT> print("Hello,"+username.title()+"!")
显示简单的问候语
625941ce15fb5d323cde0c4a
def all_parameters(datafile=None): <NEW_LINE> <INDENT> if datafile is None: <NEW_LINE> <INDENT> datafile = ('../params/era_interim_variables.csv') <NEW_LINE> <DEDENT> print('Reading variable IDs and info from ' + datafile) <NEW_LINE> df = pd.read_csv(datafile, index_col=0, dtype=str) <NEW_LINE> df['code'] = df['code']....
Return a DataFrame of parameter codes and info for ERA-Interim. Input datafile is a csv file with all the codes and info. If datafile is None, then the input file defaults to: '../params/era_interim_variables.csv'
625941ce91af0d3eaac9bb53
def sync(self): <NEW_LINE> <INDENT> btrfs.ioctl.sync(self.fd)
Call the btrfs sync kernel function, causing a transaction commit.
625941cea79ad161976cc280
def GetEventsByTagIds(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Missing associated documentation comment in .proto file.
625941ceec188e330fd5a8d9
def _create_group_tree(self, levels): <NEW_LINE> <INDENT> if levels[0] != 0: <NEW_LINE> <INDENT> raise KPError("Invalid group tree") <NEW_LINE> return False <NEW_LINE> <DEDENT> for i in range(len(self.groups)): <NEW_LINE> <INDENT> if(levels[i] == 0): <NEW_LINE> <INDENT> self.groups[i].parent = self._root_group <NEW_LIN...
This method creates a group tree
625941ce66656f66f7cbc2e5
def dedupe_posts(posts, found_posts): <NEW_LINE> <INDENT> for post in posts: <NEW_LINE> <INDENT> if post.url not in found_posts: <NEW_LINE> <INDENT> yield post <NEW_LINE> found_posts.add(post.url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Omitting duplicate {}'.format(post.url))
Generate posts where duplicates have been removed by comparing url.
625941ce8a43f66fc4b5419f
def dic(ke,a,en=True): <NEW_LINE> <INDENT> d=list(string.printable) <NEW_LINE> e=list(int(str(i**a)[:6:]) for i in [j for j in range(32,127)]) <NEW_LINE> s={} <NEW_LINE> if en==True: <NEW_LINE> <INDENT> s=dict(zip(e,d)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s=dict(zip(d,e)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <...
dic(list,int,bool) - create a dictionary
625941ce23849d37ff7b31ca
def display_dialog(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> from trionyx.views import layouts <NEW_LINE> try: <NEW_LINE> <INDENT> content = layouts.get_layout(self.kwargs.get('code'), self.object).render(self.request) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.exception(e) <NEW_LINE> cont...
Render layout for object
625941ced58c6744b4257d9a
def read_headers(self, jpegsrc): <NEW_LINE> <INDENT> self.read_markers(jpegsrc) <NEW_LINE> if self.Width <= 0 or self.Height <= 0: <NEW_LINE> <INDENT> raise ValueError("Error reading the file header") <NEW_LINE> <DEDENT> self.DataBytesLeft = len(jpegsrc) - self.DataPos <NEW_LINE> self.init_decoder()
reads Width, Height, headsize
625941ce2c8b7c6e89b358fb
def _average_path_length(n_samples_leaf): <NEW_LINE> <INDENT> n_samples_leaf = check_array(n_samples_leaf, ensure_2d=False) <NEW_LINE> n_samples_leaf_shape = n_samples_leaf.shape <NEW_LINE> n_samples_leaf = n_samples_leaf.reshape((1, -1)) <NEW_LINE> average_path_length = np.zeros(n_samples_leaf.shape) <NEW_LINE> mask_1...
The average path length in a n_samples iTree, which is equal to the average path length of an unsuccessful BST search since the latter has the same structure as an isolation tree. Parameters ---------- n_samples_leaf : array-like, shape (n_samples,). The number of training samples in each test sample leaf, for ...
625941ce10dbd63aa1bd2cde
def _get_data(self, byte_stream): <NEW_LINE> <INDENT> data_struc = {0: ('s', 1), 1: ('h', 2), 3: ('i', 4), 4: ('f', 4)} <NEW_LINE> offset = (self._record_offset + self.header['OFFSET_TO_BEGINNING_OF_DATA']) <NEW_LINE> byte_stream.goto(offset) <NEW_LINE> nos = self.header['NUMBER_OF_SAMPLES'] <NEW_LINE> enc = self.block...
Importing data
625941ce4a966d76dd55114a
def render_response(self, _template, **context): <NEW_LINE> <INDENT> ctx = {'user': self.user} <NEW_LINE> ctx.update(context) <NEW_LINE> if 'model_edited' not in ctx: <NEW_LINE> <INDENT> model_edited = self.get_session_property('model_edited') <NEW_LINE> if model_edited is not None: <NEW_LINE> <INDENT> ctx.update({'mod...
Process the template and render response.
625941cefb3f5b602dac37ce
def calc_property(self, property_name, temperature): <NEW_LINE> <INDENT> return self.properties.calc_property(property_name, temperature)
Wrapper function for the native property functions :param property_name: name of self.PROPERTY_NAMES to calculate :param temperature: 1D temperature array :return: the calculated 1D array of the specific property
625941ce16aa5153ce3625b2
def parse_data(raw_data): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for line in raw_data: <NEW_LINE> <INDENT> if line[0] != '\n': <NEW_LINE> <INDENT> crypt = line.split() <NEW_LINE> crlen = len(crypt) <NEW_LINE> if crlen == 2: <NEW_LINE> <INDENT> crypt[1] = int(crypt[1]) <NEW_LINE> data.append(crypt) <NEW_LINE> <DEDENT>...
Splits a list of strings in two, returning an array of lists composed of a string and an integer if the data is valid, or a None object otherwise.
625941ce1b99ca400220abec
def build_reconstruction_jobs(self, policy, jobs, ips): <NEW_LINE> <INDENT> obj_ring = self.get_object_ring(policy.idx) <NEW_LINE> data_dir = get_data_dir(policy.idx) <NEW_LINE> for local_dev in [dev for dev in obj_ring.devs if dev and dev['replication_ip'] in ips and dev['replication_port'] == self.port]: <NEW_LINE> <...
Helper function for collect_jobs to build jobs for reconstruction using EC style storage policy
625941cead47b63b2c50a0ba
def calPoints(self, ops): <NEW_LINE> <INDENT> points = [] <NEW_LINE> for op in ops: <NEW_LINE> <INDENT> if op == 'C': <NEW_LINE> <INDENT> points.pop() <NEW_LINE> <DEDENT> elif op == 'D': <NEW_LINE> <INDENT> points.append(points[-1] * 2) <NEW_LINE> <DEDENT> elif op == '+': <NEW_LINE> <INDENT> points.append(points[-1] + ...
:type ops: List[str] :rtype: int
625941ced10714528d5ffe1e
def add_additional_URL(self, handle, *urls, **attributes): <NEW_LINE> <INDENT> LOGGER.debug('add_additional_URL...') <NEW_LINE> handlerecord_json = self.retrieve_handle_record_json(handle) <NEW_LINE> if handlerecord_json is None: <NEW_LINE> <INDENT> msg = 'Cannot add URLS to unexisting handle!' <NEW_LINE> raise HandleN...
Add a URL entry to the handle record's 10320/LOC entry. If 10320/LOC does not exist yet, it is created. If the 10320/LOC entry already contains the URL, it is not added a second time. :param handle: The handle to add the URL to. :param urls: The URL(s) to be added. Several URLs may be specified. :param attributes: Opt...
625941ce26238365f5f0efa9
def test_rst7(self): <NEW_LINE> <INDENT> parm = ChamberParm(get_fn('ala_ala_ala.parm7'), get_fn('ala_ala_ala.rst7')) <NEW_LINE> self.assertEqual(parm.combining_rule, 'lorentz') <NEW_LINE> system = parm.createSystem() <NEW_LINE> integrator = mm.VerletIntegrator(1.0*u.femtoseconds) <NEW_LINE> sim = app.Simulation(parm.to...
Test using OpenMMRst7 to provide coordinates (CHAMBER)
625941ce76d4e153a657ec6c
def trim(self, start=0, stop=None): <NEW_LINE> <INDENT> start = Signal.in_samples(start, self.samplerate) <NEW_LINE> if stop is None: <NEW_LINE> <INDENT> stop = self.n_samples - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stop = Signal.in_samples(stop, self.samplerate) <NEW_LINE> <DEDENT> if stop >= self.n_samples:...
Trim the signal by returning the section between `start` and `stop`. Arguments: start (float | int): start of the section in seconds (given a float) or in samples (given an int). stop (float | int): end of the section in seconds (given a float) or in samples (given an int). Returns: (slab.Signal): a new ins...
625941ce435de62698dfdd88
def open(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.resp = urlopen( self.url ) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> self.log.error( 'Failed to open URL: {}'.format(err) ) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.size = int( self.resp.getheader(...
Actually open the URL
625941cef7d966606f6aa13f
def test_logger(): <NEW_LINE> <INDENT> logger = logging.getLogger() <NEW_LINE> logger.setLevel(logging.INFO) <NEW_LINE> formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') <NEW_LINE> console_handler = logging.StreamHandler() <NEW_LINE> console_handler.setLevel(logging.INFO) <NEW_LINE> ...
测试日志类的使用方法。 :return:
625941ce30dc7b7665901aa1
def run_fork(config_handler): <NEW_LINE> <INDENT> logging.info('Sending log messages[%s] to %s', config_handler.log_level, config_handler.log_file) <NEW_LINE> pid = os.fork() <NEW_LINE> if pid == 0: <NEW_LINE> <INDENT> LOGGER.info('In child: starting processing') <NEW_LINE> execute_supervisor(config_handler) <NEW_LINE>...
Starts the supervisor as a direct child process, passing to it the appropriate configuration. This is meant for use during tests, when the child process needs to be monitored (and possibly killed if it crashes) instead of allowed to roam free as in the daemon case. :param config.ConfigHandler config_handler: The con...
625941cea8ecb033257d3208
def decode(self, response, request): <NEW_LINE> <INDENT> def unq(s): <NEW_LINE> <INDENT> if s[0] == s[-1] == '"': <NEW_LINE> <INDENT> return s[1:-1] <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> response = ' '.join(response.splitlines()) <NEW_LINE> parts = response.split(',') <NEW_LINE> auth = {} <NEW_LINE> for (k, ...
Decode the given response and attempt to generate a L{DigestedCredentials} from it. @type response: C{str} @param response: A string of comma seperated key=value pairs @type request: L{knoboo.external.twisted.web2.server.Request} @param request: the request being processed @return: L{DigestedCredentials} @raise: L{...
625941ce507cdc57c6306e16
def query_groups(server, auth_token, site_id, page_size, page_number): <NEW_LINE> <INDENT> if page_size == 0: <NEW_LINE> <INDENT> url = server + "/api/{0}/sites/{1}/groups".format(VERSION, site_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = server + "/api/{0}/sites/{1}/groups?pageSize={2}&pageNumber={3}".forma...
Queries for all groups in the site URI GET /api/api-version/sites/site-id/groups GET /api/api-version/sites/site-id/groups?pageSize=page-size&pageNumber=page-number
625941ce2ae34c7f2600d26c
def insertPage(self, before, widget, name): <NEW_LINE> <INDENT> return KPageWidgetItem()
KPageWidgetItem KPageWidget.insertPage(KPageWidgetItem before, QWidget widget, QString name)
625941ce460517430c3942bf
def getVersion(self): <NEW_LINE> <INDENT> namespace = {} <NEW_LINE> version_file = self.directory.child("pyamf").child("__init__.py") <NEW_LINE> execfile(version_file.path, namespace) <NEW_LINE> return namespace["version"]
:return: :class`pyamf.version.Version` specifying the version number of the project based on live python modules.
625941ce187af65679ca525a
def run_execute_command(specifier: str, arguments, uri: str) -> None: <NEW_LINE> <INDENT> if specifier == "audit_backup": <NEW_LINE> <INDENT> client = ddl.AuditBackupSchemaSetupClient(uri) <NEW_LINE> client.execute_backup_function(arguments.date) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Functionality 'execu...
Run a function defined in the database
625941ce6fece00bbac2d87a
def disable_loopback_mode(self, target): <NEW_LINE> <INDENT> if (target != self.EYE_PRBS_LOOPBACK_TARGET_NIC) and (target != self.EYE_PRBS_LOOPBACK_TARGET_TOR_A) and (target != self.EYE_PRBS_LOOPBACK_TARGET_TOR_B) and (target != self.EYE_PRBS_LOOPBACK_TARGET_LOCAL): <NEW_LINE> <INDENT> self.log(self.LOG_ERROR...
This API disables the Loopback mode on the port user provides. Target is an integer for selecting which end of the Y cable we want to run loopback on. The port on which this API is called for can be referred using self.port. Args: target: One of the following predefined constants, the target on which to dis...
625941ceab23a570cc2502be
def GetLastMemorySequence(self): <NEW_LINE> <INDENT> r = CALL('GetLastMemorySequence', self, byref(self.id)) <NEW_LINE> return self.CheckForSuccessError(r)
The function GetLastMemorySequence() returns the ID of the last recorded sequence in the memory board. This parameter can then be used in combination with the function TransferImage() to read images out of the camera memory. No memory board to test this, Not tested!
625941ce099cdd3c635f0d96
def _add_database_error_to_messages(self, request, line: OrderedDict) -> None: <NEW_LINE> <INDENT> err_str = parse_kwargs_to_error_string(self.datamap, line) <NEW_LINE> messages.add_message(request, messages.ERROR, err_str)
Constructs a message to be used by the view template based on a single OrderedDict, line. :param request: :type request: django.core.handlers.wsgi.WSGIRequest :param line: :type line: collections.OrderedDict :return: :rtype: None
625941cee8904600ed9f2068
def std(data, ddof=0, invert=False): <NEW_LINE> <INDENT> return np.sqrt(var(data, ddof=ddof, invert=invert))
Computes standard deviation of a counter. If cdat = Counter(dat), then std(cdat) = np.std(dat) ddof: delta degrees of freedom (same as np)
625941ce97e22403b379d0d5
def _manage_users(request, course_key): <NEW_LINE> <INDENT> user_perms = get_user_permissions(request.user, course_key) <NEW_LINE> if not user_perms & STUDIO_VIEW_USERS: <NEW_LINE> <INDENT> raise PermissionDenied() <NEW_LINE> <DEDENT> course_module = modulestore().get_course(course_key) <NEW_LINE> instructors = CourseI...
This view will return all CMS users who are editors for the specified course
625941ce01c39578d7e74f76
def test_tcp_client_connect(self): <NEW_LINE> <INDENT> with patch.object(socket, 'create_connection') as mock_method: <NEW_LINE> <INDENT> mock_method.return_value = object() <NEW_LINE> client = ModbusTcpClient() <NEW_LINE> self.assertTrue(client.connect()) <NEW_LINE> <DEDENT> with patch.object(socket, 'create_connectio...
Test the tcp client connection method
625941ce15baa723493c40b1
def KWavelength(wavelength): <NEW_LINE> <INDENT> return np.reciprocal(wavelength)*2.0*np.pi
Calculate wave vector k vactor [1/AA] from wavelength [AA]
625941ce63d6d428bbe4462a
def positionMultiEnd(self, reqId:int): <NEW_LINE> <INDENT> self.logAnswer(crt_fn_name(), vars())
same as positionEnd() except it can be for a certain account/model
625941ce796e427e537b0702
def check_color(self, color): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert(min(color)>=0 and max(color)<256) <NEW_LINE> return color <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise(RuntimeError("RGB color values must be between 0 and 255 inclusive"))
This method is used to set the color of color_to_set or raise an error if the RGV values are invalid.
625941ceeab8aa0e5d26dc93
def _summarize_report(self, report, start_time, end_time, sb): <NEW_LINE> <INDENT> time_taken = end_time - start_time <NEW_LINE> num_failed = report.num_failed + report.num_interrupted <NEW_LINE> num_run = report.num_succeeded + report.num_errored + num_failed <NEW_LINE> num_tests = len(self.tests) * self.options.num_r...
Return the summary information of the execution. The summary is for 'report' that started at 'start_time' and finished at 'end_time'. Also append a summary of that execution onto the string builder 'sb'.
625941ce5166f23b2e1a5294
def set_next_version_display_datetime(self, dt): <NEW_LINE> <INDENT> version = getattr(self, self.get_next_version()) <NEW_LINE> version.set_display_datetime(dt)
Set display datetime of next version.
625941ce046cf37aa974ce83
def remove_packages(self, ref): <NEW_LINE> <INDENT> return self.base_url + _format_ref(routes.v1_remove_packages, ref.copy_clear_rev())
Remove files from a package
625941ce57b8e32f524835d6
def bucket_sort(numbers, num_buckets=10): <NEW_LINE> <INDENT> output =[] <NEW_LINE> range_num = len(numbers) // num_buckets <NEW_LINE> buckets = [[] for _ in range(range_num + 1)] <NEW_LINE> for index, number in enumerate(numbers): <NEW_LINE> <INDENT> bucket_index, remainder = divmod(number, range_num) <NEW_LINE> if re...
Sort given numbers by distributing into buckets representing subranges, then sorting each bucket and concatenating all buckets in sorted order. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?
625941ce2eb69b55b151c9eb
def rpc(opcode, req, resp=EMPTY_STRUCT): <NEW_LINE> <INDENT> def rpc_decorator(func): <NEW_LINE> <INDENT> def func_wrapper(self): <NEW_LINE> <INDENT> unpacked = self.unpack_chunk(req) <NEW_LINE> if unpacked is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> logging.debug('{}{}'.format(func.__name__, unpacked...
A decorator that handles RPC boilerplate. Receives a unique opcode number, request struct and response struct.
625941ce009cb60464c634ed
def get_revs_limit(cluster_config): <NEW_LINE> <INDENT> cluster = load_cluster_config_json(cluster_config) <NEW_LINE> return cluster["environment"]["revs_limit"]
Get revs limit
625941ce94891a1f4081bbe5
def integral(f, x, method): <NEW_LINE> <INDENT> n = x.shape[0] <NEW_LINE> if method == "trapez": <NEW_LINE> <INDENT> return sum(((x[i + 1] - x[i]) / 2) * (f(x[i]) + f(x[i + 1])) for i in range(n - 1)) <NEW_LINE> <DEDENT> if method == "dreptunghi": <NEW_LINE> <INDENT> return sum((x[i + 2] - x[i]) * f(x[i + 1]) for i in ...
Calculate the integral value on the domain x of function f using the method by summing :param f: function to calculate integral of :param x: discrete domain of x values :param method: which method to use trapez|dreptunghi|simpsion :return: the value of the integral
625941cefbf16365ca6f6301
def initialize(self, design, launch_condition): <NEW_LINE> <INDENT> self.name = design['name'] <NEW_LINE> self.m_af = design['m_af'] <NEW_LINE> self.I_af = design['I_af'] <NEW_LINE> self.CP = design['CP'] <NEW_LINE> self.CG_a = design['CG_a'] <NEW_LINE> self.d = design['d'] <NEW_LINE> self.area = np.pi * (self.d ** 2) ...
初期化
625941ce71ff763f4b5497c7
def add_position(player_grades, formation): <NEW_LINE> <INDENT> defense = [*range(1, int(formation[0])+1)] <NEW_LINE> midfield = [*range(int(formation[0])+1, int(formation[0])+ int(formation[1])+1)] <NEW_LINE> attack = [*range(int(formation[0])+int(formation[1])+1, 11)] <NEW_LINE> for idx, key in enumerate(player_grade...
add position to player grades for each player @args: {dict} player_grades: keys(): player name, values(): {list} containing player's grades {str} formation: composition of team @returns: None, modifies original player_grades dictionnary by adding the position of the player 'A': attack, 'M':midfield, 'D': de...
625941ce8c3a8732951584f6
@cli.group(short_help='Generate and display Bootloader DFU settings.') <NEW_LINE> def settings(): <NEW_LINE> <INDENT> pass
This set of commands supports creating and displaying bootloader settings.
625941ce293b9510aa2c33d1
def test_no_user(self): <NEW_LINE> <INDENT> self.assertEqual(process_client_message({'action': 'presence', 'time': 1607866996.0035086}), self.error_dict, "Ошибка! Работает без параметра user!")
Тест функция, проверяет работу без параметра user :return:
625941cebd1bec0571d9076b
def test_testscenario_object_multi_call_in_run(): <NEW_LINE> <INDENT> obj = TestedMockClass(a="super") <NEW_LINE> scenario = TestScenario( args={ "foo": {"b": "cali"}, "bar": {"c": "fragi", "d": "listic"}, "foo-2nd": {"b": "expi"}, "bar-2nd": {"c": "ali", "d": "docious"}, }, ) <NEW_LINE> result = scenario.run( obj, arg...
Test advanced workflow: run args where methods are called multiple times.
625941ce498bea3a759b9beb
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.material = args[0] <NEW_LINE> self.shape_function = FEIsoParaQuadElement(kwargs['coords'])
This class is used to create Variational Mass Lumping Matrix for a 2D element. :param args: Only one input is required for args. It needs to be a list of element thickness and density respectively :param kwargs: kwargs must be a list of four tuples with key 'coords' e.g. 'coords': [(1,2), (3,4), (5,6), (7,8)]
625941cee5267d203edcddd9
def _setBuildsBuildingForArch(self, builds_list, num_builds, archtag="i386"): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for build in builds_list[:num_builds]: <NEW_LINE> <INDENT> if build.distro_arch_series.architecturetag == archtag: <NEW_LINE> <INDENT> build.updateStatus( BuildStatus.BUILDING, builder=self.builders[co...
Helper function. Set the first `num_builds` in `builds_list` with `archtag` as BUILDING.
625941ce5fdd1c0f98dc036f
def test_006_server_file_add(self): <NEW_LINE> <INDENT> logging.info('START - test_006_server_file_add') <NEW_LINE> logging.info('Writing test006.txt into the server directory') <NEW_LINE> with open(os.path.join(self.SERVER_FOLDER, 'test006.txt'), 'w') as test_file: <NEW_LINE> <INDENT> test_file.write('test_006_server_...
Add a file to the server and check that it is removed after the sync. test006.txt is written into the server directory in preparation for running the client. First the server process is started. The client process is then started. Time is given to allow the transaction to take place. The server directory is checked to...
625941ce3617ad0b5ed68033
def template_develop(args): <NEW_LINE> <INDENT> project, project_dir = args <NEW_LINE> os.chdir(project_dir) <NEW_LINE> subprocess.check_call([ 'hg', 'clone', 'http://hg.tryton.org/trytond' ]) <NEW_LINE> os.chdir(os.path.join(project_dir, 'trytond')) <NEW_LINE> subprocess.check_call(['git', 'checkout', 'develop']) <NEW...
Install the latest development version of tryton
625941ce091ae35668667099
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941ce07d97122c41789c8
def calculateFPostLog(f, xPret, theta, As, Ds, Lambdas, mean=None, std=None, includeDet=False): <NEW_LINE> <INDENT> xPret = np.asarray(xPret) <NEW_LINE> assert len(As) == len(Ds) <NEW_LINE> assert len(Ds) == len(Lambdas) <NEW_LINE> nTime = As[0].shape[0] <NEW_LINE> nStates = len(As) <NEW_LINE> assert nStates*nTime == x...
calculates the second component of the density function, which corresponds to the logarithm of the posterior on F. Parameters ---------- f: function handle function representing the ODEs by mapping x[t] and theta[t] to x_dot[t] takes x as first and theta as second argument xPret: vector of shape nTime*nState...
625941ce7047854f462a1545
def roll(label): <NEW_LINE> <INDENT> assert label.startswith('roll:') <NEW_LINE> _, posns = label.split(':') <NEW_LINE> posns = int(posns) <NEW_LINE> return lambda context: _roll_demand(context, posns)
roll:X rolls the load by X timesteps. >>> roll("roll:3") # doctest: +ELLIPSIS <function roll.<locals>.<lambda> at ...> >>> roll("junk string") Traceback (most recent call last): AssertionError
625941ce8a349b6b435e82af
def parse_numbers(numbers_string): <NEW_LINE> <INDENT> numbers = [] <NEW_LINE> for number_string in numbers_string.split(): <NEW_LINE> <INDENT> numbers.append(int(number_string)) <NEW_LINE> <DEDENT> return numbers
Given a string containing newline-separated numbers, return an array of the numbers.
625941ce50812a4eaa59c45d
def _remove_object_from_db(plugin, context, oper): <NEW_LINE> <INDENT> LOG.debug(_('_remove_object_from_db %s'), str(oper)) <NEW_LINE> if oper.lbaas_entity == lb_db.PoolMonitorAssociation: <NEW_LINE> <INDENT> plugin._delete_db_pool_health_monitor(context, oper.entity_id, oper.object_graph['pool_id']) <NEW_LINE> <DEDENT...
Remove a specific entity from db.
625941ce091ae3566866709a
def testStandardPostmarkResponse(self): <NEW_LINE> <INDENT> model = postmark.models.standard_postmark_response.StandardPostmarkResponse()
Test StandardPostmarkResponse
625941ce0fa83653e46570f7
def _get_array_slices(self, slice_): <NEW_LINE> <INDENT> v2i = self.value2index <NEW_LINE> if isinstance(slice_, slice): <NEW_LINE> <INDENT> start = slice_.start <NEW_LINE> stop = slice_.stop <NEW_LINE> step = slice_.step <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isfloat(slice_): <NEW_LINE> <INDENT> start = v2i(...
Returns a slice to slice the corresponding data axis without changing the offset and scale of the DataAxis. Parameters ---------- slice_ : {float, int, slice} Returns ------- my_slice : slice
625941ce7c178a314d6ef59c
def _get_tt_style_attrs(self, node, in_head=False): <NEW_LINE> <INDENT> style = {} <NEW_LINE> for attr_name in self._allowed_style_attrs: <NEW_LINE> <INDENT> tts = 'tts:' + attr_name <NEW_LINE> attr_name = Ttml2Ssa._snake_to_camel(attr_name) <NEW_LINE> style[attr_name] = node.getAttribute(tts) or '' <NEW_LINE> <DEDENT>...
Extract node's style attributes Node can be a style definition element or a content element (<p>). Attributes are filtered against :attr:`Ttml2Ssa._allowed_style_attrs` and returned as a dict whose keys are attribute names camel cased.
625941ce23849d37ff7b31cb
def destroy(branch=BRANCH, vehicle=False): <NEW_LINE> <INDENT> docker_name = get_docker_name(branch, vehicle) <NEW_LINE> container = get_containers(docker_name) <NEW_LINE> if container: <NEW_LINE> <INDENT> container[0].remove(force=True) <NEW_LINE> print("Removed container for branch={}, vehicle={}".format(branch, vehi...
Remove a container for a branch and clean up the worktree for the branch. branch: Branch workspace to clean up. vehicle: Whether running on the vehicle.
625941cef8510a7c17cf9837
def getCommandLines(): <NEW_LINE> <INDENT> return getFromRegistry(CLI_KEY)
Returns the command lines to launch in order to open the selected IDE.
625941cef9cc0f698b140737
def __init__( self, export_dirs, local_export_root = None, ensemble_size = 1, timeout = 600, tf_config = None, restore_model_option = RestoreOptions.DO_NOT_RESTORE): <NEW_LINE> <INDENT> super(EnsembleExportedSavedModelPredictor, self).__init__() <NEW_LINE> self._export_dirs = export_dirs.split(',') <NEW_LINE> self._loc...
Creates an instance. Args: export_dirs: A comma-separated list of exported saved model directory paths. local_export_root: When loading the model, if export dir does not exist, looks for the basename in local_export_dir. This is useful for on-robot deployments where we want to refer to the export_dir b...
625941ce5fc7496912cc3aba
def affine_forward(x, w, b): <NEW_LINE> <INDENT> out = None <NEW_LINE> N = x.shape[0] <NEW_LINE> D = np.prod(x.shape[1:]) <NEW_LINE> M = b.shape[1] <NEW_LINE> out = np.dot(x.reshape(N, D), w.reshape(D, M)) + b.reshape(1, M) <NEW_LINE> return out, (x,w,b)
Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N examples, where each example x[i] has shape (d_1, ..., d_k). We will reshape each input into a vector of dimension D = d_1 * ... * d_k, and then transform it to an output vector of dim...
625941ce57b8e32f524835d7
def _get_model(self, persist_dict): <NEW_LINE> <INDENT> return persist_dict["model"]
Get the model from the persist dictionary
625941ced268445f265b4fa9
def find_all(self, tag_name, attribute_dict=None, recursive=True, exact_class=False, bfs=False, string=None, string_contains=None, find_first=False): <NEW_LINE> <INDENT> if attribute_dict: <NEW_LINE> <INDENT> assert isinstance(attribute_dict, dict), f"Expected " f"attribute_dict t...
Used to find all tags in within a node that matches the parameters specified
625941ce851cf427c661a64a
def pila(x): <NEW_LINE> <INDENT> woodden = 0.396 <NEW_LINE> biomass = 1.0211*woodden*(0.0000557*x**2.7089) <NEW_LINE> jenkbio = round(0.001*math.exp(-2.5356+2.4349*math.log1p(round(x,2))),5) <NEW_LINE> return(biomass, jenkbio)
T1.3.T2.1 PILA from SQNP used in W Cascades proxy: location, SQNP, range may be different (unknown) badness: potentially too broad source: tv009 accuracy: 0.981
625941cecb5e8a47e48b7be6
def get_tree_size(path, block_size=4096): <NEW_LINE> <INDENT> total_size = items_number = 0 <NEW_LINE> for dir_entry in fault_tolerant_scandir(path): <NEW_LINE> <INDENT> items_number += 1 <NEW_LINE> if os.path.islink(dir_entry.path): <NEW_LINE> <INDENT> total_size += block_size <NEW_LINE> <DEDENT> elif os.path.isdir(di...
Returns total size of files and number of files in the specified directory.
625941ce21bff66bcd684a8e
def _check_ship_alien_collisions(self): <NEW_LINE> <INDENT> if pygame.sprite.spritecollideany(self.ship, self.aliens): <NEW_LINE> <INDENT> self._ship_hit()
Look for alien-ship collisions
625941ce6e29344779a6274e
def evaluate_solution(self): <NEW_LINE> <INDENT> raise NotImplementedError("Solution class have to be implemented.")
求取适应度 接口
625941ced268445f265b4faa
def __render(page, w, h): <NEW_LINE> <INDENT> pageImage = QPixmap(w, h) <NEW_LINE> pageImage.fill(Qt.transparent) <NEW_LINE> p = QPainter(pageImage) <NEW_LINE> page.mainFrame().render(p, QWebFrame.ContentsLayer) <NEW_LINE> p.end() <NEW_LINE> return pageImage
Private function to render a pixmap of given size for a web page. @param page reference to the page to be rendered (QWebPage) @param w width of the pixmap (integer) @param h height of the pixmap (integer) @return rendered pixmap (QPixmap)
625941ce23e79379d52ee6a0
def add_input(self, text, input_handler, width): <NEW_LINE> <INDENT> assert isinstance(text, str), type(text) <NEW_LINE> assert callable(input_handler), type(input_handler) <NEW_LINE> assert isinstance(width, int) or isinstance(width, float), type(width) <NEW_LINE> input = TextAreaControl(self, text, input_handler, wid...
Add a "label" with an input box in the control panel. When click with left button of mouse on the "label" or input box, the focus is give to this input box. When press Tab, the focus is give to the next input box (if exist). When press Enter, this input box lost the focus and `input_handler` are executed with the in...
625941ced53ae8145f87a3ac
def generaete_biom_file(res_df, o, tg_rank, sampleid): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> import biom <NEW_LINE> from biom.table import Table <NEW_LINE> if biom.__version__ < '2.1.7': <NEW_LINE> <INDENT> sys.exit("[ERROR] Biom library requires v2.1.7 or above.\n") <NEW_LINE> <DEDENT> target_df = pd.DataF...
output result in biom format
625941ce442bda511e8be554
def ShannonEntropy(dataSet): <NEW_LINE> <INDENT> numOfData = len(dataSet) <NEW_LINE> labelCount = {} <NEW_LINE> for data in dataSet: <NEW_LINE> <INDENT> if data[-1] not in labelCount.keys(): <NEW_LINE> <INDENT> labelCount[data[-1]] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> labelCount[data[-1]] += 1 <NEW_LINE> <...
Calculate the Shannon Entropy of this dataSet Input: - dataSet: a list of N data, every data has D dimensions. Return: - entropy: The Shannon Entropy of this dataSet, a scaler.
625941ce3317a56b86939d94