language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def ELBND(w, e, function="max"): """ This function estimates Error and Learning Based Novelty Detection measure from given data. **Args:** * `w` : history of adaptive parameters of an adaptive model (2d array), every row represents parameters in given time index. * `e` : error of adapti...
java
public Observable<Void> beginPauseAsync(String resourceGroupName, String serverName, String databaseName) { return beginPauseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Voi...
python
def open(self): """Create a connection to the AWS API server. This can be reused for sending multiple emails. """ if self.connection: return False try: self.connection = SESConnection( aws_access_key_id=self._access_key_id, ...
python
def one(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[]): """ Transform object by jq script, returning the first result. Raise ValueError unless results does not include exactly one element. """ return compile(script, vars, library_paths).one(_get_value(value, url, ope...
java
@Override public Set<SingularAttribute<X, ?>> getDeclaredSingularAttributes() { Set<SingularAttribute<X, ?>> declaredAttribSet = null; if (declaredSingluarAttribs != null) { declaredAttribSet = new HashSet<SingularAttribute<X, ?>>(); declaredAttribSet.addAll(decla...
python
def _get_group_dataframes(self): """ Get group dataframes Returns ------- out : tuple or generator Group dataframes """ if isinstance(self.data, GroupedDataFrame): grouper = self.data.groupby() # groupby on categorical columns ...
java
public String dialogTitle() { StringBuffer html = new StringBuffer(512); String toolPath = getCurrentToolPath(); String parentPath = getParentPath(); String rootKey = getToolManager().getCurrentRoot(this).getKey(); String upLevelLink = computeUpLevelLink(); html.append(...
python
async def scalar(self, query, as_tuple=False): """Get single value from ``select()`` query, i.e. for aggregation. :return: result is the same as after sync ``query.scalar()`` call """ query = self._swap_database(query) return (await scalar(query, as_tuple=as_tuple))
java
@Override public ByteArrayList fromStream(final InputStream is) throws IOException { final int length = Util.readVByte(is); buffer.size(length); final int actual = is.read(buffer.elements(), 0, length); if (actual != length) throw new IOException("Asked for " + length + " but got " + actual); return buffer; ...
python
def create(self, user: str, *, pwd: str, sgrp: str, comment: str=None) -> None: """Create new user.""" data = { 'action': 'add', 'user': user, 'pwd': pwd, 'grp': 'users', 'sgrp': sgrp } if comment: da...
java
protected KeyRecord getKeyRecord (int keyCode) { KeyRecord krec = _keys.get(keyCode); if (krec == null) { krec = new KeyRecord(); _keys.put(keyCode, krec); } return krec; }
java
private void doUndeployModule(final Message<JsonObject> message) { final String deploymentID = message.body().getString("id"); if (deploymentID == null) { message.reply(new JsonObject().putString("status", "error").putString("message", "No deployment ID specified.")); } else { removeDeployment(d...
java
public static Date fromISODateTime(final String val, final TimeZone tz) throws BadDateException { try { synchronized (isoDateTimeTZFormat) { isoDateTimeTZFormat.setTimeZone(tz); return isoDateTimeTZFormat.parse(val); } } catch (Throwable t) { ...
java
private TranLogConfiguration createFileTranLogConfiguration(String recoveredServerIdentity, FailureScope fs, String logDir, int ...
java
private void organizeContent() { TableRowBox anonrow = null; for (Iterator<Box> it = nested.iterator(); it.hasNext(); ) { Box box = it.next(); if (box instanceof ElementBox && ((ElementBox) box).getDisplay() == ElementBox.DISPLAY_TABLE_ROW) { ...
java
public int count(String sql, Object[] params) { int rowCount = 0; try{ Map<String, Object> resultMap = null; if (params == null || params.length == 0) { resultMap = getProxy().queryForMap(sql); } else { resultMap = getProxy().queryForMap(sql, params); } Iterator<Map.Entry<String, Object>...
python
def minibatch_by_words(items, size, tuples=True, count_words=len): """Create minibatches of a given number of words.""" if isinstance(size, int): size_ = itertools.repeat(size) else: size_ = size items = iter(items) while True: batch_size = next(size_) batch = [] ...
java
private void loadChildren() throws CmsException { for (CmsResource resource : new ArrayList<CmsResource>(m_knownResources)) { if (resource.isFolder()) { if (!m_mustLoadChildren.contains(resource)) { continue; } List<CmsResou...
java
public void setValueTypes(List<ValueType<?>> valueTypes) { Validate.noNullElements(valueTypes); this.sqlExecutor.setValueTypes(valueTypes); this.callExecutor.setValueTypes(valueTypes); }
python
def setSkyboxOverride(self, unTextureCount): """ Override the skybox used in the compositor (e.g. for during level loads when the app can't feed scene images fast enough) Order is Front, Back, Left, Right, Top, Bottom. If only a single texture is passed, it is assumed in lat-long format. ...
python
def element_at(index): """Create a transducer which obtains the item at the specified index.""" if index < 0: raise IndexError("element_at used with illegal index {}".format(index)) def element_at_transducer(reducer): return ElementAt(reducer, index) return element_at_transducer
java
public int doEndTag() throws JspException { // report errors that may have occurred when the required attributes are being set if (hasErrors()) return reportAndExit(EVAL_PAGE); // build the anchor into the results ByRef script = new ByRef(); WriteRenderAppender ...
python
def _find_attrNodeNS(E, namespaceURI, localName): '''Must grab the attribute Node to distinquish between an unspecified attribute(None) and one set to empty string(""). namespaceURI localName ''' attr = E.getAttributeNodeNS(namespaceURI, localName) if attr is None: return None try:...
python
def add_duration(self, key, value): """Add a duration for the specified key :param str key: The value name :param float value: The value .. versionadded:: 3.19.0 """ if key not in self.durations: self.durations[key] = [] self.durations[key].append(v...
python
def TriadicScheme(self, angle=120, mode='ryb'): '''Return two colors forming a triad or a split complementary with this one. Parameters: :angle: The angle between the hues of the created colors. The default value makes a triad. :mode: Select which color wheel to use for the ...
java
public static BorderStyle getBorderRight(final Cell cell) { ArgUtils.notNull(cell, "cell"); final Sheet sheet = cell.getSheet(); CellRangeAddress mergedRegion = getMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex()); final Cell target; if(mergedRegion == nul...
python
def summary(args): """ %prog summary bedfile Sum the total lengths of the intervals. """ p = OptionParser(summary.__doc__) p.add_option("--sizes", default=False, action="store_true", help="Write .sizes file") p.add_option("--all", default=False, action="store_true", ...
python
def define_noisy_readout(self, qubit, p00, p11): """ For this program define a classical bit flip readout error channel parametrized by ``p00`` and ``p11``. This models the effect of thermal noise that corrupts the readout signal **after** it has interrogated the qubit. :param i...
python
def split_by_list(self, train, valid): "Split the data between `train` and `valid`." return self._split(self.path, train, valid)
java
public final void loadInterproceduralDatabases() { loadPropertyDatabase(getFieldStoreTypeDatabase(), FieldStoreTypeDatabase.DEFAULT_FILENAME, "field store type database"); loadPropertyDatabase(getUnconditionalDerefParamDatabase(), UNCONDITIONAL_DEREF_DB_FILENAME, "unconditional param der...
java
public static HttpCarbonRequest setupCarbonRequest(HttpRequest httpRequest, Http2SourceHandler http2SourceHandler) { ChannelHandlerContext ctx = http2SourceHandler.getChannelHandlerContext(); HttpCarbonRequest sourceReqCMsg = new HttpCarbonRequest(httpRequest, new DefaultListener(ctx)); sourceRe...
java
@Override public EClass getFormatSerializerMap() { if (formatSerializerMapEClass == null) { formatSerializerMapEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(113); } return formatSerializerMapEClass; }
java
public static void tileImage (Graphics2D gfx, Mirage image, int x, int y, int width, int height) { int iwidth = image.getWidth(), iheight = image.getHeight(); int xnum = width / iwidth, xplus = width % iwidth; int ynum = height / iheight, yplus = height % iheight; Shape oclip = gfx.g...
python
def _shift_headings(self, content: str, shift: int) -> str: '''Shift Markdown headings in a string by a given value. The shift can be positive or negative. :param content: Markdown content :param shift: Heading shift :returns: Markdown content with headings shifted by ``shift``...
java
public static byte[] dgst(InputStream is, Digest digest) throws IOException { checkNotNull(is); int n = 0; byte[] buffer = new byte[BUFFER_SIZE]; while (n >= 0) { n = is.read(buffer); if (n > 0) { digest.update(buffer, 0, n); } ...
java
private Map<JSType, String> buildPropNames(Property prop) { UnionFind<JSType> pTypes = prop.getTypes(); String pname = prop.name; Map<JSType, String> names = new HashMap<>(); for (Set<JSType> set : pTypes.allEquivalenceClasses()) { checkState(!set.isEmpty()); JSType representative = pTypes.f...
java
public static final ParameterizedType parameterize(final Class<?> raw, final Type... typeArguments) { return parameterizeWithOwner(null, raw, typeArguments); }
python
def default(self) -> Optional[ScalarValue]: """Default value of the receiver, if any.""" if self.mandatory: return None if self._default is not None: return self._default return (None if self.type.default is None else ArrayValue([self.type.default]...
java
void runWithinPeriod(Runnable runnable, ExecuteStepMessage executeStepMessage, int timeout, TimeUnit unit) { if ( ! isRunningAStep.getAndSet(true)) { this.currentlyExecutingStep = executeStepMessage; Future<String> future = null; try { future = scheduledExecut...
java
private PathFilter getFileFilter() { final String extension = (this.expectedExtension.startsWith(".")) ? this.expectedExtension : "." + this.expectedExtension; return new PathFilter() { @Override public boolean accept(Path path) { return path.getName().endsWith(extension) &&...
java
public boolean parseLine(WsByteBuffer buff) throws Exception { final boolean bTrace = TraceComponent.isAnyTracingEnabled(); if (bTrace && tc.isDebugEnabled()) { Tr.debug(tc, "parseLine called for " + this); } //PI34161 - Record the start of the request at the time of parsing...
java
protected static Capabilities substituteMobilePlatform(Capabilities originalCapabilities, String newPlatform) { DesiredCapabilities dc = new DesiredCapabilities(originalCapabilities); dc.setCapability(PLATFORM_NAME, newPlatform); return dc; }
java
public Observable<Page<SharedAccessSignatureAuthorizationRuleInner>> listKeysNextAsync(final String nextPageLink) { return listKeysNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<SharedAccessSignatureAuthorizationRuleInner>>, Page<SharedAccessSignatureAuthorizationRule...
python
def create_mssql_pymssql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mssql_pymssql), **kwargs )
java
public static String getRendererOverride(final String classname) { if (StringUtils.isBlank(classname)) { throw new IllegalArgumentException("classname cannot be blank."); } return get().getString(RENDERER_OVERRIDE_PREFIX + classname); }
java
public void removePostSelectionChangedListener( ISelectionChangedListener listener) { if (fOutlineViewer != null) { fOutlineViewer.removePostSelectionChangedListener(listener); } else { fPostSelectionChangedListeners.remove(listener); } }
python
def _get_attribute_value_for_node(self, record): """ Gets the closest value for the current node's attribute matching the given record. """ # Abort if this node has not get split on an attribute. if self.attr_name is None: return # O...
java
public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoaderWithContext<K, V> batchLoadFunction) { return newMappedDataLoader(batchLoadFunction, null); }
python
def package_existent(name): """Search package. * :class:`bootstrap_py.exceptions.Conflict` exception occurs when user specified name has already existed. * :class:`bootstrap_py.exceptions.BackendFailure` exception occurs when PyPI service is down. :param str name: package name """ ...
java
protected void onFinishPublishJob(CmsPublishJobRunning publishJob) { try { cleanupEmptyWorkflowProjects(null); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } }
java
private List<HistogramScene> computeHistograms(FeatureToWordHistogram_F64 featuresToHistogram ) { List<String> scenes = getScenes(); List<HistogramScene> memory;// Processed results which will be passed into the k-NN algorithm memory = new ArrayList<>(); for( int sceneIndex = 0; sceneIndex < scenes.size(); s...
java
@Override public void registerFactories(ChannelFactoryProvider provider) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Register factory provider; " + provider.getClass().getName()); } synchronized (this.factories) { for (Entry<Stri...
python
def report_change(project, path, old_content): """Report that the contents of file at `path` was changed The new contents of file is retrieved by reading the file. """ resource = path_to_resource(project, path) if resource is None: return for observer in list(project.observers): ...
java
public Object get( String name ) throws EvalError { try { Object ret = globalNameSpace.get( name, this ); return Primitive.unwrap( ret ); } catch ( UtilEvalError e ) { throw e.toEvalError( SimpleNode.JAVACODE, new CallStack() ); } }
java
private static final void set(long10 out, int in) { out._0=in; out._1=0; out._2=0; out._3=0; out._4=0; out._5=0; out._6=0; out._7=0; out._8=0; out._9=0; }
python
def _seqfeature_to_coral(feature): '''Convert a Biopython SeqFeature to a coral.Feature. :param feature: Biopython SeqFeature :type feature: Bio.SeqFeature ''' # Some genomic sequences don't have a label attribute # TODO: handle genomic cases differently than others. Some features lack # a...
python
def start_request(self, headers, *, end_stream=False): """ Start a request by sending given headers on a new stream, and return the ID of the new stream. This may block until the underlying transport becomes writable, and the number of concurrent outbound requests (open outbound...
python
def charge_credit_card(credit_card_psp_object: Model, amount: Money, client_ref: str) -> Tuple[bool, Model]: """ :param credit_card_psp_object: an instance representing the credit card in the psp :param amount: the amount to charge :param client_ref: a reference that will appear on the customer's credit...
java
public boolean isRegisteredLanguage(String language) { String lang = getLanguageOrDefault(language); return getRegisteredLanguages().contains(lang); }
python
def ema_historical_return(prices, frequency=252, span=500): """ Calculate the exponentially-weighted mean of (daily) historical returns, giving higher weight to more recent data. :param prices: adjusted closing prices of the asset, each row is a date and each column is a ticker/id. ...
python
def context_click(self, on_element=None): """ Performs a context-click (right click) on an element. :Args: - on_element: The element to context-click. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) ...
python
def _get_buffered_response(self): """Returns a buffered response :return: Buffered response """ response = self._get_response() if response.request.method == 'DELETE' and response.status_code == 204: return [{'status': 'record deleted'}], 1 result = self._...
java
@Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { // check if a dummy for this type already exists in cache if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } ...
java
private String normalizeFilePath(final String path) { String normalizedPath = path.replace('\\', '/'); if (!normalizedPath.startsWith("/")) { normalizedPath = "/" + normalizedPath; } return normalizedPath; }
python
def handleLocalJob(self, jobNode): # type: (JobNode) -> Optional[int] """ To be called by issueBatchJobs. Returns the jobID if the jobNode has been submitted to the local queue, otherwise returns None """ if (not self.config.runCwlInternalJobsOnWorkers a...
python
def normalizePointType(value): """ Normalizes point type. * **value** must be an string. * **value** must be one of the following: +----------+ | move | +----------+ | line | +----------+ | offcurve | +----------+ | curve | +----------+ ...
python
def post(self): """Create a new config item""" self.reqparse.add_argument('namespacePrefix', type=str, required=True) self.reqparse.add_argument('description', type=str, required=True) self.reqparse.add_argument('key', type=str, required=True) self.reqparse.add_argument('value', ...
python
def __get_last_update_time(): '''Returns last FTP site update time''' now = datetime.datetime.utcnow() # Get the first Tuesday of the month first_tuesday = __get_first_tuesday(now) if first_tuesday < now: return first_tuesday else: first_of_month = datetime.datetime(now.year, n...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case TypesPackage.JVM_TYPE_PARAMETER__CONSTRAINTS: return constraints != null && !constraints.isEmpty(); case TypesPackage.JVM_TYPE_PARAMETER__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); cas...
python
def instantiate(self, **extra_args): """ Instantiate the model """ input_block = self.input_block.instantiate() backbone = self.backbone.instantiate(**extra_args) return QStochasticPolicyModel(input_block, backbone, extra_args['action_space'])
python
def _handleClassAttr(self): ''' _handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack. ''' if len(self.tag._classNames)...
python
def parse_signature(self, statement, element, module=None): """Parses the specified line as a new version of the signature for 'element'. :arg statement: the string that has the new signature. :arg element: the code element whose signature will be changed. """ #If the signature ...
java
public SftpFileAttributes get(String remote, OutputStream local, FileTransferProgress progress, long position) throws SftpStatusException, SshException, TransferCancelledException { String remotePath = resolveRemotePath(remote); SftpFileAttributes attrs = sftp.getAttributes(remotePath); if (position > ...
python
def _decode_fname(self): """Extracts the actual string from the available bytes.""" self.fname = self.fname[:self.fname.find('\0')] self.fname = self.fname.replace('\\', '/')
java
public Search name(@Nullable Predicate<String> nameMatches) { if (nameMatches != null) this.nameMatches = nameMatches; return this; }
java
public static <T extends NamedElement> ElementMatcher.Junction<T> nameEndsWithIgnoreCase(String suffix) { return new NameMatcher<T>(new StringMatcher(suffix, StringMatcher.Mode.ENDS_WITH_IGNORE_CASE)); }
java
@Override public int compareTo(Object obj) { int result = -1; if (obj instanceof AbstractPlugin) { AbstractPlugin test = (AbstractPlugin) obj; if (getId() < test.getId()) { result = -1; } else if (getId() > test.getId()) { ...
python
def read_csv(path, fieldnames=None, sniff=True, encoding='utf-8', *args, **kwargs): ''' Read CSV rows as table from a file. By default, csv.reader() will be used any output will be a list of lists. If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead. CSV sni...
java
public Contact sendContact(final ContactRequest contactRequest) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(CONTACTPATH, contactRequest, Contact.class); }
python
def has_bom(self, f): """Check for UTF8, UTF16, and UTF32 BOMs.""" content = f.read(4) encoding = None m = RE_UTF_BOM.match(content) if m is not None: if m.group(1): encoding = 'utf-8-sig' elif m.group(2): encoding = 'utf-3...
java
private void populateTasks(List<Flow> flows) throws IOException { if (flows == null || flows.size() == 0) { return; } // for simplicity, we assume that flows are ordered and consecutive JobKey startJob = null; // find the first job for (Flow f : flows) { List<JobDetails> jobs = f.ge...
java
private static JSONObject process_json_value(JSONObject object, String name, String value, String path, Boolean isSet) throws Exception { if (!path.equals("")) { String[] pathElements = path.split("\\."); String remainingPath = pathElements.length > 1 ? path.replace(pathElements[0] + "."...
java
private void markExterns(ImmutableList<CompilerInput> originalInputs) { for (CompilerInput input : originalInputs) { if (input.getHasExternsAnnotation()) { input.setIsExtern(); } } }
java
public void processUpdates(FacesContext context) { if (context == null) { throw new NullPointerException(); } if (!isRendered()) { return; } pushComponentToEL(context, this); preUpdate(context); iterate(context, PhaseId.UPDATE_MODEL_VALUE...
python
def relative_script(lines): "Return a script that'll work in a relocatable environment." activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, act...
java
private static int getMethodModifiers(ExecutableElement method) { int modifiers = ElementUtil.fromModifierSet(method.getModifiers()); if (method.isVarArgs()) { modifiers |= ElementUtil.ACC_VARARGS; } if (ElementUtil.isSynthetic(method)) { modifiers |= ElementUtil.ACC_SYNTHETIC; } ret...
python
def from_name(clz, name): """ Instantiates the object from a known name """ if isinstance(name, list) and "green" in name: name = "teal" assert name in COLOR_NAMES, 'Unknown color name' r, b, g = COLOR_NAMES[name] return clz(r, b, g)
java
public final void mREGEX_MATCH() throws RecognitionException { try { int _type = REGEX_MATCH; int _channel = DEFAULT_TOKEN_CHANNEL; // src/riemann/Query.g:9:13: ( '~=' ) // src/riemann/Query.g:9:15: '~=' { match("~="); } ...
java
public Map<String, Set<String>> getReverseMap() { Set<Map.Entry<String,Set<String>>> entries = map.entrySet(); Map<String, Set<String>> rMap = new HashMap<String, Set<String>>(entries.size()); for (Map.Entry<String,Set<String>> me : entries) { String k = me.getKey(); Set<String> transList =...
python
def _ _init__(self, driverName=None, debug=False): """ Constructs a new TTS engine instance. @param driverName: Name of the platform specific driver to use. If None, selects the default driver for the operating system. @type: str @param debug: Debugging output enable...
java
@Override public void write(DataOutput out) throws IOException { Text.writeString(out, getJobId()); out.writeDouble(getCpuUsageGHz()); out.writeDouble(getMemUsageGB()); }
java
public void destroy() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { MUCLightDestroyIQ mucLightDestroyIQ = new MUCLightDestroyIQ(room); IQ responseIq = connection.createStanzaCollectorAndSend(mucLightDestroyIQ).nextResultOrThrow(); boolean roomDestr...
python
def run_single_eval(nlp, loading_time, print_name, text_path, gold_ud, tmp_output_path, out_file, print_header, check_parse, print_freq_tasks): """" Run an evaluation of a model nlp on a certain specified treebank """ with text_path.open(mode='r', encoding='utf-8') as f: flat_text = ...
java
public static byte[] decode( String s, int options ) { byte[] bytes = s.getBytes( Charsets.UTF_8 ); // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if( byte...
python
def create(self, **kwargs): """ Creates a new post. When the `markdown` property is present, it will be automatically converted to `mobiledoc` on v1.+ of the server. :param kwargs: The properties of the post :return: The created `Post` object """ return ...
java
@Override public void busy(long time) { getRequestBusyProbe().start(); synchronized (this) { degrade(time); _lastBusyTime = time; _firstSuccessTime = 0; _currentFailCount++; _busyCountTotal++; _state = _state.toBusy(); } }
python
def get_ext(self, obj=None): """Return the file extension :param obj: the fileinfo with information. If None, this will use the stored object of JB_File :type obj: :class:`FileInfo` :returns: the file extension :rtype: str :raises: None """ if obj is None...
python
def diffplot(self, f, delay=1, lfilter=None, **kargs): """diffplot(f, delay=1, lfilter=None) Applies a function to couples (l[i],l[i+delay])""" return plt.plot([ f(i, j) for i in self.res[:-delay] for j in self.res[delay:] if not lfilter or (lfilter(i) and lfilter(j))], **kargs)
java
@Override public List<CommerceRegion> findByC_A(long commerceCountryId, boolean active, int start, int end) { return findByC_A(commerceCountryId, active, start, end, null); }
python
def sendData(self, data): """Write data to server""" # Not set up yet if self.client_log is None: self.client_log_buffer.append(data) else: self.client_log.write(data) self.transport.write(data)