code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def _get_style_of_faulting_term(self, C, rake): f_n, f_r = self._get_fault_type_dummy_variables(rake) return C['C6'] * f_n + C['C7'] * f_r
Returns the style of faulting factor
def _handleSmsReceived(self, notificationLine): self.log.debug('SMS message received') cmtiMatch = self.CMTI_REGEX.match(notificationLine) if cmtiMatch: msgMemory = cmtiMatch.group(1) msgIndex = cmtiMatch.group(2) sms = self.readStoredSms(msgIndex, msgMemory) ...
Handler for "new SMS" unsolicited notification line
def InitializeMonitorThread(self): if self.monitor_thread: return self.monitor_thread = utils.InterruptableThread( name="DataStore monitoring thread", target=self._RegisterSize, sleep_time=60) self.monitor_thread.start()
Start the thread that registers the size of the DataStore.
def init_file(self, filename, lines, expected, line_offset): super(_PycodestyleReport, self).init_file( filename, lines, expected, line_offset) self.errors = []
Prepare storage for errors.
def r_num(obj): if isinstance(obj, (list, tuple)): it = iter else: it = LinesIterator dataset = Dataset([Dataset.FLOAT]) return dataset.load(it(obj))
Read list of numbers.
def _process_transform(self, data, transform, step_size): if isinstance(transform, (list,tuple,set)): return { t : self._transform(data,t,step_size) for t in transform } elif isinstance(transform, dict): return { tn : self._transform(data,tf,step_size) for tn,tf in transform.items() } return sel...
Process transforms on the data.
def mouseReleaseEvent(self, event): super(AbstractDragView, self).mouseReleaseEvent(event) self.dragStartPosition = None
Resets the drag start position
def _normalize_url(graph: BELGraph, keyword: str) -> Optional[str]: if keyword == BEL_DEFAULT_NAMESPACE and BEL_DEFAULT_NAMESPACE not in graph.namespace_url: return BEL_DEFAULT_NAMESPACE_URL return graph.namespace_url.get(keyword)
Normalize a URL for the BEL graph.
def _validated(self, data): errors = [] for sub in self.schemas: try: return sub(data) except NotValid as ex: errors.extend(ex.args) raise NotValid(' and '.join(errors))
Validate data if any subschema validates it.
def _GetRow(self, columns=None): row = self._table[self._row_index] if columns: result = [] for col in columns: if col not in self.header: raise TableError("Column header %s not known in table." % col) result.append(row[self.hea...
Returns the current row as a tuple.
def close(self): self.logger = None for exc in _EXCEPTIONS: setattr(self, exc, None) try: self.mdr.close() finally: self.mdr = None
Close the connection this context wraps.
def resolved(value): p = Promise() p._state = 'resolved' p.value = value return p
Creates a promise object resolved with a certain value.
def check(text): err = "glaad.offensive_terms" msg = "Offensive term. Remove it or consider the context." list = [ "fag", "faggot", "dyke", "sodomite", "homosexual agenda", "gay agenda", "transvestite", "homosexual lifestyle", "gay life...
Flag offensive words based on the GLAAD reference guide.
def flip_all(self, tour): if self.signs is None: score = 0 else: old_signs = self.signs[:self.N] score, = self.evaluate_tour_Q(tour) self.signs = get_signs(self.O, validate=False, ambiguous=False) score_flipped, = self.evaluate_tour_Q(tour) if ...
Initialize the orientations based on pairwise O matrix.
def drop_paired_notebook(self, path): if path not in self.paired_notebooks: return fmt, formats = self.paired_notebooks.pop(path) prev_paired_paths = paired_paths(path, fmt, formats) for alt_path, _ in prev_paired_paths: if alt_path in self.paired_notebooks: ...
Remove the current notebook from the list of paired notebooks
def matchCollapsedState( self ): collapsed = not self.isChecked() if self._inverted: collapsed = not collapsed if ( not self.isCollapsible() or not collapsed ): for child in self.children(): if ( not isinstance(child, QWidget) ): con...
Matches the collapsed state for this groupbox.
def req(self, msgtype, payload, flags, size=0, offset=0, timeout=0): if timeout < 0: raise ValueError("timeout cannot be negative!") tohead = _ToServerHeader(payload=len(payload), type=msgtype, flags=flags, size=size, offset=offset) tstartcom = monoto...
send message to server and return response
def list_entitlements(owner, repo, page, page_size, show_tokens): client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_list_with_http_info( owner=owner, repo=repo, page=page, page_size=page_size, ...
Get a list of entitlements on a repository.
def b(s): return s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())
Encodes Unicode strings to byte strings, if necessary.
def earliest_possible_date(): today = pd.Timestamp('now', tz='UTC').normalize() return today.replace(year=today.year - 10)
The earliest date for which we can load data from this module.
def sort_generators(self): self.generators.sort(key=lambda gn: gn.bus._i)
Reorders the list of generators according to bus index.
def DocbookXslt(env, target, source=None, *args, **kw): target, source = __extend_targets_sources(target, source) kw['DOCBOOK_XSL'] = kw.get('xsl', 'transform.xsl') __builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder) result = [] for t,s in zip(target,source): ...
A pseudo-Builder, applying a simple XSL transformation to the input file.
def read(self): __result = [] __ll = self.readline() while __ll: __result.append(__ll) __ll = self.readline() return list(__result)
Read the file until EOF and return a list of dictionaries.
def visit_with(self, node): items = ", ".join( ("%s" % expr.accept(self)) + (vars and " as %s" % (vars.accept(self)) or "") for expr, vars in node.items ) return "with %s:\n%s" % (items, self._stmt_list(node.body))
return an astroid.With node as string
def kill_all(): for i in dispatchers.all_instances(): try: os.kill(-i.pid, signal.SIGKILL) except OSError: pass
When polysh quits, we kill all the remote shells we started
def _get_relative_path(self): param_string = self._get_query_string() if self.path is None: path = '/' else: path = self.path if param_string: return '?'.join([path, param_string]) else: return path
Returns the path with the query parameters escaped and appended.
def address(self) -> str: return str(self._public_key.to_address( net_query(self.network)) )
generate an address from pubkey
def setup_logfile(self, logfile, mode='w'): self.logfile = open(logfile, mode=mode)
start logging to the given logfile, with timestamps
def config_dir(mkcustom=False): from acorn.utility import reporoot from acorn.base import testmode from os import path alternate = path.join(path.abspath(path.expanduser("~")), ".acorn") if testmode or (not path.isdir(alternate) and not mkcustom): return path.join(reporoot, "acorn", "config"...
Returns the configuration directory for custom package settings.
def structureOutput(fileUrl, fileName, searchFiles, format=True, space=40): if format: splitUrls = fileUrl[1:].split('/') fileUrl = "" for splitUrl in splitUrls: if splitUrl != "" and (not "." in splitUrl) and (splitUrl != "pub" and splitUrl != "files"): fileUrl += splitUrl + '/' elif "." in splitUrl: ...
Formats the output of a list of packages
def run_index_cmd(name, cmd): sys.stderr.write("Creating {} index...\n".format(name)) p = sp.Popen(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE) stdout, stderr = p.communicate() if p.returncode != 0: sys.stderr.write("Index for {} failed\n".format(name)) sys.stderr.write(stdout) ...
Run command, show errors if the returncode is non-zero.
async def status(self, switch=None): if switch is not None: if self.waiters or self.in_transaction: fut = self.loop.create_future() self.status_waiters.append(fut) states = await fut state = states[switch] else: ...
Get current relay status.
def _get_instance_state(self): instance = self._get_instance() statuses = instance.instance_view.statuses for status in statuses: if status.code.startswith('PowerState'): return status.display_status
Retrieve state of instance.
def encode_sid(cls, secret, sid): secret_bytes = secret.encode("utf-8") sid_bytes = sid.encode("utf-8") sig = hmac.new(secret_bytes, sid_bytes, hashlib.sha512).hexdigest() return "%s%s" % (sig, sid)
Computes the HMAC for the given session id.
def hasPublicNet(self, system_name): nets_id = [net.id for net in self.networks if net.isPublic()] system = self.get_system_by_name(system_name) if system: i = 0 while True: f = system.getFeature("net_interface.%d.connection" % i) if not f:...
Return true if some system has a public network.
def parmap(f, X, nprocs=multiprocessing.cpu_count()): q_in = multiprocessing.Queue(1) q_out = multiprocessing.Queue() proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out)) for _ in range(nprocs)] for p in proc: p.daemon = True p.start() sent = [q_in.put((i, x...
paralell map for multiprocessing
def create(cls, event): release_id = event.payload['release']['id'] existing_release = Release.query.filter_by( release_id=release_id, ).first() if existing_release: raise ReleaseAlreadyReceivedError( u'{release} has already been received.' ...
Create a new Release model.
def reset(self) -> None: self.evaluating = set() self.assumptions = {} self.known_results = {} self.current_node = None self.evaluate_stack = [] self.bnode_map = {}
Reset the context preceeding an evaluation
def _serialize(self, zenpy_object): if not type(zenpy_object) == dict: log.debug("Setting dirty object: {}".format(zenpy_object)) self._dirty_object = zenpy_object return json.loads(json.dumps(zenpy_object, default=json_encode_for_zendesk))
Serialize a Zenpy object to JSON
def add_account_to_group(self, account, group): lgroup: OpenldapGroup = self._get_group(group.name) person: OpenldapAccount = self._get_account(account.username) changes = changeset(lgroup, {}) changes = lgroup.add_member(changes, person) save(changes, database=self._database)
Add account to group.
def utf(text): try: output = unicode(text, encoding='utf-8') except UnicodeDecodeError: output = text except TypeError: output = text return output
Shortcut funnction for encoding given text with utf-8
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): if breadcrumb: return nodes for node in nodes: if node.attr.get('hidden'): node.visible = False return nodes
Modify nodes of a menu
def read_targets(targets): results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) return results
Reads generic key-value pairs from input files
def AgregarPrecioClase(self, clase_tabaco, precio, total_kilos=None, total_fardos=None, **kwargs): "Agrego un PrecioClase a la liq." precioclase = dict(claseTabaco=clase_tabaco, precio=precio, totalKilos=total_kilos, totalFardos=total_fardos) self.solicitud['precioClas...
Agrego un PrecioClase a la liq.
def to_match(self): self.validate() def visitor_fn(expression): if isinstance(expression, TernaryConditional): raise ValueError(u'Cannot emit MATCH code for TernaryConditional that contains ' u'in its predicate another TernaryConditional: ' ...
Return a unicode object with the MATCH representation of this TernaryConditional.
def default_redirect(request, fallback_url, **kwargs): redirect_field_name = kwargs.get("redirect_field_name", "next") next = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if not next: if hasattr(request, "session"): session_k...
Evaluates a redirect url by consulting GET, POST and the session.
def _wrap_result(self, result): if isinstance(result, ABCSeries) and self._selection is not None: result.name = self._selection if isinstance(result, ABCSeries) and result.empty: obj = self.obj if isinstance(obj.index, PeriodIndex): result.index = obj....
Potentially wrap any results.
def clip_slices(r, region, scale=1): t = [] for ch in r: a1 = intersection(ch[0], region[0], scale=scale) if a1 is None: continue a2 = intersection(ch[1], region[1], scale=scale) if a2 is None: continue t.append((a1, a2)) return t
Intersect slices with a region.
def _from_dict(cls, _dict): args = {} if 'languages' in _dict: args['languages'] = [ IdentifiableLanguage._from_dict(x) for x in (_dict.get('languages')) ] else: raise ValueError( 'Required property \'languages\'...
Initialize a IdentifiableLanguages object from a json dictionary.
def make_dict(self): out = {} while True: try: key = self.dict_key() self.separator(separator=":") value = self.value_assign(end_token="]") out[key] = value self.separator(end_token="}") except self.P...
We are in a dict so get key value pairs until the end token.
def _create_auth(team, timeout=None): url = get_registry_url(team) contents = _load_auth() auth = contents.get(url) if auth is not None: if auth['expires_at'] < time.time() + 60: try: auth = _update_auth(team, auth['refresh_token'], timeout) except Command...
Reads the credentials, updates the access token if necessary, and returns it.
def warning_msg_callback(self, callback): if callable(callback): self._warning_msg_callback = callback else: self._warning_msg_callback = None
Set the warning message callback.
def artboards(src_path): pages = list_artboards(src_path) artboards = [] for page in pages: artboards.extend(page.artboards) return artboards
Return artboards as a flat list
def warn(self, cmd, desc=''): return self._label_desc(cmd, desc, self.warn_color)
Style for warning message.
def validate_contribution(the_con): passing = True for dtype in list(the_con.tables.keys()): print("validating {}".format(dtype)) fail = validate_table(the_con, dtype) if fail: passing = False print('--')
Go through a Contribution and validate each table
def _db_install(self, db_name): self._logger.info("Installing NIPAP database schemas into db") self._execute(db_schema.ip_net % (db_name)) self._execute(db_schema.functions) self._execute(db_schema.triggers)
Install nipap database schema
def _mark_received(self, tsn): if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True self._sack_misordered.add(tsn) for tsn in sorted(self._sack_misordered): if tsn == tsn_plus_one(self._last...
Mark an incoming data TSN as received.
def where(cmd, path=None): raw_result = shutil.which(cmd, os.X_OK, path) if raw_result: return os.path.abspath(raw_result) else: raise ValueError("Could not find '{}' in the path".format(cmd))
A function to wrap shutil.which for universal usage
def __add_tokenization(self, tree): for token_id in self.get_token_ids(tree): self.add_node(token_id, layers={self.ns}) self.tokens.append(token_id)
adds a node for each token ID in the document
def use_plenary_objective_bank_view(self): self._objective_bank_view = PLENARY for session in self._get_provider_sessions(): try: session.use_plenary_objective_bank_view() except AttributeError: pass
Pass through to provider ObjectiveObjectiveBankSession.use_plenary_objective_bank_view
def filter_roidb(self): num_roidb = len(self._roidb) self._roidb = [roi_rec for roi_rec in self._roidb if len(roi_rec['gt_classes'])] num_after = len(self._roidb) logger.info('filter roidb: {} -> {}'.format(num_roidb, num_after))
Remove images without usable rois
def _VerifyExtensionHandle(message, extension_handle): if not isinstance(extension_handle, _FieldDescriptor): raise KeyError('HasExtension() expects an extension handle, got: %s' % extension_handle) if not extension_handle.is_extension: raise KeyError('"%s" is not an extension.' % extensi...
Verify that the given extension handle is valid.
def overall(): return ZeroOrMore(Grammar.comment) + Dict(ZeroOrMore(Group( Grammar._section + ZeroOrMore(Group(Grammar.line))) ))
The overall grammer for pulling apart the main input files.
def history(self, **kwargs): url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id'] del kwargs['alarm_id'] if kwargs: url_str = url_str + '?%s' % parse.urlencode(kwargs, True) resp = self.client.list(url_str) return resp['elements'] if type(resp) is dict e...
History of a specific alarm.
def validate(self): if not self.editable: assert self.populate_from is not NotSet, u"If field (%s) is not editable, you must set populate_from" % self.name
Discover certain illegal configurations
def to_binary_string(self, code, identifier): return struct.pack(self.FORMAT, self.COMMAND, code, identifier)
Pack the error response to binary string and return it.
def getbalance(self, address: str) -> Decimal: try: return Decimal(cast(float, self.ext_fetch('getbalance/' + address))) except TypeError: return Decimal(0)
Returns current balance of given address.
def getKnownPlayers(reset=False): global playerCache if not playerCache or reset: jsonFiles = os.path.join(c.PLAYERS_FOLDER, "*.json") for playerFilepath in glob.glob(jsonFiles): filename = os.path.basename(playerFilepath) name = re.sub("^player_", "", filename) ...
identify all of the currently defined players
def OnVideoCell(self, event): if self.video_cell_button_id == event.GetId(): if event.IsChecked(): wildcard = _("Media files") + " (*.*)|*.*" videofile, __ = self.get_filepath_findex_from_user( wildcard, "Choose video or audio file", wx.OPEN) ...
Event handler for video cell toggle button
def main(argv): _, black_model, white_model = argv utils.ensure_dir_exists(FLAGS.eval_sgf_dir) play_match(black_model, white_model, FLAGS.num_evaluation_games, FLAGS.eval_sgf_dir)
Play matches between two neural nets.
def _canonical_type(name): if name == 'int': return 'int256' if name == 'uint': return 'uint256' if name == 'fixed': return 'fixed128x128' if name == 'ufixed': return 'ufixed128x128' if name.startswith('int['): return 'int256' + name[3:] if name.startswith...
Replace aliases to the corresponding type to compute the ids.
def emit(self, record): self.entries.append(self.format(record)) if len(self.entries) > self.flush_limit and not self.session.auth.renewing: self.log_to_api() self.entries = []
Emit the log record.
def stop(self, wait=False): if self.instance_id is not None: log.info("Shutting down node `%s` (VM instance `%s`) ...", self.name, self.instance_id) self._cloud_provider.stop_instance(self.instance_id) if wait: while self.is_alive(): ...
Terminate the VM instance launched on the cloud for this specific node.
def process(self, request, item): warn_untested() from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) params = self.cleaned_data params['creditcardtype'] = self.fields['acct'].card_type params['expdate'] = self.cleaned_data['expdate'].strftime("%m%Y") ...
Process a PayPal direct payment.
def parse_class_id(self, sel, m, has_selector): selector = m.group(0) if selector.startswith('.'): sel.classes.append(css_unescape(selector[1:])) else: sel.ids.append(css_unescape(selector[1:])) has_selector = True return has_selector
Parse HTML classes and ids.
def time_to_first_byte(self): if self.page_id == 'unknown': return None ttfb = 0 for entry in self.entries: if entry['response']['status'] == 200: for k, v in iteritems(entry['timings']): if k != 'receive': if v ...
Time to first byte of the page request in ms
def extract_frames(self, bpf_buffer): len_bb = len(bpf_buffer) if len_bb < 20: return if FREEBSD or NETBSD: bh_tstamp_offset = 16 else: bh_tstamp_offset = 8 bh_caplen = struct.unpack('I', bpf_buffer[bh_tstamp_offset:bh_tstamp_offset + 4])[0] ...
Extract all frames from the buffer and stored them in the received list.
def corner_depots(self) -> Set[Point2]: if len(self.upper2_for_ramp_wall) == 2: points = self.upper2_for_ramp_wall p1 = points.pop().offset((self.x_offset, self.y_offset)) p2 = points.pop().offset((self.x_offset, self.y_offset)) center = p1.towards(p2, p1.distance...
Finds the 2 depot positions on the outside
def harden_attention_weights(weights, hard_attention_k): weights -= common_layers.top_kth_iterative(weights, hard_attention_k) weights = tf.nn.relu(weights) weights_sum = tf.reduce_sum(weights, axis=-1, keep_dims=True) weights_sum = tf.maximum(weights_sum, 1e-6) weights /= weights_sum return weights
Make attention weights non-0 only on the top-hard_attention_k ones.
def calculate_month(birth_date): year = int(birth_date.strftime('%Y')) month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20 return month
Calculates and returns a month number basing on PESEL standard.
def create_from_name_and_dictionary(self, name, datas): parameter = ObjectParameter() self.set_common_datas(parameter, name, datas) if "optional" in datas: parameter.optional = to_boolean(datas["optional"]) if "type" in datas: parameter.type = str(datas["type"]) ...
Return a populated object Parameter from dictionary datas
def _fill_file_path(line, data): def _find_file(xs, target): if isinstance(xs, dict): for v in xs.values(): f = _find_file(v, target) if f: return f elif isinstance(xs, (list, tuple)): for x in xs: f = _find_...
Fill in a full file path in the configuration file from data dictionary.
def write_file(self, filename=None, buffer=None, fileobj=None): closefile = True if buffer: self.filename = None self.file = buffer closefile = False elif filename: self.filename = filename self.file = GzipFile(filename, "wb") e...
Write this NBT file to a file.
def rsl_dump_stream_next(self, output_format): timestamp = 0 stream_id = 0 value = 0 reading_id = 0 error = Error.NO_ERROR reading = self.sensor_log.dump_next() if reading is not None: timestamp = reading.raw_time stream_id = reading.stream...
Dump the next reading from the output stream.
def detached(self, worker): for wfb in self.attaching_workers + self.workers: if wfb.worker == worker: break else: log.msg("WEIRD: Builder.detached(%s) (%s)" " not in attaching_workers(%s)" " or workers(%s)" % (worker, worke...
This is called when the connection to the bot is lost.
def right(self): return self.source.directory[self.right_sibling_id] \ if self.right_sibling_id != NOSTREAM else None
Entry is right sibling of current directory entry
def server_lia_countries(self): response = self._post(self.apiurl + "/v2/server/lia_countries", data={'apikey': self.apikey}) return self._raise_or_extract(response)
Show the available localized internet anonymization countries.
def bind(self, func): if self.__methods__ is None: self.__methods__ = {} self.__methods__[func.__name__] = BoundFunction(func)
Take a function and create a bound method
def add_variables_to_context(generator): context = generator.context context['relpath_to_site'] = relpath_to_site context['main_siteurl'] = _MAIN_SITEURL context['main_lang'] = _MAIN_LANG context['lang_siteurls'] = _SITE_DB current_lang = generator.settings['DEFAULT_LANG'] extra_siteurls = _...
Adds useful iterable variables to template context
def run_analysis(self, argv): args = self._parser.parse_args(argv) components = Component.build_from_yamlfile(args.comp) NAME_FACTORY.update_base_dict(args.data) model_dict = make_library(**args.__dict__) model_manager = model_dict['ModelManager'] models = load_yaml(args....
Build the manifest for all the models
def list_styles(self): known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(...
Print available styles and exit.
def header_echo(cls, request, api_key: (Ptypes.header, String('API key'))) -> [ (200, 'Ok', String)]: log.info('Echoing header param, value is: {}'.format(api_key)) for i in range(randint(0, MAX_LOOP_DURATION)): yield msg = 'The value sent was: {}'.for...
Echo the header parameter.
def itn(n, digits=8, format=DEFAULT_FORMAT): if 0 <= n < 8 ** (digits - 1): s = ("%0*o" % (digits - 1, n)).encode("ascii") + NUL else: if format != GNU_FORMAT or n >= 256 ** (digits - 1): raise ValueError("overflow in number field") if n < 0: n = struct.unpack("L"...
Convert a python number to a number field.
def create_image(cloud, **kwargs): if cloud == 'ec2': return create_ami(**kwargs) if cloud == 'rackspace': return create_rackspace_image(**kwargs) if cloud == 'gce': return create_gce_image(**kwargs)
proxy call for ec2, rackspace create ami backend functions
def _build_static_validator(exact_value): def static_validator(data): if data == exact_value: return data raise NotValid('%r is not equal to %r' % (data, exact_value)) return static_validator
Build a validator that checks if the data is equal to an exact value.
def _view_changed(self, event=None): tr = self.node_transform(self._linked_view.scene) p1, p2 = tr.map(self._axis_ends()) if self.orientation in ('left', 'right'): self.axis.domain = (p1[1], p2[1]) else: self.axis.domain = (p1[0], p2[0])
Linked view transform has changed; update ticks.
def includeme(config): config.add_route('references', '/references') _add_referencer(config.registry) config.add_view_deriver(protected_resources.protected_view) config.add_renderer('json_item', json_renderer) config.scan()
this function adds some configuration for the application
def merge(request, obj_id): res = Result() if request.POST: tags = json.loads(request.POST['tags']) else: tags = json.loads(request.body)['body']['tags'] guids = [] images = Image.objects.filter(tags__id__in=tags) guids += [_.guid for _ in images] videos = Video.objects.filte...
Merges multiple tags into a single tag and all related objects are reassigned
def repr_setup(self, name=None, col_names=None, col_types=None): self._name = name or self._name self._col_types = col_types or self._col_types
This wasn't safe to pass into init because of the inheritance
def replace_tag(self, resource_type, resource_id, body, **_params): return self.put(self.tags_path % (resource_type, resource_id), body)
Replace tags on the resource.