language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void setCompanies(final JAASSystem _jaasSystem, final Set<Company> _companies) throws EFapsException { if (_jaasSystem == null) { throw new EFapsException(getClass(), "setRoles.nojaasSystem", getName()); } if (_companies == null) { ...
java
public static <U> Stream<U> takeWhile(final Stream<U> stream, final Predicate<? super U> predicate) { return StreamSupport.stream(new LimitWhileSpliterator<>(stream.spliterator(), predicate),stream.isParallel()); }
java
final public void write(char []buf, int offset, int length) { Writer out = this.out; if (out == null) return; try { out.write(buf, offset, length); } catch (IOException e) { log.log(Level.FINE, e.toString(), e); } }
python
def endswith(self, value): """ Sets the operator type to Query.Op.Endswith and sets \ the value to the inputted value. This method will only work on text \ based fields. :param value <str> :return <Query> :usage |>>>...
java
@Override public Object map(Object input) { List row = (List) input; String[] first = row.get(0).toString().split(delimiter); String[] second = row.get(1).toString().split(delimiter); String[] stdev = columns.length > 2 ? row.get(2).toString().split(delimiter) : null; double...
python
def get_b2aset(a2bset): """Given gene2gos, return go2genes. Given go2genes, return gene2gos.""" b2aset = {} for a_item, bset in a2bset.items(): for b_item in bset: if b_item in b2aset: b2aset[b_item].add(a_item) else: b2aset[b_item] = set([a_it...
python
def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, ...
java
public synchronized static void write(int fd, InputStream input) throws IOException { // ensure bytes are available if(input.available() <= 0){ throw new IOException("No available bytes in input stream to write to serial port."); } ByteArrayOutputStream buffer = new ByteArr...
java
private void addPossibleSignature(String name, Node node, NodeTraversal t) { if (node.isFunction()) { // The node we're looking at is a function, so we can add it directly addSignature(name, node, t.getSourceName()); } else { nonMethodProperties.add(name); } }
python
def _std(self): """Computes the current estimate of the standard deviation. Note that the standard deviation is not defined until at least two samples were seen. Returns: Tensor of current variance. """ variance = tf.cond( self._count > 1, lambda: self._var_sum / tf.cast(...
java
public static String encodeString(String s) { if (s != null && s.length() != 0) { try { final byte[] encode = Base64.encode(s.getBytes(DATA_ENCODING)); return new String(encode, BYTE_ENCODING); } catch (UnsupportedEncodingException e) { VdmDebugPlugin.log(e); } } return EMPTY; }
java
public final AntlrDatatypeRuleToken ruleOpEquality() throws RecognitionException { AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken(); Token kw=null; enterRule(); try { // InternalPureXbase.g:1326:2: ( (kw= '==' | kw= '!=' | kw= '===' | kw= '!==' ) ) ...
python
def check_mutate_fields( op, op_data ): """ Verify that all mutate fields are present. Return True if so. Raise an exception (AssertionError) if not. """ mutate_fields = op_get_mutate_fields( op ) assert mutate_fields is not None, "No mutate fields defined for %s" % op missing = [] ...
python
def pairwise_tukey(dv=None, between=None, data=None, alpha=.05, tail='two-sided', effsize='hedges'): '''Pairwise Tukey-HSD post-hoc test. Parameters ---------- dv : string Name of column containing the dependant variable. between: string Name of column containing ...
python
def get_axes_layout(self, figure_list): """ returns the axes objects the script needs to plot its data the default creates a single axes object on each figure This can/should be overwritten in a child script if more axes objects are needed Args: figure_list: a list of...
python
def start(label, at=None): """Begins the countdown""" t = at if at is not None else time.time() marker = Marker().start(t) labels[label] = marker.dumps()
java
private void applyExecute(ExecuteOperation operation) { Session session = context.getOrCreateSession(operation.session(), operation.node()); if (operation.operation() != null) { try { context.service().apply(new DefaultCommit<>( context.setIndex(operation.index()), operatio...
python
def set_observer(self, observer): """ Validates and sets the color's observer angle. .. note:: This only changes the observer angle value. It does no conversion of the color's coordinates. :param str observer: One of '2' or '10'. """ observer = str(observer)...
java
public static <T extends Schema> T newInstance(Class<T> clz) { try { return clz.newInstance(); } catch (Exception e) { throw H2O.fail("Failed to instantiate schema of class: " + clz.getCanonicalName(),e); } }
java
public static void fire(HasHandlers source, boolean valid) { ValidationChangedEvent eventInstance = new ValidationChangedEvent(valid); source.fireEvent(eventInstance); }
java
public void addItemForLogger(Logger logger) { Item item = m_container.addItem(logger); if (item != null) { item.getItemProperty(TableColumn.Channel).setValue(logger.getName()); Logger parent = logger.getParent(); item.getItemProperty(TableColumn.ParentChannel).setVal...
python
def assoc(self, key, value): """ Return a modified PrettyContext with ``key`` set to ``value`` """ return self._replace(user_ctx={ **self.user_ctx, key: value, })
java
public void deleteObject(DeleteObjectRequest request) { checkNotNull(request, "request should not be null."); assertStringNotNullOrEmpty(request.getKey(), "object key should not be null or empty"); this.invokeHttpClient(this.createRequest(request, HttpMethodName.DELETE), BosResponse.class); ...
java
private static Level logLevelFor(DescriptorVisibilityFilter f) { Long interval = SystemProperties.getLong( DescriptorVisibilityFilter.class.getName() + ".badFilterLogWarningIntervalMinutes", 60L); // the healthy path will never see this synchronized block synchron...
java
@Override public Restoration getBySnapshotId(String snapshotId) throws RestorationNotFoundException { List<Restoration> restorations = this.restoreRepo.findBySnapshotNameOrderByModifiedDesc(snapshotId); if (CollectionUtils.isEmpty(restorations)) { log.debug("Restoration returned ...
python
def transform(self, col): """Prepare the transformer to convert data and return the processed table. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ out = pd.DataFrame(index=col.index) out[self.col_name] = col.apply...
python
def info(zone, show_all=False): ''' Display the configuration from memory zone : string name of zone show_all : boolean also include calculated values like capped-cpu, cpu-shares, ... CLI Example: .. code-block:: bash salt '*' zonecfg.info tallgeese ''' ret = ...
java
protected synchronized void reset() { if (max == 0) { return; } for (int i = 0; i < timestamps.length; i++) { timestamps[i] = 0; } min = 0; max = 0; tested = 0; locked = false; }
java
@Override public EClass getIfcMechanicalFastener() { if (ifcMechanicalFastenerEClass == null) { ifcMechanicalFastenerEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(376); } return ifcMechanicalFastenerEClass; }
python
def template(template_name): """Return a jinja template ready for rendering. If needed, global variables are initialized. Parameters ---------- template_name: str, the name of the template as defined in the templates mapping Returns ------- The Jinja template ready for rendering """ ...
java
@NotNull public OptionalInt filter(@NotNull IntPredicate predicate) { if (!isPresent()) return this; return predicate.test(value) ? this : OptionalInt.empty(); }
java
public Set<String> setToString(final Set<?> target) { if (target == null) { return null; } final Set<String> result = new LinkedHashSet<String>(target.size() + 2); for (final Object element : target) { result.add(toString(element)); } return result...
python
def selection_notification(self, model, property, info): """If a single state is selected, open the corresponding tab""" if model is not self.current_state_machine_m or len(self.current_state_machine_m.ongoing_complex_actions) > 0: return state_machine_m = model assert isinst...
python
def led_rgb(self, color): """Set devices LED color.""" if (not isinstance(color, (list, tuple)) or not all(isinstance(item, int) for item in color)): raise SkybellException(ERROR.COLOR_VALUE_NOT_VALID, color) self._set_setting( { CONST.SET...
java
private static Set<Attr> collectAttributes(Element element, boolean includeCssClass) { Set<Attr> attributes = new HashSet<Attr>(); Attr cssClass = null; boolean foundDataCssClass = false; for (Attr attr : element.getAttrs()) { final AttrImpl attrImpl = new AttrImpl(attr); if (includeCssClass) { ...
java
public static void checkAllDone(Collection<Future> futures) throws Exception { for (Future f : futures) { if (f.isDone()) { f.get(); } } }
python
def open(self): """ Fixes RDF validation issues. Zotero incorrectly uses ``rdf:resource`` as a child element for Attribute; ``rdf:resource`` should instead be used as an attribute of ``link:link``. """ with open(self.path, 'r') as f: corrected = f.read().repl...
java
public void fixupVariables(java.util.Vector vars, int globalsSize) { m_predicateIndex = -1; AxesWalker walker = m_firstWalker; while (null != walker) { walker.fixupVariables(vars, globalsSize); walker = walker.getNextWalker(); } }
python
def do_string_set(self, element, decl, pseudo): """Implement string-set declaration.""" args = serialize(decl.value) step = self.state[self.state['current_step']] strval = '' strname = None for term in decl.value: if type(term) is ast.WhitespaceToken: ...
java
public static void index() throws EFapsException { final List<IndexDefinition> defs = IndexDefinition.get(); for (final IndexDefinition def : defs) { final QueryBuilder queryBldr = new QueryBuilder(def.getUUID()); final InstanceQuery query = queryBldr.getQuery(); ...
java
public void addVariant(CmsDocumentDependency dep) { // check if already exists for (CmsDocumentDependency lang : m_variants) { if (lang.getLocale().equals(dep.getLocale())) { return; } } dep.setType(DependencyType.variant); m_variants.add(...
java
public void setDispatchTime(TaskAttemptID taskid, long disTime){ dispatchTimeMap.put(taskid, disTime); this.lastDispatchTime = disTime; }
java
public CreateVolumeResponse createVolume(CreateVolumeRequest request) { checkNotNull(request, "request should not be null."); if (Strings.isNullOrEmpty(request.getClientToken())) { request.setClientToken(this.generateClientToken()); } if (null == request.getBilling()) { ...
python
def BP(candidate, references): """ calculate brevity penalty """ c = len(candidate) ref_lens = (len(reference) for reference in references) r = min(ref_lens, key=lambda ref_len: (abs(ref_len - c), ref_len)) if c > r: return 1 else: return math.exp(1 - r / c)
python
def cleanup_containers(self): """ stop all container created by conu :return: None """ for cont in self.list_containers(): if CONU_ARTIFACT_TAG in cont.name: try: logger.debug("removing container %s created by conu", cont) ...
python
def remove_seat(self, seat_id): """ Remove a seat from your team :param seat_id: Id of user """ url = self.TEAM_SEATS_ID_URL % seat_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
python
def get_list(self, list_name, options=None): """ Get detailed metadata information about a list. """ options = options or {} data = {'list': list_name} data.update(options) return self.api_get('list', data)
java
@ObjectiveCName("sendMessageWithPeer:withText:withMarkdownText:withMentions:autoDetect:") public void sendMessage(@NotNull Peer peer, @NotNull String text, @Nullable String markDownText, @Nullable ArrayList<Integer> mentions, boolean autoDetect) { modules.getMessagesModule().send...
java
public Subject newSubject(final NameID nameId, final NameID subjectConfNameId, final String recipient, final ZonedDateTime notOnOrAfter, final String inResponseTo, final ...
java
@Override public Parameter visitParameter(Context context, Parameter p) { return filter.filterParameter(p); }
python
def parse_data_to_internal(self, data=None): """Use numpy loadtxt """ if data is None: kwargs = self.kwargs data = np.loadtxt( open(self.location_dat, "rb"), **kwargs ) if self.filetype is "pickle": pickle.dump(data, open(se...
python
def snmp_server_enable_trap_trap_flag(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") enable = ET.SubElement(snmp_server, "enable") trap = ET.SubElement...
python
def ls(topics): """List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 - 2500 Return codes: 0 Normal 2 When insuffici...
python
def create_environment(self, **kwargs): """ Return a new Jinja environment. Derived classes may override method to pass additional parameters or to change the template loader type. """ return jinja2.Environment( loader=jinja2.FileSystemLoader(self.tem...
python
def bounds(ctx, tile): """Print Tile bounds.""" click.echo( '%s %s %s %s' % TilePyramid( ctx.obj['grid'], tile_size=ctx.obj['tile_size'], metatiling=ctx.obj['metatiling'] ).tile(*tile).bounds(pixelbuffer=ctx.obj['pixelbuffer']) )
python
def _notify_media_transport_available(self, path, transport): """ Called by the endpoint when a new media transport is available """ self.source = BTAudioSource(dev_path=path) self.state = self.source.State self.source.add_signal_receiver(self._property_change_eve...
python
def websocket_safe_read(self): """ Returns data if available, otherwise ''. Newlines indicate multiple messages """ data = [] while True: try: data.append(self.websocket.recv()) except (SSLError, SSLWantReadError) as err: ...
python
def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ...
java
public void write(FileColumn[] columns, List<String[]> lines) throws IOException { Object contents = getContents(columns, lines); if(stream != null && contents instanceof byte[]) { byte[] bytes = (byte[])contents; stream.write(bytes); } } /** * C...
python
def fast_sync_snapshot_decompress( snapshot_path, output_dir ): """ Given the path to a snapshot file, decompress it and write its contents to the given output directory Return {'status': True} on success Return {'error': ...} on failure """ if not tarfile.is_tarfile(snapshot_path): ...
java
public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) { List<Field> fields = new ArrayList<Field>(); for (Class<?> acls = clazz; acls != null; acls = acls.getSuperclass()) { for (Field field : acls.getDeclaredFields()) { fields.add(field); } } return fields.toArray(new Field[fields....
java
public void delete(String name) throws IOException { if (name.equalsIgnoreCase(DIGITAL_SIGNATURE)) { set(0,false); } else if (name.equalsIgnoreCase(NON_REPUDIATION)) { set(1,false); } else if (name.equalsIgnoreCase(KEY_ENCIPHERMENT)) { set(2,false); } ...
python
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, unitsx='', unitsy='', scalex=1, scaley=1, **kwargs): """ Add scalebars to axes Adds a set of scale bars to *ax*, matching the size to the ticks of the plot and optionally hiding the x and y axes - ax : the axis to attach ticks to ...
java
public static Node getGrandchildNode(Node parentNode, String childNodeName, String grandChildNodeName, String grandChildNodeValue){ List<Node> matchingChildren = getChildren(parentNode, childNodeName, null); for(Node child : matchingChildren){ Node matchingGrandCh...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'timezone') and self.timezone is not None: _dict['timezone'] = self.timezone if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.u...
python
def scan_results(self, obj): """Get the AP list after scanning.""" avail_network_list = pointer(WLAN_AVAILABLE_NETWORK_LIST()) self._wlan_get_available_network_list(self._handle, byref(obj['guid']), byref(avail_network_list)) networks = cast(avail_network_list.contents.Netwo...
python
def timeout(self, timeout): '''Set a new :attr:`timeout` for this protocol ''' if self._timeout is None: self.event('connection_made').bind(self._add_timeout) self.event('connection_lost').bind(self._cancel_timeout) self._timeout = timeout or 0 self._add_t...
python
def estimate_row_means( self, X, observed, column_means, column_scales): """ row_center[i] = sum{j in observed[i, :]}{ (1 / column_scale[j]) * (X[i, j] - column_center[j]) } ----------------------------------...
python
def keyDown(self, keys): """ Accepts a string of keys (including special keys wrapped in brackets or provided by the Key or KeyModifier classes). Holds down all of them. """ if not isinstance(keys, basestring): raise TypeError("keyDown expected keys to be a string") in_specia...
java
public DeletedCertificateBundle deleteCertificate(String vaultBaseUrl, String certificateName) { return deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body(); }
java
private final char parseSet(String rule, ParsePosition pos) { UnicodeSet set = new UnicodeSet(rule, pos, parseData); if (variableNext >= variableLimit) { throw new RuntimeException("Private use variables exhausted"); } set.compact(); return generateStandInFor(set); ...
java
public Date[] removeDatastream(String id, Date start, Date end) throws ServerException { assertNotInvalidated(); assertNotPendingRemoval(); ArrayList<Datastream> removeList = new ArrayList<Datastream>(); for (Datastream ds : m_obj.datastreams(id)) { boolean doRemo...
java
@Exported public Set<LabelAtom> getAssignedLabels() { Set<LabelAtom> r = Label.parse(getLabelString()); r.add(getSelfLabel()); r.addAll(getDynamicLabels()); return Collections.unmodifiableSet(r); }
python
def _add_default_entries(input_dict, defaults_dict): """ Add the entries in defaults dict into input_dict if they don't exist in input_dict This is based on the accepted answer at http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth :param dict input_dict...
python
def _on_sphinx_thread_html_ready(self, html_text): """Set our sphinx documentation based on thread result""" self._sphinx_thread.wait() self.set_rich_text_html(html_text, QUrl.fromLocalFile(self.css_path))
java
private String failureProcessing(BackupAgentResponse response) throws BackupExecuteException { try { String result = "\nFailure :\n" + "\tstatus code : " + response.getStatus() + "\n" + "\tmessage : " + new String(response.getResponseData()...
python
def add_modules(self, package): """Add the modules of the given package without their members.""" for name in os.listdir(package.__path__[0]): if name.startswith('_'): continue name = name.split('.')[0] short = '|%s|' % name long = ':mod:`~...
python
def spawn_containers(addrs, env_cls=Environment, env_params=None, mgr_cls=EnvManager, *args, **kwargs): """Spawn environments in a multiprocessing :class:`multiprocessing.Pool`. Arguments and keyword arguments are passed down to the created environments at initiali...
java
public Rectangle rectangle(float top, float bottom) { Rectangle tmp = new Rectangle(getLeft(), getBottom(), getRight(), getTop()); tmp.cloneNonPositionParameters(this); if (getTop() > top) { tmp.setTop(top); tmp.setBorder(border - (border & TOP)); } if (ge...
python
def describe(o): """Describes the object using developer-specified attributes specific to each main object type. Returns: dict: keys are specific attributes tailored to the specific object type, though `fqdn` is common to all descriptions; values are the corresponding attribute valu...
python
def run_console( self, authorization_prompt_message=_DEFAULT_AUTH_PROMPT_MESSAGE, authorization_code_message=_DEFAULT_AUTH_CODE_MESSAGE, **kwargs): """Run the flow using the console strategy. The console strategy instructs the user to open the authorizati...
java
@SuppressWarnings("WeakerAccess") public ApiFuture<List<Cluster>> listClustersAsync(String instanceId) { String name = NameUtil.formatInstanceName(projectId, instanceId); com.google.bigtable.admin.v2.ListClustersRequest request = com.google.bigtable.admin.v2.ListClustersRequest.newBuilder().setParent(...
python
def exportpub(self, format="PEM"): """ Returns public key as PEM or DER structure. """ bio = Membio() if format == "PEM": retcode = libcrypto.PEM_write_bio_PUBKEY(bio.bio, self.key) else: retcode = libcrypto.i2d_PUBKEY_bio(bio.bio, self.key) ...
python
def _location_infos_equal(left, right): """Return True if LocationInfo objects are equivalent for the SQL backend, False otherwise. LocationInfo objects are considered equal for the SQL backend iff the optional scopes depth, recursive scopes depth, types and parent query paths are equal. Args: ...
python
def update(self, *args, **kwargs): """Update the last section record""" self.augment_args(args, kwargs) kwargs['log_action'] = kwargs.get('log_action', 'update') if not self.rec: return self.add(**kwargs) else: for k, v in kwargs.items(): ...
python
def _blobs_page_start(iterator, page, response): """Grab prefixes after a :class:`~google.cloud.iterator.Page` started. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type page: :class:`~google.cloud.api.core.page_iterator.Page...
python
def download(self, obj, directory, structure=True): """ Fetches the object from storage, and writes it to the specified directory. The directory must exist before calling this method. If the object name represents a nested folder structure, such as "foo/bar/baz.txt", that folder...
python
def items(self): """ Generator returning all keys and values stored in a trie. """ L = [] def aux(node, s): s = s + node.char if node.output is not nil: L.append((s, node.output)) for child in node.children.values(): if child is not node: aux(child, s) aux(self.root, '') return it...
java
public Paint getFrameBorderPaint(Shape s) { switch (state) { case BACKGROUND_ENABLED: return frameBorderInactive; case BACKGROUND_ENABLED_WINDOWFOCUSED: return frameBorderActive; } return null; }
java
public static RocksDbWrapper openReadOnly(File directory) throws RocksDbException, IOException { RocksDbWrapper rocksDbWrapper = new RocksDbWrapper(directory, true); rocksDbWrapper.init(); return rocksDbWrapper; }
java
@Override public void add(IBasicEntity entity) throws CachingException { final EntityIdentifier entityIdentifier = entity.getEntityIdentifier(); final Class<? extends IBasicEntity> addType = entityIdentifier.getType(); if (!this.entityType.isAssignableFrom(addType)) { throw new ...
java
@Override public Set<IPersonAttributes> getPeopleWithMultivaluedAttributes(final Map<String, List<Object>> seed, final IPersonAttributeDaoFilter filter) { Validate.notNull(seed, "Argument 'seed' cannot be null."); for (final Attri...
java
public static <E extends Comparable<?>> TreeSet<E> newTreeSet(Iterable<? extends E> elements) { TreeSet<E> set = newTreeSet(); for (E element : elements) { set.add(element); } return set; }
java
private void addToInvalidates(Block b, boolean ackRequired) { StringBuilder sb = new StringBuilder(); for (Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(b); it.hasNext();) { DatanodeDescriptor node = it.next(); addToInvalidatesNoLog(b, node, ackRequired); sb.append(node.getNam...
java
public static String pluralize(String word) { if (word == null) { throw new IllegalArgumentException(); } final String lowerCaseWord = word.toLowerCase(); if (endsWithAny(lowerCaseWord, "s", "sh", "o")) { return word + "es"; } if (lowerCaseWord.en...
java
static String normalizeString(String string, int desiredLength) { if (string == null || string.length() == 0) { throw new IllegalArgumentException("Must supply a non-null, non-empty string."); } if (desiredLength <= 0) { throw new IllegalArgumentException("Desired length must be greater than zer...
java
private static String removeLastDot(final String pkgName) { return pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName; }
java
private void initMimeTypes() { // legacy MIME type initialization: try to read properties file Properties mimeTypes = new Properties(); try { // first try: read MIME types from default package mimeTypes.load(getClass().getClassLoader().getResourceAsStream("mimetypes.prop...
java
private static String[] executeShellCommand(String[] command) throws IOException { String groups = Shell.execCommand(command); StringTokenizer tokenizer = new StringTokenizer(groups); int numOfTokens = tokenizer.countTokens(); String[] tokens = new String[numOfTokens]; for (int i=0; tokenizer.hasM...
java
public com.google.protobuf.ByteString getInstanceClassBytes() { java.lang.Object ref = instanceClass_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); instanceClass_ = b; ...