language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void setEntityId(String v) { if (DictTerm_Type.featOkTst && ((DictTerm_Type)jcasType).casFeat_entityId == null) jcasType.jcas.throwFeatMissing("entityId", "ch.epfl.bbp.uima.types.DictTerm"); jcasType.ll_cas.ll_setStringValue(addr, ((DictTerm_Type)jcasType).casFeatCode_entityId, v);}
java
public DataObjectModel hide(String... properties) { DataObjectModel view = clone(); view.propertyList = new ArrayList<String>(); view.propertyList.addAll(this.propertyList); for (String property : properties) { view.propertyList.remove(property); }...
java
public void selectByValue(String value) { getDispatcher().beforeSelect(this, value); new Select(getElement()).selectByValue(value); if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIActions(UIActions.SELECTED, value); } getD...
java
protected void doHandleTargetedRequest(final Request request) { // Check for file id String fileId = request.getParameter(FILE_UPLOAD_ID_KEY); if (fileId == null) { throw new SystemException("No file id provided for content request."); } // Check valid file id FileWidgetUpload file = getFile(fileId); ...
python
def shutdown(self): """ Called by the server to commence a graceful shutdown. """ if self.cycle is None or self.cycle.response_complete: self.transport.close() else: self.cycle.keep_alive = False
python
def _get_api_params(api_url=None, page_id=None, api_key=None, api_version=None): ''' Retrieve the API params from the config file. ''' statuspage_cfg = __salt__['config.get']('statuspage') if not statuspage_cfg: statuspage_cfg = {} ...
java
public static BloomSpecification computeBloomSpec(int maxBucketsPerElement, double maxFalsePosProb) { assert maxBucketsPerElement >= 1; assert maxBucketsPerElement <= probs.length - 1; int maxK = probs[maxBucketsPerElement].length - 1; // Handle the trivial cases if(maxFalse...
python
def greedy_merge( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Greedily merge overlapping sequences into longer sequences. Accepts a collection of VariantSequence objects and returns another collection of elongated variant sequences. The reads fie...
java
public Object processInvocation(final InterceptorContext context) throws Exception { try { Method method = this.method; if (withContext) { if (changeMethod) { final Method oldMethod = context.getMethod(); context.setMethod(method); ...
java
public static GrayU8 labelToBinary(GrayS32 labelImage , GrayU8 binaryImage ) { binaryImage = InputSanityCheck.checkDeclare(labelImage, binaryImage, GrayU8.class); if( BoofConcurrency.USE_CONCURRENT ) { ImplBinaryImageOps_MT.labelToBinary(labelImage, binaryImage); } else { ImplBinaryImageOps.labelToBinary(l...
java
@SuppressWarnings("unchecked") public static <T extends Sorter> T createSorter(final SortType type) { switch (ObjectUtils.defaultIfNull(type, SortType.UNKONWN)) { case BUBBLE_SORT: return (T) new BubbleSort(); case COMB_SORT: return (T) new CombSort(); case HEAP_SORT: ret...
python
def locateChild(self, context, segments): """ Return a statically defined child or a child defined by a site root plugin or an avatar from guard. """ request = IRequest(context) webViewer = IWebViewer(self.store, None) childAndSegments = self.siteProduceResource(r...
python
def store_mapping(self, path): """Store the current Id mappings into a TSV file.""" with open(path, "w") as writer: for key, value in self.mapping.iteritems(): writer.write("{}\t{}\n".format(key, value))
python
def file_transfer( ssh_conn, source_file, dest_file, file_system=None, direction="put", disable_md5=False, inline_transfer=False, overwrite_file=False, ): """Use Secure Copy or Inline (IOS-only) to transfer files to/from network devices. inline_transfer ONLY SUPPORTS TEXT FILES ...
java
private PrintStream setUpNewPrintStream(final boolean visitorStream, final String... names) { PrintStream out = System.out; if (folder == null) { if (visitorStream) { out.println(); } } else { final File toWriteTo = new File(folder, buildFile...
java
public List<Rev> getPageRevisions(String pageTitle, int revisionLimit, final String rvprop, String queryParams) throws Exception { if (StringUtils.isBlank(pageTitle)) { throw new IllegalArgumentException("Please provide a valid page title."); } if (revisionLimit < 1 || revisionLimit > 500) { thr...
python
def suggestion_delete(self, account_id): """ Remove the user with the given `account_id` from the follow suggestions. """ account_id = self.__unpack_id(account_id) url = '/api/v1/suggestions/{0}'.format(str(account_id)) self.__api_request('DELETE', url)
python
def Parse(self, stat, file_object, knowledge_base): """Parse the netgroup file and return User objects. Lines are of the form: group1 (-,user1,) (-,user2,) (-,user3,) Groups are ignored, we return users in lines that match the filter regexes, or all users in the file if no filters are specified....
java
public String convertBDDReserved2ToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def iter_lines(url_or_text, ext=None, mode='rt'): r""" Return an iterator over the lines of a file or URI response. >>> len(list(iter_lines('cats_and_dogs.txt'))) 263 >>> len(list(iter_lines(list('abcdefgh')))) 8 >>> len(list(iter_lines('abc\n def\n gh\n'))) 3 >>> len(list(iter_lines('a...
java
public synchronized void addElement(@NonNull T element) { hashCached = false; this.elementsMap.put(element.getLabel(), element); this.elements.add(element); }
java
@Override public DisableImportFindingsForProductResult disableImportFindingsForProduct(DisableImportFindingsForProductRequest request) { request = beforeClientExecution(request); return executeDisableImportFindingsForProduct(request); }
java
public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) { this.callback = callback; JSObject doc = (JSObject) getJSObject().eval("document"); doc.setMember(getVariableName(), this); StringBuilder r = new StringBuilder(getV...
python
def write(graph, fileformat=None, filename=None): """ A basic graph writer (to stdout) for any of the sources. this will write raw triples in rdfxml, unless specified. to write turtle, specify format='turtle' an optional file can be supplied instead of stdout :return: Non...
python
def rm_command( ignore_missing, star_silent, recursive, enable_globs, endpoint_plus_path, label, submission_id, dry_run, deadline, skip_activation_check, notify, meow, heartbeat, polling_interval, timeout, timeout_exit_code, ): """ Executor for `gl...
python
def to_mask(self, size, start_name='start', stop_name='end'): """Construct a mask array where elements are True if the fall within features in the table. Parameters ---------- size : int Size of chromosome/contig. start_name : string, optional Na...
python
def token(self): """ Token given by Transbank for payment initialization url. Will raise PaymentError when an error ocurred. """ if not self._token: self._token = self.fetch_token() logger.payment(self) return self._token
python
def add_listener(self, callback, event_type=None): """Add a callback handler for events going to this room. Args: callback (func(room, event)): Callback called when an event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique i...
java
@Override public DescribeSMBSettingsResult describeSMBSettings(DescribeSMBSettingsRequest request) { request = beforeClientExecution(request); return executeDescribeSMBSettings(request); }
java
public static BigMoney ofMinor(CurrencyUnit currency, long amountMinor) { MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null"); return BigMoney.of(currency, BigDecimal.valueOf(amountMinor, currency.getDecimalPlaces())); }
python
def ajax_recalculate_records(self): """Recalculate all AR records and dependencies - samples - templates - profiles - services - dependecies XXX: This function has grown too much and needs refactoring! """ out = {} # ...
python
def load_messages(self, directory, catalogue): """ Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError ...
python
def is_running(self) -> bool: """Specifies whether or not the thread is running""" return ( self._has_started and self.is_alive() or self.completed_at is None or (datetime.utcnow() - self.completed_at).total_seconds() < 0.5 )
python
def get_project_trend_graph_url(project, start, end): """Generates a bar graph for a project. """ filename = get_project_trend_graph_filename(project, start, end) urls = { 'graph_url': urlparse.urljoin(GRAPH_URL, filename + ".png"), 'data_url': urlparse.urljoin(GRAPH_URL, filename + ".csv")...
java
protected Record getOrNullIfExpired(Record record, long now, boolean backup) { if (!isRecordStoreExpirable()) { return record; } if (record == null) { return null; } Data key = record.getKey(); if (isLocked(key)) { return record; ...
python
def dl(self, ds_type:DatasetType=DatasetType.Valid)->DeviceDataLoader: "Returns appropriate `Dataset` for validation, training, or test (`ds_type`)." #TODO: refactor return (self.train_dl if ds_type == DatasetType.Train else self.test_dl if ds_type == DatasetType.Test else ...
java
public synchronized static void read(int fd, int length, OutputStream stream) throws IOException{ stream.write(read(fd, length)); }
python
def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica: """ Create a new replica with the specified parameters. """ return self._replica_class(self._node, instance_id, self._config, is_master, bls_bft, self._metrics)
python
def _organize_step_scatter(step, inputs, remapped): """Add scattering information from inputs, remapping input variables. """ def extract_scatter_id(inp): _, ns_var = inp.split("#") _, var = ns_var.split("/") return var scatter_local = {} if "scatter" in step.tool: as...
java
@Nonnull public static HeightSpec abs (@Nonnegative final float fValue) { ValueEnforcer.isGT0 (fValue, "Value"); return new HeightSpec (EValueUOMType.ABSOLUTE, fValue); }
python
def url_scan(self, url, opts, functionality, enabled_functionality, hide_progressbar): """ This is the main function called whenever a URL needs to be scanned. This is called when a user specifies an individual CMS, or after CMS identification has taken place. This function is called for...
java
public List<TypedDependency> getStanfordTypedDependencies(DependencyForm form) { List<TypedDependency> dependencies = new ArrayList<TypedDependency>(); if (this.nodes == null) nodes = getStanfordTreeGraphNodes(form); List<AgigaTypedDependency> agigaDeps = getAgigaDeps(form); fo...
python
def filter_used_routes( transfers_pair: List[MediationPairState], routes: List[RouteState], ) -> List[RouteState]: """This function makes sure we filter routes that have already been used. So in a setup like this, we want to make sure that node 2, having tried to route the transfer through ...
java
public static void setReplicationsPending(Context context, Class<? extends PeriodicReplicationService> prsClass, boolean pending) { SharedPreferences prefs = context.getSharedPreferences(PREFERENCES_FILE_NAME, Context .MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); ...
java
public String fixValue(String value) { logger.trace("Fix label value : ", value); if (value != null && !value.equals("")) { value = value.toUpperCase(); if (value.startsWith("MI ")) value = value.replaceFirst("MI ", ""); if (value.startsWith("MEN ")) value = value.replaceFirst("MEN ", ""); ...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "Sphere", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "_GriddedSurface") public JAXBElement<SphereType> createSphere(SphereType value) { return new JAXBElement<SphereType>(_Sphere_QNAME, SphereType.class, n...
java
public void apply(Message m, int error, TSIGRecord old) { Record r = generate(m, m.toWire(), error, old); m.addRecord(r, Section.ADDITIONAL); m.tsigState = Message.TSIG_SIGNED; }
java
public int diff_levenshtein(LinkedList<Diff> diffs) { int levenshtein = 0; int insertions = 0; int deletions = 0; for (Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: insertions += aDiff.text.length(); break; ...
java
@Override public double execute(Geometry geom1, Geometry geom2, ProgressTracker progressTracker) { if (null == geom1 || null == geom2) { throw new IllegalArgumentException(); } Geometry geometryA = geom1; Geometry geometryB = geom2; if (geometryA.isEmpty() || geometryB.isEmpty()) return NumberUtil...
python
def get_nodes(code, desired_type, path="__main__", mode="exec", tree=None): """Find all nodes of a given type Arguments: code -- code text desired_type -- ast Node or tuple Keyword Arguments: path -- code path mode -- execution mode (exec, eval, single) tree -- current tree, if it wa...
python
def save_feature(self, cat, img, feature, data): """Saves a new feature.""" filename = self.path(cat, img, feature) mkdir(filename) savemat(filename, {'output':data})
java
public static <T> Field create(Type type, T value, Map<String, String> attributes) { return new Field(Utils.checkNotNull(type, "type"), type.convert(value), attributes); }
java
public static <T> Collection<T> diff(Collection<T> list1, Collection<T> list2) { Collection<T> diff = new ArrayList<T>(); for (T t : list1) { if (!list2.contains(t)) { diff.add(t); } } return diff; }
python
def create(self, name=None, **kwargs): """ Create a volume. Args: name (str): Name of the volume. If not specified, the engine generates a name. driver (str): Name of the driver used to create the volume driver_opts (dict): Driver options as ...
java
@Override public synchronized void onNext(final ClientRuntimeProtocol.JobControlProto jobControlProto) { if (jobControlProto.hasSignal()) { if (jobControlProto.getSignal() == ClientRuntimeProtocol.Signal.SIG_TERMINATE) { try { if (jobControlProto.hasMessage()) { getClientCloseW...
java
public Observable<JobTargetGroupInner> getAsync(String resourceGroupName, String serverName, String jobAgentName, String targetGroupName) { return getWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, targetGroupName).map(new Func1<ServiceResponse<JobTargetGroupInner>, JobTargetGroupInner>() ...
python
def parse_alt_text(alt): """ Parses the arguments out from a Publ-Markdown alt text into a tuple of text, args """ match = re.match(r'([^\{]*)(\{(.*)\})$', alt) if match: alt = match.group(1) args = parse_arglist(match.group(3)) else: args = {} return alt, args
java
@Override public String getHeader(String key) { ServletRESTRequestImpl ret = castRequest(); if (ret != null) return ret.getHeader(key); return null; }
python
def target_range(self): """Get the range on the target strand :return: target range :rtype: GenomicRange """ if not self.is_aligned(): return None if self._target_range: return self._target_range # check cache global _sam_cigar_target_add tlen = sum([x[0] for x in self.cigar_array if _s...
java
public static void init(String[] args) throws UnknownHostException { boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false; boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false; boolean mlst = false...
python
def get_sticker_set(self, name): """ Use this method to get a sticker set. On success, a StickerSet object is returned. https://core.telegram.org/bots/api#getstickerset Parameters: :param name: Name of the sticker set :type name: str|unicode ...
java
private static int mod(int a, final int B) { final int N = a / B; a -= N * B; if (a < 0) { return a + B; } return a; }
python
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing.""" status = status_map.get(error_status_code or self.DEFAULT_VALIDATION_STATUS) if status is None: raise LookupError("Status code {0} not supported".format(error_status_cod...
java
public float time_tell(){ // translate time to PCM position and call pcm_seek int link=-1; long pcm_total=0; float time_total=0.f; if(seekable){ pcm_total=pcm_total(-1); time_total=time_total(-1); // which bitstream section does this time offset occur in? for(link=links-1;...
java
public String convertIfcConstructionProductResourceTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def _variant_to_dsl_helper(tokens) -> Variant: """Convert variant tokens to DSL objects. :type tokens: ParseResult """ kind = tokens[KIND] if kind == HGVS: return hgvs(tokens[IDENTIFIER]) if kind == GMOD: return gmod( name=tokens[IDENTIFIER][NAME], name...
python
def _create_online_model(self, lattice_instance, use_bl, mode='simu'): """ make online model according to the lattice.Lattice instance :param lattice_instance: lattice.Lattice instance, created from lte/json file :param use_bl: selected beamline name :param simu: online model...
python
def log_debug(func, *args, **kwargs): ''' Wrap call of provided function with debug log statements. ''' logging.debug('Starting "%s" in thread %s...', func.__name__, current_thread()) results = func(*args, **kwargs) logging.debug('Successfully finished "%s" in thread %s.', func.__name__, current_thread(...
python
def prin(*args, **kwargs): r"""Like ``print``, but a function. I.e. prints out all arguments as ``print`` would do. Specify output stream like this:: print('ERROR', `out="sys.stderr"``). """ print >> kwargs.get('out',None), " ".join([str(arg) for arg in args])
python
def select_between_exonic_splice_site_and_alternate_effect(effect): """ If the given effect is an ExonicSpliceSite then it might contain an alternate effect of higher priority. In that case, return the alternate effect. Otherwise, this acts as an identity function. """ if effect.__class__ is not...
python
def _join_disease(query, disease_definition, disease_id, disease_name): """helper function to add a query join to Disease model :param sqlalchemy.orm.query.Query query: SQL Alchemy query :param disease_definition: :param str disease_id: see :attr:`models.Disease.disease_id` ...
python
def _assemble_corpus_string(self, corpus): """Takes a list of filepaths, returns a string containing contents of all files.""" if corpus == 'phi5': filepaths = assemble_phi5_author_filepaths() file_cleaner = phi5_plaintext_cleanup elif corpus == 'tlg': ...
java
private void setComponents() { CmsUriSplitter splitter = new CmsUriSplitter(m_uri, true); m_target = splitter.getPrefix(); m_anchor = CmsLinkProcessor.unescapeLink(splitter.getAnchor()); setQuery(splitter.getQuery()); }
python
def login(self, return_to=None, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None): """ Initiates the SSO process. :param return_to: Optional argument. The target URL the user should be redirected to after login. :type return_to: string :param ...
java
public String joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) { return collect(DoubleCollector.joining(delimiter, prefix, suffix)); }
python
def get_sensor_code_by_number(si, mtype, sensor_number, quiet=False): """ Given a sensor number, get the full sensor code (e.g. ACCX-UB1-L2C-M) :param si: dict, sensor index json dictionary :param mtype: str, sensor type :param sensor_number: int, number of sensor :param quiet: bool, if true th...
python
def install_client_interceptors(client_interceptors=()): """ Install client interceptors for the patchers. :param client_interceptors: a list of client interceptors to install. Should be a list of classes """ if not _valid_args(client_interceptors): raise ValueError('client_intercep...
java
protected synchronized void fireTrackPositionChangeEvent(long newTime) { TrackPositionChangeEvent tpce = new TrackPositionChangeEvent(this, newTime); for (TrackPositionChangeListener tpcl : trackListeners) { tpcl.trackPositionChanged(tpce); } }
python
def post_build(self, container_builder, container): """ This method make sure the flask configuration is fine, and check the if ioc.extra.jinja2 service is available. If so, the flask instance will use this service, by keeping the flask template loader and the one registered a...
java
@SuppressWarnings("unchecked") private Constructor<BDBRepository> getRepositoryConstructor() throws ClassCastException, ClassNotFoundException, NoSuchMethodException { String packageName; { String thisClassName = getClass().getName(); packageName = thisClassName.s...
python
def get_asset(self, asset_hash, id=None, endpoint=None): """ Get an asset by its hash Args: asset_hash: (str) asset to lookup, example would be 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b' id: (int, optional) id to use for response tracking ...
java
@VisibleForTesting CompletableFuture<List<Long>> getBucketOffsets(DirectSegmentAccess segment, TableBucket bucket, TimeoutTimer timer) { val result = new ArrayList<Long>(); AtomicLong offset = new AtomicLong(bucket.getSegmentOffset()); return Futures.loop( () -> offset.get() ...
java
public Stat stat(final Txn<T> txn) { if (SHOULD_CHECK) { requireNonNull(txn); txn.checkReady(); } final MDB_stat stat = new MDB_stat(RUNTIME); checkRc(LIB.mdb_stat(txn.pointer(), ptr, stat)); return new Stat( stat.f0_ms_psize.intValue(), stat.f1_ms_depth.intValue(), ...
java
private void setCalendarToLastRelativeDay(Calendar calendar) { calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); int requiredDayOfWeek = getDayOfWeek().getValue(); int dayOfWeekOffset = 0; i...
python
def preprocess(content, options): # type: (Text, Optional[optparse.Values]) -> ReqFileLines """Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file :param options: cli options """ lines_enum = enumerate(content.splitlines(), start=1) # ...
java
public Observable<Void> deleteAsync(String jobScheduleId) { return deleteWithServiceResponseAsync(jobScheduleId).map(new Func1<ServiceResponseWithHeaders<Void, JobScheduleDeleteHeaders>, Void>() { @Override public Void call(ServiceResponseWithHeaders<Void, JobScheduleDeleteHeaders> respo...
python
def expand_all(self): """ Expand all positions; works only if the underlying tree allows it. """ if implementsCollapseAPI(self._tree): self._tree.expand_all() self._walker.clear_cache() self.refresh()
python
def _timestamp_query_param_from_json(value, field): """Coerce 'value' to a datetime, if set or not nullable. Args: value (str): The timestamp. field (.SchemaField): The field corresponding to the value. Returns: Optional[datetime.datetime]: The parsed datetime object from `...
python
def compute_positions(cls, screen_width, line): """Compute the relative position of the fields on a given line. Args: screen_width (int): the width of the screen line (mpdlcd.display_fields.Field list): the list of fields on the line Returns: ...
python
def model_file_fields(self, model): """ Generator yielding all instances of FileField and its subclasses of a model. """ for field in model._meta.fields: if isinstance(field, models.FileField): yield field
java
public String getContent() throws ConnectionException { logger.debug("Enter Response::getContent"); if (content != null) { logger.debug("content already available "); return content; } BufferedReader rd = new BufferedReader(new InputStreamReader(stream)); StringB...
python
def is_rate_limited(self, namespace: str) -> bool: """ Checks if a namespace is already rate limited or not without making any additional attempts :param namespace: Rate limiting namespace :type namespace: str :return: Returns true if attempt can go ahead under current rate...
java
public void printScreen(PrintWriter out, ResourceBundle reg) throws DBException { String strParamHelp = this.getProperty(DBParams.HELP); // Display record if (strParamHelp != null) return; // Don't do this for help screens this.printHtmlStartForm(out); in...
python
def helices(self): """Generates new `Assembly` containing just α-helices. Notes ----- Metadata is not currently preserved from the parent object. Returns ------- hel_assembly : ampal.Protein `Assembly` containing only the α-helices of the original `A...
python
def transform(self, X, y, sample_weight=None): ''' Transforms the time series data with run length encoding of the target variable Note this transformation changes the number of samples in the data If sample_weight is provided, it is transformed to align to the new target encoding ...
java
public Workflow getWorkflowById(String workflowId, boolean includeTasks) { Workflow workflow = executionDAO.getWorkflow(workflowId, includeTasks); if (workflow == null) { LOGGER.debug("Workflow {} not found in executionDAO, checking indexDAO", workflowId); String json = indexDAO....
python
def _write_inventory(self): """ Writes the provisioner's inventory file to disk and returns None. :return: None """ self._verify_inventory() util.write_file(self.inventory_file, util.safe_dump(self.inventory))
java
@Override public List<CommerceTierPriceEntry> findByCommercePriceEntryId( long commercePriceEntryId, int start, int end, OrderByComparator<CommerceTierPriceEntry> orderByComparator) { return findByCommercePriceEntryId(commercePriceEntryId, start, end, orderByComparator, true); }
python
def setdocument(self, doc): """Associate a document with this element. Arguments: doc (:class:`Document`): A document Each element must be associated with a FoLiA document. """ assert isinstance(doc, Document) if not self.doc: self.doc = doc ...
python
def subnode(self, node): """Make `node` receiver's child.""" self.children.append(node) node.parent = self node.adjust_interleave(node.interleave)