language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Integer parseDefault(String input, Integer defaultValue) { if (input == null) { return defaultValue; } Integer answer = defaultValue; try { answer = Integer.parseInt(input); } catch (NumberFormatException ignored) { } return answer; ...
java
public double[] eval( double currentTimeInMinutes, double[] input, double[] rainArray, double[] etpArray, boolean isAtFinalSubtimestep ) { // the input's length is twice the number of links... the first half // corresponds to links // discharge and the second to hillslopes storage ...
java
@Override public CommerceTaxMethod findByGroupId_First(long groupId, OrderByComparator<CommerceTaxMethod> orderByComparator) throws NoSuchTaxMethodException { CommerceTaxMethod commerceTaxMethod = fetchByGroupId_First(groupId, orderByComparator); if (commerceTaxMethod != null) { return commerceTaxMetho...
python
def parse_class_names(args): """ parse # classes and class_names if applicable """ num_class = args.num_class if len(args.class_names) > 0: if os.path.isfile(args.class_names): # try to open it to read class names with open(args.class_names, 'r') as f: class_n...
java
void recycle() { _outputState=NO_OUT; _out=null; _writer=null; _session=null; _noSession=false; _locale=null; _charEncodingSetInContentType=false; }
java
public LineSegment subSegment(double offset, double length) { Point subSegmentStart = pointAlongLineSegment(offset); Point subSegmentEnd = pointAlongLineSegment(offset + length); return new LineSegment(subSegmentStart, subSegmentEnd); }
java
public static void createAllDirectories() { try { if (conf.data_file_directories.length == 0) throw new ConfigurationException("At least one DataFileDirectory must be specified"); for (String dataFileDirectory : conf.data_file_directories) { ...
java
public boolean changeHorizon(long val) { this.removeConstraint(horizonConstraint); SimpleDistanceConstraint sdc = new SimpleDistanceConstraint(); sdc.setFrom(this.getVariable(0)); sdc.setTo(this.getVariable(1)); sdc.setMinimum(val); sdc.setMaximum(val); if (this.addConstraint(sdc)) { this.H =...
python
def entity_list(args): """ List entities in a workspace. """ r = fapi.get_entities_with_type(args.project, args.workspace) fapi._check_response_code(r, 200) return [ '{0}\t{1}'.format(e['entityType'], e['name']) for e in r.json() ]
java
private static Typeface getFontFromTag(AssetManager assets, View view, boolean strict) { final Object tagObject = view.getTag(); final String tag = tagObject instanceof String ? (String) tagObject : null; final Typeface typeface = getFontFromString(assets, tag, strict); if (!(tagObject ...
python
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: build_pxe_default /config_templates/build_pxe_default clone /config_templates/clone revision /conf...
python
def base_args(parser): """Add the generic command line options""" generic_args(parser) parser.add_argument('--monochrome', dest='monochrome', help='Whether or not to use colors', action='store_true') parser.add_argument('--metadata'...
java
public static void addAdditionalNamenodesToProps(Props props, String additionalNamenodes) { String otherNamenodes = props.get(OTHER_NAMENODES_PROPERTY); if (otherNamenodes != null && otherNamenodes.length() > 0) { props.put(OTHER_NAMENODES_PROPERTY, otherNamenodes + "," + additionalNamenodes); } else ...
java
private boolean hasUnblockedPathToGrant( IAuthorizationService service, IAuthorizationPrincipal principal, IPermissionOwner owner, IPermissionActivity activity, IPermissionTarget target, Set<IGroupMember> seenGroups) throws GroupsExcept...
python
def available_on_day(self, day): """ Return events that are available on a given day. """ if isinstance(day, datetime): d = day.date() else: d = day return self.starts_within(d, d)
java
private ZapMenuItem getMenuItemPolicy() { if (menuItemPolicy == null) { menuItemPolicy = new ZapMenuItem("menu.analyse.scanPolicy", getView().getMenuShortcutKeyStroke(KeyEvent.VK_P, 0, false)); menuItemPolicy.addActionListener(new java.awt.event.ActionListener()...
python
def bytes_to_long(s): """bytes_to_long(string) : long Convert a byte string to a long integer. This is (essentially) the inverse of long_to_bytes(). """ if isinstance(s, int): # On Python 2, indexing into a bytearray returns a byte string; on Python 3, an int. return s acc = 0 ...
java
@Sensitive @Override public byte[] getCredentialToken() throws CredentialDestroyedException, CredentialExpiredException { if (credentialToken != null) { return credentialToken.clone(); } else { return null; } }
python
def reduce_value(cls, value): """Cleans the value by either compressing it if it is a string, or reducing it if it is a number. """ if isinstance(value, str): return to_compressed_string(value) elif isinstance(value, bool): return value elif isinstance(value, Number): return re...
python
def holdout(self, train_perc=0.7, num_rep=50, stratified=True, return_ids_only=False, format='MLDataset'): """ Builds a generator for train and test sets for cross-validation. """ ids_in_class = {cid: self....
java
@Override public void handleChannelData(final JSONObject jsonObject) throws BitfinexClientException { final String channelType = jsonObject.getString("channel"); final int channelId = jsonObject.getInt("chanId"); BitfinexStreamSymbol symbol = null; switch (channelType) { case "ticker": symbol = handleT...
java
protected XContentBuilder newBuilder() throws IndexException { try { XContentBuilder builder = XContentFactory.jsonBuilder(); if (debug()) { builder = builder.prettyPrint(); } return builder; } catch (final Throwable t) { throw new IndexException(t); } }
java
public ExpressionSpecBuilder addUpdate(UpdateAction updateAction) { final String operator = updateAction.getOperator(); List<UpdateAction> list = updates.get(operator); if (list == null) { list = new LinkedList<UpdateAction>(); updates.put(operator, list); } ...
python
def se(actual, predicted): """ Computes the squared error. This function computes the squared error between two numbers, or for element between a pair of lists or numpy arrays. Parameters ---------- actual : int, float, list of numbers, numpy array The ground truth value p...
java
public List<Map<String, String>> getQuagganInfo(String[] ids) throws GuildWars2Exception { isParamValid(new ParamChecker(ids)); try { Response<List<Map<String, String>>> response = gw2API.getQuagganInfo(processIds(ids)).execute(); if (!response.isSuccessful()) throwError(response.code(), response.errorBody())...
java
private void parseJITOnlyReads(Map<Object, Object> props) { Object value = props.get(HttpConfigConstants.PROPNAME_JIT_ONLY_READS); if (null != value) { this.bJITOnlyReads = convertBoolean(value); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { T...
python
def acosh(x): """ acosh(x) Hyperbolic arc cos function. """ _math = infer_math(x) if _math is math: return _math.acosh(x) else: return _math.arccosh(x)
python
def pageHeader(self, title): """Render the page header""" self.setSessionCookie() self.wfile.write('''\ Content-type: text/html; charset=UTF-8 <html> <head><title>%s</title></head> <style type="text/css"> * { font-family: verdana,sans-serif; } body { width:...
python
def get_token_and_data(self, data): ''' When we receive this, we have 'token):data' ''' token = '' for c in data: if c != ')': token = token + c else: break; return token, data.lstrip(token + '):')
java
public final void entryRuleXRelationalExpression() throws RecognitionException { try { // InternalXbaseWithAnnotations.g:434:1: ( ruleXRelationalExpression EOF ) // InternalXbaseWithAnnotations.g:435:1: ruleXRelationalExpression EOF { if ( state.backtracking==0 ) ...
python
def cache_control_expires(num_hours): """ Set the appropriate Cache-Control and Expires headers for the given number of hours. """ num_seconds = int(num_hours * 60 * 60) def decorator(func): @wraps(func) def inner(request, *args, **kwargs): response = func(request, *...
python
def pop(self, key, *args, **kwargs): """Remove specified key and return the corresponding value. :keyword default: If key is not found, ``default`` is returned if given, otherwise :exc:`KeyError` is raised. """ try: val = self[key] except KeyError: ...
python
def _createFuture(func, *args, **kwargs): """Helper function to create a future.""" assert callable(func), ( "The provided func parameter is not a callable." ) if scoop.IS_ORIGIN and "SCOOP_WORKER" not in sys.modules: sys.modules["SCOOP_WORKER"] = sys.modules["__main__"] # If funct...
python
def auth_add_creds(self, username, password, pwtype='plain'): """ Add a valid set of credentials to be accepted for authentication. Calling this function will automatically enable requiring authentication. Passwords can be provided in either plaintext or as a hash by specifying the hash type in the *pwtype* a...
java
public TonerSaverTSvCtrl createTonerSaverTSvCtrlFromString(EDataType eDataType, String initialValue) { TonerSaverTSvCtrl result = TonerSaverTSvCtrl.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'")...
java
public void setRunDirection(int runDirection) { if (runDirection < PdfWriter.RUN_DIRECTION_DEFAULT || runDirection > PdfWriter.RUN_DIRECTION_RTL) throw new RuntimeException("Invalid run direction: " + runDirection); this.runDirection = runDirection; }
python
def _version_view(self): """ View that returns the contents of version.json or a 404. """ version_json = self._version_callback(self.version_path) if version_json is None: return 'version.json not found', 404 else: return jsonify(version_json)
java
protected PropertyData removeChildProperty(final String parentIdentifier, final String childIdentifier) { final List<PropertyData> childProperties = propertiesCache.get(parentIdentifier); if (childProperties != null) { synchronized (childProperties) { // [PN] 17.01.07 ...
java
@GwtIncompatible("Unnecessary") private void outputSourceMap(B options, String associatedName) throws IOException { if (Strings.isNullOrEmpty(options.sourceMapOutputPath) || options.sourceMapOutputPath.equals("/dev/null")) { return; } String outName = expandSourceMapPath(options, null); ...
java
private void handlePipeLining() { HttpServiceContextImpl sc = getHTTPContext(); WsByteBuffer buffer = sc.returnLastBuffer(); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Pipelined request found: " + buffer); } sc.clear(); //...
python
def GetSoapXMLForComplexType(self, type_name, value): """Return an XML string representing a SOAP complex type. Args: type_name: The name of the type with namespace prefix if necessary. value: A python dictionary to hydrate the type instance with. Returns: A string containing the SOAP XM...
java
public NodeType[] getRequiredPrimaryTypes() { InternalQName[] requiredPrimaryTypes = nodeDefinitionData.getRequiredPrimaryTypes(); NodeType[] result = new NodeType[requiredPrimaryTypes.length]; for (int i = 0; i < requiredPrimaryTypes.length; i++) { NodeTypeData ntData = nodeTypeData...
java
public Observable<Page<IotHubQuotaMetricInfoInner>> getQuotaMetricsAsync(final String resourceGroupName, final String resourceName) { return getQuotaMetricsWithServiceResponseAsync(resourceGroupName, resourceName) .map(new Func1<ServiceResponse<Page<IotHubQuotaMetricInfoInner>>, Page<IotHubQuotaMetr...
python
def convert(self, targetunits): """Set new user unit, for either wavelength or flux. This effectively converts the spectrum wavelength or flux to given unit. Note that actual data are always kept in internal units (Angstrom and ``photlam``), and only converted to user units by :...
java
public static List<Path> getAncestorPathList(Path startPath) { List<Path> ancestorPathList = new ArrayList<>(); buildPathListOfAncestorDirectory(ancestorPathList, startPath); Collections.reverse(ancestorPathList); return ancestorPathList; }
python
def get_mount_points(): """Get all current mount points of the system. Changes to the mount points during iteration may be reflected in the result. @return a generator of (source, target, fstype, options), where options is a list of bytes instances, and the others are bytes instances (this avoids en...
python
def tag(name, message, author=None): # type: (str, str, Author, bool) -> None """ Tag the current commit. Args: name (str): The tag name. message (str): The tag message. Same as ``-m`` parameter in ``git tag``. author (Author): The commit author. ...
java
protected SigninPanel<T> newSigninPanel(final String id, final IModel<T> model) { return new SigninPanel<>(id, model); }
java
public Subscription postponeSubscription(final Subscription subscription, final DateTime renewaldate) { return doPUT(Subscription.SUBSCRIPTION_RESOURCE + "/" + subscription.getUuid() + "/postpone?next_renewal_date=" + renewaldate, subscription, Subscription.class); }
java
public static long min(LongTuple t) { return LongTupleFunctions.reduce( t, Long.MAX_VALUE, Math::min); }
java
final public Boolean checkRealOffset() { if ((tokenRealOffset == null) || !provideRealOffset) { return false; } else if (tokenOffset == null) { return true; } else if (tokenOffset.getStart() == tokenRealOffset.getStart() && tokenOffset.getEnd() == tokenRealOffset.getEnd()) { return...
python
def get_sequence_properties(self, clean_seq=False, representatives_only=True): """Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences. Results are stored in the protein's respective SeqProp objects at ``.annotations`` Args: repres...
python
def add_assertion(self, assertion, agent, agent_label, date=None): """ Add assertion to graph :param assertion: :param agent: :param evidence_line: :param date: :return: None """ self.model.addIndividualToGraph(assertion, None, self.globaltt['asser...
python
def IterAssociatorInstances(self, InstanceName, AssocClass=None, ResultClass=None, Role=None, ResultRole=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None, ...
python
def show(self): """ More details about the selected issue or trace frame. """ self._verify_entrypoint_selected() if self.current_issue_instance_id != -1: self._show_current_issue_instance() return self._show_current_trace_frame()
java
@Override public void writeFragmentTo(MwsWriter w) { w.write("Locale", locale); w.write("Text", text); }
python
def decode(in_bytes): """Decode a string using Consistent Overhead Byte Stuffing (COBS). Input should be a byte string that has been COBS encoded. Output is also a byte string. A cobs.DecodeError exception will be raised if the encoded data is invalid.""" if isinstance(in_bytes, str): ...
java
@Override protected void suspendFaxJobImpl(FaxJob faxJob) { //get fax job ID int faxJobIDInt=WindowsFaxClientSpiHelper.getFaxJobID(faxJob); //invoke fax action this.winSuspendFaxJob(this.faxServerName,faxJobIDInt); }
java
private static void appendEncode( CssFormatter formatter, byte[] bytes ) { for( byte b : bytes ) { if ((b >= 'a' && b <= 'z' ) || (b >= 'A' && b <= 'Z' ) || (b >= '0' && b <= '9' )) { formatter.append( (char )b ); } else { switch( b ) { ...
java
private int parseUTF8Char() throws IOException { int ch = read(); if (ch < 0x80) return ch; else if ((ch & 0xe0) == 0xc0) { int ch1 = read(); int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); return v; } else if ((ch & 0xf0) ...
python
def codes_get_double_array(handle, key, size): # type: (cffi.FFI.CData, str, int) -> T.List[float] """ Get double array values from a key. :param bytes key: the keyword whose value(s) are to be extracted :rtype: T.List(float) """ values = ffi.new('double[]', size) size_p = ffi.new('siz...
python
def get_scan_parameters_table_from_meta_data(meta_data_array, scan_parameters=None): '''Takes the meta data array and returns the scan parameter values as a view of a numpy array only containing the parameter data . Parameters ---------- meta_data_array : numpy.ndarray The array with the scan pa...
python
def load_config(filename=None, text=None, test=False, commit=True, debug=False, replace=False, commit_in=None, commit_at=None, revert_in=None, revert_at=None, c...
java
public static <T> Handler<T> mdcEventLoop(final Handler<T> handler) { if (handler == null) { // Throw here instead of getting NPE inside the handler so we can see the stack trace throw new IllegalArgumentException("handler may not be null"); } final Map<String, String> mdc = MDC.getCopyOfContex...
java
public CreateTaskSetRequest withServiceRegistries(ServiceRegistry... serviceRegistries) { if (this.serviceRegistries == null) { setServiceRegistries(new com.amazonaws.internal.SdkInternalList<ServiceRegistry>(serviceRegistries.length)); } for (ServiceRegistry ele : serviceRegistries)...
python
def _iter_text_wave( self, text, numbers, step=1, fore=None, back=None, style=None, rgb_mode=False): """ Yield colorized characters from `text`, using a wave of `numbers`. Arguments: text : String to be colorized. numbers : A list/tuple ...
java
public void close() { if (gcs != null) { logger.atFine().log("close()"); try { gcs.close(); } finally { gcs = null; if (updateTimestampsExecutor != null) { try { shutdownExecutor(updateTimestampsExecutor, /* waitSeconds= */ 10); } finally { ...
java
public static List<File> getMatchingFiles(String root, String filterExpr) { if (root == null) return Collections.emptyList(); File file = new File(root); return getMatchingFiles(file, filterExpr); }
java
private static WorkUnitState mergeSplits(FileSystem fs, CopyableFile file, Collection<WorkUnitState> workUnits, Path parentPath) throws IOException { log.info(String.format("File %s was written in %d parts. Merging.", file.getDestination(), workUnits.size())); Path[] parts = new Path[workUnits.size()]; ...
java
@SuppressWarnings("unchecked") public EList<IfcProperty> getRelatedProperties() { return (EList<IfcProperty>) eGet( Ifc2x3tc1Package.Literals.IFC_PROPERTY_CONSTRAINT_RELATIONSHIP__RELATED_PROPERTIES, true); }
python
def setup_groups(portal): """Setup roles and groups for BECHEM """ logger.info("*** Setup Roles and Groups ***") portal_groups = api.get_tool("portal_groups") for gdata in GROUPS: group_id = gdata["id"] # create the group and grant the roles if group_id not in portal_groups...
python
def create_copy(self): """ Initialises a temporary directory structure and copy of MAGICC configuration files and binary. """ if self.executable is None or not isfile(self.executable): raise FileNotFoundError( "Could not find MAGICC{} executable: {}".f...
java
public Request<SNSFactorProvider> getSNSFactorProvider() { String url = baseUrl .newBuilder() .addPathSegments("api/v2/guardian/factors/push-notification/providers/sns") .build() .toString(); CustomRequest<SNSFactorProvider> request = new ...
python
def _read_para_hip_cipher(self, code, cbit, clen, *, desc, length, version): """Read HIP HIP_CIPHER parameter. Structure of HIP HIP_CIPHER parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 ...
java
public static boolean isMultiListener(String[] args) { for(int i = 0; i < args.length; i++) { if(args[i].equals("-ml")) { return true; } } return false; }
java
@Pure public double distance(BusStop stop) { if (isValidPrimitive() && stop.isValidPrimitive()) { final GeoLocationPoint p = getGeoPosition(); final GeoLocationPoint p2 = stop.getGeoPosition(); return Point2D.getDistancePointPoint(p.getX(), p.getY(), p2.getX(), p2.getY()); } return Double.NaN; }
python
def folders(self, mountPoint): """Get an iterator of JFSFolder() from the given mountPoint. "mountPoint" may be either an actual mountPoint element from JFSDevice.mountPoints{} or its .name. """ if isinstance(mountPoint, six.string_types): # shortcut: pass a mountpoint name ...
python
def _strfactory(cls, line): """factory class method for Chain :param line: header of a chain (in .chain format) """ assert type(line) == str, "this is a factory from string" line = line.rstrip().split()[1:] # the first component is the keyword "chain" tup = [t[0](t[1])...
java
public Observable<ServiceResponse<Void>> promoteWithServiceResponseAsync(String resourceGroupName, String clusterName, String scriptExecutionId) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");...
java
public OperaOptions addExtensions(List<File> paths) { for (File path : paths) { checkNotNull(path); checkArgument(path.exists(), "%s does not exist", path.getAbsolutePath()); checkArgument(!path.isDirectory(), "%s is a directory", path.getAbsolutePath()); } extensionFiles.addAll(...
java
public void setApiKey(String apiKey) { if (this.jsonHttpClient != null) { this.jsonHttpClient.setApiKey(apiKey); } if (this.restApiClient != null) { this.restApiClient.setApiKey(apiKey); } if (this.swaggerApiClient != null) { ApiKeyAuth...
python
def create_dhcp_options(self, vpc_id, cidr_block, availability_zone=None): """ Create a new DhcpOption :type vpc_id: str :param vpc_id: The ID of the VPC where you want to create the subnet. :type cidr_block: str :param cidr_block: The CIDR block you want the subnet to ...
java
public static Intent newEmptySmsIntent(Context context, String[] phoneNumbers) { return newSmsIntent(context, null, phoneNumbers); }
java
public static List<SimpleFeature> featureCollectionToList( SimpleFeatureCollection collection ) { List<SimpleFeature> featuresList = new ArrayList<SimpleFeature>(); if (collection == null) { return featuresList; } SimpleFeatureIterator featureIterator = collection.features();...
python
def materialize_as_ndarray(a): """Convert distributed arrays to ndarrays.""" if type(a) in (list, tuple): if da is not None and any(isinstance(arr, da.Array) for arr in a): return da.compute(*a, sync=True) return tuple(np.asarray(arr) for arr in a) return np.asarray(a)
python
def get_certificate_issuer_configs(self, **kwargs): # noqa: E501 """Get certificate issuer configurations. # noqa: E501 Get certificate issuer configurations, optionally filtered by reference. <br> **Example usage:** ``` curl \\ -H 'authorization: <valid access token>' \\ -H 'content-type: applicati...
python
def top(self, container, ps_args=None): """ Display the running processes of a container. Args: container (str): The container to inspect ps_args (str): An optional arguments passed to ps (e.g. ``aux``) Returns: (str): The output of the top ...
python
def etree_to_dict(tree): """Translate etree into dictionary. :param tree: etree dictionary object :type tree: <http://lxml.de/api/lxml.etree-module.html> """ d = {tree.tag.split('}')[1]: map( etree_to_dict, tree.iterchildren() ) or tree.text} return d
python
def presigned_url(self, method, bucket_name, object_name, expires=timedelta(days=7), response_headers=None, request_date=None): """ Presigns a method on an object and provides a url Example: ...
python
def update_batch_count(instance, **kwargs): """Sample post-save handler to update the sample's batch count. Batches are unpublished by default (to prevent publishing empty batches). If the `AUTO_PUBLISH_BATCH` setting is true, the batch will be published automatically when at least one published sample...
java
public static <K, V, K2, V2> MutableMap<K2, V2> collect( Map<K, V> map, Function2<? super K, ? super V, Pair<K2, V2>> function) { return MapIterate.collect(map, function, UnifiedMap.<K2, V2>newMap(map.size())); }
python
def get_tags(self, name): """ Returns a list of tags. @param str name: The name of the tag. :rtype: list[str] """ tags = list() for tag in self._tags: if tag[0] == name: tags.append(tag[1]) return tags
java
protected String computeUpLevelLink() { String parentPath = getParentPath(); String rootKey = getToolManager().getCurrentRoot(this).getKey(); CmsTool parentTool = getToolManager().resolveAdminTool(rootKey, parentPath); String upLevelLink = null; if (parentTool != null) { ...
java
public static boolean match(String keyword, String mappingId) { if (mappingId.indexOf(keyword) != -1) { // match found! return true; } return false; }
java
private static File findDirectoryOption(String[] args, String option, String name, boolean needed, boolean allow_dups, boolean create) throws ProblemException, ProblemException { File dir = null; for (int i = 0; i<args.length; ++i) { if (args[i].equals(option)) { if (...
python
def _setup(self): tablepath = _get_data_file_path("dark_matter/gammamc_dif.dat") self._data = np.loadtxt(tablepath) """ Mapping between the channel codes and the rows in the gammamc file 1 : 8, # ee 2 : 6, # mumu 3 : 3, # tautau 4 :...
python
def wiki_request(self, params): """ Make a request to the MediaWiki API using the given search parameters Args: params (dict): Request parameters Returns: A parsed dict of the JSON response Note: Useful when wanting...
java
@POST @Produces({MediaType.APPLICATION_JSON}) @Path("meta/{repository}/{workspace}/{path:.*}") public Response getScriptMetadata(@PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { ...
java
public char setIndex(int pos) { if (pos < 0) { _pos = 0; return DONE; } else if (_length <= pos) { _pos = _length; return DONE; } else { _pos = pos; return _string.charAt(pos); } }
java
@Override public void run() { boolean isValid = false; try { _socket.getChannel().configureBlocking(true); /* EndpointReaderWebSocket wsEndpointReader = _client.getEndpointReader(); do { if (! wsEndpointReader.onRead()) { return; } } whil...