language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public OutputStream asOutputStream() { if ( tmp != null ) throw new RuntimeException("can create Input/OutputStream only once"); tmp = new byte[1]; return new OutputStream() { @Override public void write(int b) throws IOException { tmp[0] = (b...
java
public IfcPlateTypeEnum createIfcPlateTypeEnumFromString(EDataType eDataType, String initialValue) { IfcPlateTypeEnum result = IfcPlateTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName...
java
private static void addDir(File dirObj, ZipOutputStream out) throws IOException { File[] dirList = dirObj.listFiles(); byte[] tmpBuf = new byte[1024]; for (int i = 0; i < dirList.length; i++) { if (dirList[i].isDirectory()) { addDir(dirList[i], out...
python
def maximum_hline_bundle(self, y0, x0, x1): """Compute a maximum set of horizontal lines in the unit cells ``(x,y0)`` for :math:`x0 \leq x \leq x1`. INPUTS: y0,x0,x1: int OUTPUT: list of lists of qubits """ x_range = range(x0, x1 + 1) if x0 < x1 ...
java
public void localBegin() { if (this.isInLocalTransaction) { throw new TransactionInProgressException("Connection is already in transaction"); } Connection connection = null; try { connection = this.getConnection(); } ...
python
def merge_duplicates(model_name, keep_descriptors=False): """ Identifies repeated experimental values and returns mean values for those data along with their standard deviation. Only aggregates experimental values that have been acquired at the same temperature and pressure. Parameters --------...
java
public SearchPlaylistsRequest.Builder searchPlaylists(String q) { return new SearchPlaylistsRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) .q(q); }
java
private synchronized void onDropPackage(byte[] data) throws IOException { DataInput drop = new DataInput(data); long messageId = drop.readLong(); int errorCode = drop.readByte(); int messageLen = drop.readInt(); String message = new String(drop.readBytes(messageLen), "UTF-8"); ...
java
protected String getFieldKey(Field field, Class<? extends ActionBean> actionBeanClass) { // Use key attribute if it is defined. String sessionKey = ((Session)field.getAnnotation(Session.class)).key(); if (sessionKey != null && !"".equals(sessionKey)) { return sessionKey; ...
python
def wait(obj, timeout=None): """ Wait until *obj* gets notified with #notify() or #notify_all(). If a timeout is specified, the function can return without the object being notified if the time runs out. Note that you can only use this function on #synchronized() objects. # Arguments obj (Synchronizable...
python
def get_exporter_thread(metric_producer, exporter, interval=None): """Get a running task that periodically exports metrics. Get a `PeriodicTask` that periodically calls: exporter.export_metrics(metric_producer.get_metrics()) :type metric_producer: :class:`opencensus.metrics.export.metric_...
java
public SecretBundle updateSecret(UpdateSecretRequest updateSecretRequest) { return updateSecret(updateSecretRequest.vaultBaseUrl(), updateSecretRequest.secretName(), updateSecretRequest.secretVersion(), updateSecretRequest.contentType(), updateSecretRequest.secretAttributes(), up...
python
def check_independence(self, event1, event2, event3=None, condition_random_variable=False): """ Check if the Joint Probability Distribution satisfies the given independence condition. Parameters ---------- event1: list random variable whose independence is to be chec...
java
public void initialize() throws SQLException { synchronized (lock) { source = createConnectionPool(); try { source.initializeFrom(this); } catch (Exception e) { throw new PSQLException(GT.tr("Failed to setup DataSource."), PSQLState.UNEXPECTED_ERROR, e); } ...
java
@Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { Arrays.checkOffsetAndCount(buffer.length, byteOffset, byteCount); if (byteCount == 0) { return 0; } checkReadPrimitiveTypes(); return primitiveData.read(buffer, byteOffset...
python
def add_label_cycle(self, label, cycle): """Add new cycle to the plotter with label `label`.""" self.labels.append(label) self.cycles.append(cycle)
python
def _must_not_custom_query(issn): """ Este metodo constroi a lista de filtros por título de periódico que será aplicada na pesquisa boleana como restrição "must_not". A lista de filtros é coletada do template de pesquisa customizada do periódico, quanto este templ...
python
def newDevice(deviceJson, lupusec): """Create new device object for the given type.""" type_tag = deviceJson.get('type') if not type_tag: _LOGGER.info('Device has no type') if type_tag in CONST.TYPE_OPENING: return LupusecBinarySensor(deviceJson, lupusec) elif type_tag in CONST.TYP...
python
def _find_by_name(tree_data, name, is_dir, start_at): """return data entry matching the given name and tree mode or None. Before the item is returned, the respective data item is set None in the tree_data list to mark it done""" try: item = tree_data[start_at] if item and item[2] == ...
python
def network_interface_delete(name, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 Delete a network interface. :param name: The name of the network interface to delete. :param resource_group: The resource group name assigned to the network interface. CLI Example: .. co...
java
public void comment(char[] ch, int start, int length) throws SAXException { if (lexicalHandler != null) { lexicalHandler.comment(ch, start, length); } }
python
def logical_enclosures(self): """ Gets the LogicalEnclosures API client. Returns: LogicalEnclosures: """ if not self.__logical_enclosures: self.__logical_enclosures = LogicalEnclosures(self.__connection) return self.__logical_enclosures
python
def add_vq(self, parser): ''' Add verbose & quiet options ''' group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true")
python
def fetch(self, vault_client): """Updates the context based on the contents of the Vault server. Note that some resources can not be read after they have been written to and it is up to those classes to handle that case properly.""" backends = [(self.mounts, SecretBackend), ...
java
private void resolveRemainingToCurrent() { for (int i = 0; i < this.size; i++) { if (sourceRevisions.get(i) == null) { sourceRevisions.set(i, currentRevision); } } }
java
public static MenuItem getMenuItem(@NonNull Toolbar toolbar, @IdRes int menuId) { View v; int childCount; View innerView; MenuItem menuItem; for (int i = 0; i < toolbar.getChildCount(); i++) { v = toolbar.getChildAt(i); if (v instanceof ActionMenuView) { ...
java
private void initView(){ LinearLayout mProgressContainer = (LinearLayout) mLayout.findViewById(R.id.progress_container); int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, mLayout.getResources().getDisplayMetrics()); mLayout.setPadding(padding, padding, padding, padd...
python
def add_remote(name, location): ''' Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. CLI Example: .. code-block:: bash ...
python
def run_experiment(self): """ Run the job specified in experiment_script """ data=self.data options=self.options result=self.result command = open(self.options.experiment_script).read() result["experiment_script"]=command t0=time.time() ex...
python
def calculateHiddenLayerActivation(self, features): """ Calculate activation level of the hidden layer :param features feature matrix with dimension (numSamples, numInputs) :return: activation level (numSamples, numHiddenNeurons) """ if self.activationFunction is "sig": H = sigmoidActFunc(...
python
def get_auth_params_from_request(request): """Extracts properties needed by novaclient call from the request object. These will be used to memoize the calls to novaclient. """ return ( request.user.username, request.user.token.id, request.user.tenant_id, request.user.tok...
python
def stop(self, terminate=False): """ Stops the TCP server. :return: Method success. :rtype: bool """ if not self.__online: raise foundations.exceptions.ServerOperationError( "{0} | '{1}' TCP Server is not online!".format(self.__class__.__name...
java
@Override public DescribePipelinesResult describePipelines(DescribePipelinesRequest request) { request = beforeClientExecution(request); return executeDescribePipelines(request); }
java
public ListUpdatesResult withUpdateIds(String... updateIds) { if (this.updateIds == null) { setUpdateIds(new java.util.ArrayList<String>(updateIds.length)); } for (String ele : updateIds) { this.updateIds.add(ele); } return this; }
python
def __ProcessResponse(self, response): """Process response (by updating self and writing to self.stream).""" if response.status_code not in self._ACCEPTABLE_STATUSES: # We distinguish errors that mean we made a mistake in setting # up the transfer versus something we should attem...
python
def searchRecords(self, search): """ Creates a search for the inputed records by joining the search terms and query from the inputed search string by using the Orb.Query.fromSearch method. :param search | <str> refined | <orb.Query> || N...
java
public void shutdown(long quietPeriod, long timeout, TimeUnit timeUnit) { try { shutdownAsync(quietPeriod, timeout, timeUnit).get(); } catch (RuntimeException e) { throw e; } catch (ExecutionException e) { if (e.getCause() instanceof RedisCommandExecutionExc...
python
def update(self, event_or_list): """Update the button with the events.""" for e in super().update(event_or_list): if e.type == MOUSEBUTTONDOWN: if e.pos in self: self.click() else: self.release(force_no_call=True) ...
java
public static List<GeneName> getGeneNames(InputStream inStream) throws IOException{ ArrayList<GeneName> geneNames = new ArrayList<GeneName>(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); // skip reading first line (it is the legend) String line = reader.readLine(); while ((...
java
public Object getValue(final JavaType type, final ResultSet rs, final int columnIndex) throws SQLException { Class<?> rawType = type.getRawType(); for (PropertyMapper<?> propertyMapper : this.mappers) { if (propertyMapper.canAccept(rawType) && propertyMapper.canAcceptTest(type, rs, columnIndex, this)) { retu...
python
def log_prov_graph(self): """ Log provenance graph so far """ glogger.debug("Spec generation provenance graph:") glogger.debug(self.prov_g.serialize(format='turtle'))
java
public static <S, I, O> AbstractSULOmegaOracle<S, I, O, ?> newOracle(ObservableSUL<S, I, O> sul) { return newOracle(sul, !sul.canFork()); }
java
public <T> ESDatas<T> searchAll(String index, int fetchSize ,Class<T> type) throws ElasticSearchException{ return searchAll(index, fetchSize ,(ScrollHandler<T>) null,type); }
java
public static <T, R> Supplier<R> andThen(Supplier<T> supplier, Function<T, R> resultHandler, Function<Exception, R> exceptionHandler){ return () -> { try{ T result = supplier.get(); return resultHandler.apply(result); }catch (Exception exception){ ...
java
public String render(String templateName, EmailModel emailModel, Map<String, Object> model, Locale locale) { if (logger.isDebugEnabled()) { logger.debug("Rendering template [{}] for recipient [{}]", templateName, emailModel.getTo()); } final IEngineConfiguration engineConfiguration = templateEngineFactory.ge...
python
def execute_message_call( laser_evm, callee_address, caller_address, origin_address, code, data, gas_limit, gas_price, value, track_gas=False, ) -> Union[None, List[GlobalState]]: """Execute a message call transaction from all open states. :param laser_evm: :param ca...
java
public DataSink<T> writeAsCsv(String filePath, String rowDelimiter, String fieldDelimiter) { return internalWriteAsCsv(new Path(filePath), rowDelimiter, fieldDelimiter, null); }
python
def cli(self, prt=sys.stdout): """Command-line interface to print specified GO Terms from the DAG source .""" kws = self.objdoc.get_docargs(prt=None) if os.path.exists(kws['i']): obj = NCBIgeneFileReader(kws['i']) nts = obj.get_nts() if nts: ge...
java
public void pullImage(DockerImagePullStrategy pullStrategy, String imageName) throws InterruptedException { LOG.info("Pulling image {} with {} strategy...", imageName, pullStrategy); final List<Image> images = getDockerCli().listImagesCmd().withShowAll(true).exec(); NameParser.ReposTag repostag...
python
def _get_tgt_length(self, var): """Get the total length of the whole reference sequence """ if var.type == "g" or var.type == "m": return float("inf") else: # Get genomic sequence access number for this transcript identity_info = self.hdp.get_tx_identi...
python
def get_op_or_tensor_by_name(name): """ Get either tf.Operation of tf.Tensor from names. Args: name (list[str] or str): names of operations or tensors. Raises: KeyError, if the name doesn't exist """ G = tfv1.get_default_graph() def f(n): if len(n) >= 3 and n[-2] =...
python
def short(cls, path): """ Example: short("examined /Users/joe/foo") => "examined ~/foo" Args: path: Path to represent in its short form Returns: (str): Short form, using '~' if applicable """ if not path: return path ...
java
public static StandaloneLeaderRetrievalService createLeaderRetrievalService( Configuration configuration, boolean resolveInitialHostName, String jobManagerName) throws ConfigurationException, UnknownHostException { Tuple2<String, Integer> hostnamePort = HighAvailabilityServicesUtils.getJobManagerAddress(co...
java
@Override public MessageBriefInfo[] getStates(String corpNum, String[] receiptNumList) throws PopbillException { return getStates(corpNum, receiptNumList, null); }
java
private void printInfoContexts(StringBuilder buf, String uri, boolean reduceDisplay, boolean allowCmd, long host, Node.VHostMapping vhost, Node node) { if (!reduceDisplay) buf.append("<h3>Contexts:</h3>"); buf.append("<pre>"); for (Context context : node.getContexts()) { ...
java
public void setModified(Object newModified) { Object oldModified = modified; modified = newModified; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.SCENARIO__MODIFIED, oldModified, modified)); }
python
def from_events(self, instance, ev_args, ctx): """ Like :meth:`.Child.from_events`, but instead of replacing the attribute value, the new object is appended to the list. """ obj = yield from self._process(instance, ev_args, ctx) self.__get__(instance, type(instance)).app...
java
public synchronized void putXid(Xid xid) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "putXid", xid); putInt(xid.getFormatId()); putInt(xid.getGlobalTransactionId().length); put(xid.getGlobalTransactionId()); putInt(xid.getBranchQualifier().length)...
python
def _getOLRootNumber(self): """_getOLRootNumber(self) -> PyObject *""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document__getOLRootNumber(self)
python
def expected_diag_regression_log_prob(A, sigmasq, stats): """ Expected log likelihood of p(y | x) where y_{n,d} ~ N(a_d^\trans x_n, sigma_d^2) and expectation is wrt q(y,x). We only need expected sufficient statistics E[yy.T], E[yx.T], E[xx.T], and n, where n is the number of observations...
python
def _remove(self, client_kwargs): """ Remove an object. args: client_kwargs (dict): Client arguments. """ with _handle_oss_error(): bucket = self._get_bucket(client_kwargs) # Object if 'key' in client_kwargs: retur...
python
def mute(self): """get/set the current mute state""" response = self.rendering_control.GetMute(InstanceID=1, Channel=1) return response.CurrentMute == 1
java
@InterfaceAudience.Public public Object getProperty(String key) { if (getCurrentRevision() != null && getCurrentRevision().getProperties().containsKey(key)) { return getCurrentRevision().getProperties().get(key); } return null; }
python
def deregister(self, key): """ Deregisters an existing key. `key` String key to deregister. Returns boolean. """ if not key in self._actions: return False del self._actions[key] if key in self._cache: del se...
python
def get_named_arg(name, default_val=None, reqd=False): """ Extract the value after a command-line flag such as '-f' and return it. If the command-line flag is missing, return default_val. If reqd == True and the command-line flag is missing, throw an error. Parameters ---------- name : str ...
java
public static RSAKeyString keyGen(int keySize) { try { RSAKey keys = RSA.keyGen(keySize); return new RSAKeyString( Base64Util.encode2String(keys.getPublicKey().getEncoded()), Base64Util.encode2String(keys.getPrivateKey().getEncoded()) )...
python
def QA_fetch_get_future_transaction_realtime(code, ip=None, port=None): '期货历史成交分笔' ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API() global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_lis...
java
public static HierarchicalProperty lockDiscovery(String token, String lockOwner, String timeOut) { HierarchicalProperty lockDiscovery = new HierarchicalProperty(new QName("DAV:", "lockdiscovery")); HierarchicalProperty activeLock = lockDiscovery.addChild(new HierarchicalProperty(new QName(...
java
public boolean unlock(KeyColumn kc, T requestor) { if (!locks.containsKey(kc)) { log.info("Local unlock failed: no locks found for {}", kc); return false; } AuditRecord<T> unlocker = new AuditRecord<>(requestor, null); AuditRecord<T> holder = locks.get(kc); ...
java
public void deselect(Item item, int position, @Nullable Iterator<Integer> entries) { item.withSetSelected(false); if (entries != null) { entries.remove(); } if (position >= 0) { mFastAdapter.notifyItemChanged(position); } if (mSelectionListener !=...
python
def remove_child_bin(self, bin_id, child_id): """Removes a child from a bin. arg: bin_id (osid.id.Id): the ``Id`` of a bin arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``bin_id`` not a parent of ``child_id`` raise: NullArgument - ``bin_id`` o...
python
def clear(self, domain=None, path=None, name=None): """Clear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified ...
python
def _pop(self): ''' Actual pop ''' if not self.canPop(): raise IndexError('pop from an empty or blocked queue') priority = self.prioritySet[-1] ret = self.queues[priority]._pop() self.outputStat = self.outputStat + 1 self.totalSize = self.total...
python
def find_link(self, *args, **kwargs): """Find and return a link, as a bs4.element.Tag object. The search can be refined by specifying any argument that is accepted by :func:`links`. If several links match, return the first one found. If no link is found, raise :class:`LinkNotFoundError...
java
public JSONStringer key(String name) throws JSONException { if (name == null) { throw new JSONException("Names must be non-null"); } beforeKey(); string(name); return this; }
python
def get_essential_properties(self): """Gets essential scheduling properties as required by ironic :returns: a dictionary of server properties like memory size, disk size, number of cpus, cpu arch, port numbers and mac addresses. :raises:IloError if iLO return...
python
def convert_language_code(django_lang): """ Converts Django language codes "ll-cc" into ISO codes "ll_CC" or "ll" :param django_lang: Django language code as ll-cc :type django_lang: str :return: ISO language code as ll_CC :rtype: str """ lang_and_country = django_lang.split('-') tr...
python
def handle(client_message, handle_event_entry=None, to_object=None): """ Event handler """ message_type = client_message.get_message_type() if message_type == EVENT_ENTRY and handle_event_entry is not None: key = None if not client_message.read_bool(): key = client_message.read_d...
java
public String retrieveReferenceList() { try { references = gpUtil.getReferences(spaceKey, getPage().getTitle()); if(isEditMode) { repositories = gpUtil.getRepositories(spaceKey); if(repositories.isEmpty()) throw...
python
def tensor_info_proto_maps_match(map_a, map_b): """Whether two signature inputs/outputs match in dtype, shape and sparsity. Args: map_a: A proto map<string,TensorInfo>. map_b: A proto map<string,TensorInfo>. Returns: A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and sp...
java
public static void setAttribute(List<Attribute> attrs, String name, String v) { for (Attribute attr : attrs) { if (name.equals(attr.getAttributeName())) { if (v!=null) attr.setAttributeValue(v); else attrs.remove(attr); // TODO this will throw a concurrent modificati...
java
void add(final File file) { if (file.isFile()) { if (this.fileNames.contains(file.getName())) { LOG.log(Level.FINEST, "A file with this name has already been added: {0}", file.getName()); } else { this.fileNames.add(file.getName()); this.theFiles.add(file); } } else { ...
python
def db_en020(self, value=None): """ Corresponds to IDD Field `db_en020` mean coincident dry-bulb temperature to Enthalpy corresponding to 2.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `db_en020` Unit: C ...
python
def getTauLeibniz(n): """Returns a list containing first n digits of Pi """ myTau = tauGenLeibniz() result = [] if n > 0: result += [next(myTau) for i in range(n)] myTau.close() return result
java
protected <Type extends JvmType> Type findDeclaredType(String clazzName, ITypeReferenceOwner owner) { @SuppressWarnings("unchecked") Type result = (Type) services.getTypeReferences().findDeclaredType(clazzName, owner.getContextResourceSet()); return result; }
java
@Override public void setClientInformationArray(String[] clientInfoArray, WSRdbManagedConnectionImpl mc, boolean explicitCall) throws SQLException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "setClientInfor...
java
@Override public final void handle(final Map<String, Object> pRqVs, final IRequestData pRqDt, final int pDang, final String pMsg) throws Exception { String msg = "Spam request from host/addr/port/user/danger: " + pRqDt .getRemoteHost() + "/" + pRqDt.getRemoteAddr() + "/" + pRqDt .getRemot...
java
public void replaceShortMessage(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) thro...
python
def _warning_for_deprecated_user_based_rules(rules): """Warning user based policy enforcement used in the rule but the rule doesn't support it. """ for rule in rules: # We will skip the warning for the resources which support user based # policy enforcement. if [resource for reso...
java
private static String formatHumanMedium(final PointLocation pointLocation) { final Latitude latitude = pointLocation.getLatitude(); final Longitude longitude = pointLocation.getLongitude(); String string = formatLatitudeHumanMedium(latitude) + " " + formatLongitudeHumanMedium(longitude...
java
public IntBinaryTree createExample() { // START SNIPPET: sampleTree IntBinaryTree tree = _Node(42, _Node(12, _EmptyTree(), _EmptyTree()), _Node(103, _EmptyTree(), _Node(110, _EmptyTree(), _EmptyTree()))); // END SNIPPET: sampleTree return tree; }
java
public static DocumentBuilder buildSecureDocumentBuilder() throws ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/f...
java
@Override public PutSubscriptionFilterResult putSubscriptionFilter(PutSubscriptionFilterRequest request) { request = beforeClientExecution(request); return executePutSubscriptionFilter(request); }
python
def union(self, *iterables): """ Return a new SortedSet with elements from the set and all *iterables*. """ return self.__class__(chain(iter(self), *iterables), key=self._key)
python
async def fetch(self, limit: int = None) -> Sequence[StorageRecord]: """ Fetch next batch of search results. Raise BadSearch if search is closed, WalletState if wallet is closed. :param limit: maximum number of records to return (default value Wallet.DEFAULT_CHUNK) :return: nex...
java
private boolean checkContains(String fieldName, String... propNames) { for (String propName : propNames) { if (fieldName.contains("/" + propName + "/")) { return true; } } return false; }
python
def list_namespaced_replica_set(self, namespace, **kwargs): """ list or watch objects of kind ReplicaSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_replica_set(namespac...
java
static Map<Long, Long> fenceOut(List<LedgerMetadata> ledgers, BookKeeper bookKeeper, BookKeeperConfig config, String traceObjectId) throws DurableDataLogException { // Fence out the ledgers, in descending order. During the process, we need to determine whether the ledgers we // fenced out actually have ...
java
@SuppressWarnings("checkstyle:all") protected StringConcatenationClient generateFieldsAndMethods(boolean forInterface, boolean forAppender) { TypeReference scriptInterface = getCodeElementExtractor().getLanguageScriptInterface(); return new StringConcatenationClient() { @Override protected void appendTo(Targ...
python
def to_unicode(value): """Converts bytes, unicode, and C char arrays to unicode strings. Bytes and C char arrays are decoded from UTF-8. """ if isinstance(value, ffi.CData): return ffi.string(value).decode('utf-8') elif isinstance(value, binary_type): return value.decode('utf-8') ...