language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected void readMetadata() throws IOException { int blockCount = super.read(); // System.out.println ("blocks to read: " + blockCount); int byteCount = (blockCount * 16); // 16 bytes per block if (byteCount <= 0) return; // WTF?! byte[] metadataBlock = new byte[byteCount]; int index = 0; // build an a...
java
private void _processAttribute (final CAttributePropertyInfo aPropertyInfo, final ClassOutline aClassOutline) { final String sPropertyName = aPropertyInfo.getName (false); final XSComponent aDefinition = aPropertyInfo.getSchemaComponent (); final AttributeUseImpl aParticle = (AttributeUseImpl) aDefinitio...
java
protected int startsWithIgnoredWord(String word, boolean caseSensitive) { if (word.length() < 4) { return 0; } Optional<String> match = Optional.empty(); if(caseSensitive) { Set<String> subset = wordsToBeIgnoredDictionary.get(word.substring(0, 1)); if (subset != null) { match =...
python
def _wait_for_process(self, pid, name): """Wait for the given process to terminate. @return tuple of exit code and resource usage """ try: logging.debug("Waiting for process %s with pid %s", name, pid) unused_pid, exitcode, ru_child = os.wait4(pid, 0) ...
python
def _set_fabric_dport(self, v, load=False): """ Setter method for fabric_dport, mapped from YANG variable /interface/fortygigabitethernet/fabric/fabric_dport (container) If this variable is read-only (config: false) in the source YANG file, then _set_fabric_dport is considered as a private method. B...
python
def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec): """Process computed edge rule Recursively processes BELAst versus a single computed edge rule Args: edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs ast (Function): BEL Function AS...
java
public String getParameter(String name) { String[] values = parameters.get(name); if (values == null) { return null; } if (values.length == 0) { return ""; } return values[0]; }
java
public void cleanup () { // tell any pending object subscribers that they're not getting their bits for (PendingRequest<?> req : _penders.values()) { for (Subscriber<?> sub : req.targets) { sub.requestFailed(req.oid, new ObjectAccessException("Client connection closed"));...
java
public static List<CommerceNotificationTemplate> filterFindByGroupId( long groupId, int start, int end) { return getPersistence().filterFindByGroupId(groupId, start, end); }
python
def pluralize(singular=None): """ Naively pluralize words """ if singular.endswith("y") and not singular.endswith("ay"): plural = singular[:-1] + "ies" elif singular.endswith("s"): plural = singular + "es" else: plural = singular + "s" return plural
java
public static String join(final Object array[], final String delim) { return join(new StringBuffer(), array, delim); }
python
def _replace_greek_characters(line): """Replace greek characters in a string.""" for greek_char, replacement in iteritems(_GREEK_REPLACEMENTS): try: line = line.replace(greek_char, replacement) except UnicodeDecodeError: current_app.logger.exception("Unicode decoding erro...
java
public static URI relativize(URI base,URI target) { if(!base.getScheme().equals(target.getScheme())) { return target; } StringBuilder rel = new StringBuilder(); String path = base.getPath(); String separator = "/"; StringTokenizer tokenizer = new StringTokeniz...
python
def date_from_quarter(base_date, ordinal, year): """ Extract date from quarter of a year """ interval = 3 month_start = interval * (ordinal - 1) if month_start < 0: month_start = 9 month_end = month_start + interval if month_start == 0: month_start = 1 return [ ...
python
def return_item_count_on_page(self, page=1, total_items=1): """ Return the number of items on page. Args: * page = The Page to test for * total_items = the total item count Returns: * Integer - Which represents the calculated number of items on page. """ up_...
python
def update_username( self, username: Union[str, None] ) -> bool: """Use this method to update your own username. This method only works for users, not bots. Bot usernames must be changed via Bot Support or by recreating them from scratch using BotFather. To update a ...
python
def get_biographies(self, results=15, start=0, license=None, cache=True): """Get a list of artist biographies Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. r...
python
def read_aldb(self, mem_addr=0x0000, num_recs=0): """Read the device All-Link Database.""" if self._aldb.version == ALDBVersion.Null: _LOGGER.info('Device %s does not contain an All-Link Database', self._address.human) else: _LOGGER.info('Reading ...
java
public UnfilledDependency replaceObject(int newObjectIndex) { return new UnfilledDependency(subject, subjectSyntax, subjectFunctionVarIndex, subjectArgIndex, null, newObjectIndex); }
java
public void buildAnnotationTypeRequiredMemberSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters.get(VisibleMemberMap.Kind.ANNOTATION_TYPE_MEMBER_REQUIRED); VisibleMemberMap visibleMemberMap = getVisibleMemberMap(VisibleMem...
python
def delete(self, pk): """Delete item from Model --- delete: parameters: - in: path schema: type: integer name: pk responses: 200: description: Item deleted content: applica...
java
@Override public <T> DtoQuery<T> createDtoQuery(Class<T> dtoType, String sql) { return ebeanServer.findDto(dtoType, sql).setRelaxedMode(); }
python
def first_where(pred, iterable, default=None): """Returns the first element in an iterable that meets the given predicate. :param default: is the default value to use if the predicate matches none of the elements. """ return next(six.moves.filter(pred, iterable), default)
java
protected final O execute(@Nullable EventLoop eventLoop, HttpMethod method, String path, @Nullable String query, @Nullable String fragment, I req, BiFunction<ClientRequestContext, Throwable, O> fallback) { final ClientRequestContext ctx; if (e...
java
@Override public Object put(Object key, Object value) { final String methodName = "put(key, value)"; return functionNotAvailable(methodName); }
python
def get_simple_info_for_index(self, index=None, params={}, **kwargs): """ Return a list of simple info by specified index (default all), each elements is a dictionary such as { 'health' : 'green', 'status' : 'open', 'index' : 'xxxx', 'uuid' : 'xxxx', '...
java
public void watch(Watcher watcher) throws WatchException{ if(isClosed){ throw new WatchException("Watch Monitor is closed !"); } registerPath(); // log.debug("Start watching path: [{}]", this.path); while (false == isClosed) { WatchKey wk; try { wk = watchService.take(); } catch (...
python
def delete_multi_async(blob_keys, **options): """Async version of delete_multi().""" if isinstance(blob_keys, (basestring, BlobKey)): raise TypeError('Expected a list, got %r' % (blob_key,)) rpc = blobstore.create_rpc(**options) yield blobstore.delete_async(blob_keys, rpc=rpc)
python
def index_siblings(pid, include_pid=False, children=None, neighbors_eager=False, eager=False, with_deposits=True): """Send sibling records of the passed pid for indexing. Note: By default does not index the 'pid' itself, only zero or more siblings. :param pid: PID (recid) of w...
java
@SuppressWarnings("unchecked") public static <T> T getSingletonService(Class<T> intf) { T ret = null; synchronized (singletons) { if (singletons.containsKey(intf)) { ret = (T) singletons.get(intf); } else { List<T> services = getServices(intf)...
java
public String removeSuffix(String original, String suffix) { if (original.endsWith(suffix)) { return original.substring(0, original.length() - suffix.length()); } return original; }
python
def _get_smart_storage_config_by_controller_model(self, controller_model): """Returns a SmartStorageConfig Instance for controller by model. :returns: SmartStorageConfig Instance for controller """ ac = self.smart_storage.array_controllers.array_controller_by_model( controll...
java
@Override public CommerceAccountUserRel fetchByCommerceAccountId_Last( long commerceAccountId, OrderByComparator<CommerceAccountUserRel> orderByComparator) { int count = countByCommerceAccountId(commerceAccountId); if (count == 0) { return null; } List<CommerceAccountUserRel> list = findByCommerceAcco...
java
@Nonnull public static <Message extends PMessage<Message, Field>, Field extends PField> Stream<Message> path(Path file, Serializer serializer, PMessageDescriptor<Message, Field> descriptor) throws IOException { return file(file.toFile(), seri...
python
def invalid_marker(text): """ Validate text as a PEP 508 environment marker; return an exception if invalid or False otherwise. """ try: evaluate_marker(text) except SyntaxError as e: e.filename = None e.lineno = None return e return False
python
def supported_operations(self): """ All file operations supported by the camera. """ return tuple(op for op in backend.FILE_OPS if self._operations & op)
java
public void domain_mailingList_name_PUT(String domain, String name, OvhMailingList body) throws IOException { String qPath = "/email/domain/{domain}/mailingList/{name}"; StringBuilder sb = path(qPath, domain, name); exec(qPath, "PUT", sb.toString(), body); }
java
public static int cudaMemset(Pointer mem, int c, long count) { return checkResult(cudaMemsetNative(mem, c, count)); }
java
public URIBuilder setPort(final int port) { this.port = port < 0 ? -1 : port; this.encodedSchemeSpecificPart = null; this.encodedAuthority = null; return this; }
java
public static String encodeStringsAsBase64Parameter(List<String> strings) { JSONArray array = new JSONArray(); for (String string : strings) { array.put(string); } byte[] bytes; try { // use obfuscateBytes here to to make the output look more random ...
python
def interrupt(self): """ Interrupts the current database from processing. """ if self._database and self._databaseThreadId: # support Orb 2 interruption capabilities try: self._database.interrupt(self._databaseThreadId) except A...
java
public synchronized void persist() throws KeyStoreException, NoSuchAlgorithmException, CertificateException { try { FileOutputStream kso = new FileOutputStream(new File(root, _caPrivateKeystore)); _ks.store(kso, _keystorepass); kso.flush(); kso.close(); persistCertMap(); persistSubjectMap(); pe...
java
public static void main(String[] args) throws InterruptedException { TagContextBuilder tagContextBuilder = tagger.currentBuilder().put(FRONTEND_KEY, TagValue.create("mobile-ios9.3.5")); SpanBuilder spanBuilder = tracer .spanBuilder("my.org/ProcessVideo") .setRecordEvents(...
java
public String parseString(String name) { String property = getProperties().getProperty(name); if (property == null) { throw new NullPointerException(); } return property; }
python
def add_file_to_zip(zip_file, filename, archname=None, compress_type=None): """ Zip <filename> into <zip_file> as <archname>. :param str|unicode zip_file: The file name of the zip file :param str|unicode filename: The name of the file to add, including the path :param str|unicode archname: The new n...
java
static String escape(final String text, final CssIdentifierEscapeType escapeType, final CssIdentifierEscapeLevel escapeLevel) { if (text == null) { return null; } final int level = escapeLevel.getEscapeLevel(); final boolean useBackslashEscapes = escapeType.getUseBackslashE...
python
def plot(self, threshold=None, **kwargs): """Barplot of the ARMA response.""" try: # Works under matplotlib 3. pyplot.bar(x=self.ma.delays+.5, height=self.response, width=1., fill=False, **kwargs) except TypeError: # pragma: no cover #...
python
def signature_type(self): """Return the signature type used in this MAR. Returns: One of None, 'unknown', 'sha1', or 'sha384' """ if not self.mardata.signatures: return None for sig in self.mardata.signatures.sigs: if sig.algorithm_id == 1: ...
java
public static List<String> parseConnectionPrefixes(Config config, SharedRestClientKey key) throws URISyntaxException, NotConfiguredException { if (key instanceof UriRestClientKey) { return Lists.newArrayList(((UriRestClientKey) key).getUri()); } if (!config.hasPath(SERVER_URI_KEY)) { throw new ...
python
def _sendQueued(self): """Connection just came up, send the unsent requests.""" for tReq in list(self.requests.values()): # must copy, may del if not tReq.sent: self._sendRequest(tReq)
java
public static Point getSize(Resources res, int resId) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); int width = options.outWidth; int height = options.outHeight; return ...
python
def _checkretry(self, mydelay, condition, tries_remaining, data): """Check if input parameters allow to retries function execution. :param float mydelay: waiting delay between two execution. :param int condition: condition to check with this condition. :param int tries_remaining: tries ...
python
def vei_CoR_veX(X, C=None, R=None): """ Args: X: NxPxS tensor C: CxC row covariance (if None: C set to I_PP) R: NxN row covariance (if None: R set to I_NN) Returns: NxPxS tensor obtained as ve^{-1}((C \kron R) ve(X)) where ve(X) reshapes X as a NPxS matrix. """...
python
def authenticate_server(self, response): """ Uses GSSAPI to authenticate the server. Returns True on success, False on failure. """ log.debug("authenticate_server(): Authenticate header: {0}".format( _negotiate_value(response))) host = urlparse(response.url...
java
@Override public void release() { super.release(); setBase64Expr(null); setActionExpr(null); setModuleExpr(null); setAlignExpr(null); setAltExpr(null); setAltKeyExpr(null); setBorderExpr(null); setBundleExpr(null); setDirExpr(null); setHeightExpr(null); setHspaceExpr(null); setImageNameExpr(n...
java
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public final void setFontFeatureSettings(final String fontFeatureSettings) { getView().setFontFeatureSettings(fontFeatureSettings); }
python
def assert_unordered_list_eq(expected, actual, message=None): """Raises an AssertionError if the objects contained in expected are not equal to the objects contained in actual without regard to their order. This takes quadratic time in the umber of elements in actual; don't use it for very long lists....
java
@Override public void actionCommit() { List<Throwable> errors = new ArrayList<Throwable>(); try { if (isForAll()) { OpenCms.getSessionManager().sendBroadcast(getCms(), m_msgInfo.getMsg()); } else { List<String> ids = CmsStringUtil.splitAsList...
java
public Versioned<E> next() { if(!hasNext()) throw new NoSuchElementException(); Versioned<VListNode<E>> tmpNode = _nextNode; VListNode<E> tmpNodeValue = _nextNode.getValue(); _lastId = tmpNodeValue.getId(); _lastCall = LastCall.NEXT; if(tmpNodeValue.getNextI...
python
def p_expr_unary_op(p): '''expr : PLUS expr | MINUS expr | NOT expr | BOOLEAN_NOT expr''' p[0] = ast.UnaryOp(p[1], p[2], lineno=p.lineno(1))
java
public void bind(Object item) { this.item = item; if (onItemBindListener != null) { onItemBindListener.onItemBind(itemView, item, getAdapterPosition()); } }
python
def convertLocation(self, pos): """ Accepts a position string (start/length) and returns a GA4GH AlleleLocation with populated fields. :param pos: :return: protocol.AlleleLocation """ if isUnspecified(pos): return None coordLen = pos.split('/')...
python
def _get_uniprot_id(agent): """Return the UniProt ID for an agent, looking up in HGNC if necessary. If the UniProt ID is a list then return the first ID by default. """ up_id = agent.db_refs.get('UP') hgnc_id = agent.db_refs.get('HGNC') if up_id is None: if hgnc_id is None: ...
python
def convex_conj(self): """The convex conjugate functional. Convex conjugate distributes over separable sums, so the result is simply the separable sum of the convex conjugates. """ convex_conjs = [func.convex_conj for func in self.functionals] return SeparableSum(*convex...
java
protected String signRSAWithQuote(final List<StringPair> p) { String param = join(p, false, true); String sign = rsaSign(param); return sign; }
java
private AtomicReferenceArray getTable() { expungeCount++; if (expungeCount >= MAX_EXPUNGE_COUNT) { expungeCount = 0; if (expungerUpdater.compareAndSet(this, 0, 1)) { MithraConcurrentEvictorThread.getInstance().queueEviction(this); ...
python
def get_module_classes(node): """ Return classes associated with a given module """ return [ child for child in ast.walk(node) if isinstance(child, ast.ClassDef) ]
python
def autoprops(include=None, # type: Union[str, Tuple[str]] exclude=None, # type: Union[str, Tuple[str]] cls=DECORATED): """ A decorator to automatically generate all properties getters and setters from the class constructor. * if a @contract annotation exist on the __init__ met...
java
public void flush() throws InterruptedException { List<Entry> toFlush = new ArrayList<>(mEvictBatchSize); Iterator<Entry> it = mMap.values().iterator(); while (it.hasNext()) { if (Thread.interrupted()) { throw new InterruptedException(); } while (toFlush.size() < mEvictBatchSize &&...
python
def on_epoch_end(self, last_metrics, **kwargs): "Finish the computation and sends the result to the Recorder." if not self.nums: return metrics = [self.metrics[name]/self.nums for name in self.names] return {'last_metrics': last_metrics+metrics}
java
@Override public CPInstance findByG_ST_First(long groupId, int status, OrderByComparator<CPInstance> orderByComparator) throws NoSuchCPInstanceException { CPInstance cpInstance = fetchByG_ST_First(groupId, status, orderByComparator); if (cpInstance != null) { return cpInstance; } StringBundler msg...
java
public void loadTemplateClass(TemplateClass tc) { if (!readEnabled()) { return; } InputStream is = null; try { File f = getCacheFile(tc); if (!f.exists() || !f.canRead()) return; is = new BufferedInputStream(new FileInputStream(f)); ...
java
public static @Nonnull <T> Optional<T> tryInstantiate(@Nonnull Constructor<T> type, Object... args) { try { return Optional.of(type.newInstance(args)); } catch (Throwable e) { Logger log = ClassUtils.REFLECTION_LOGGER; if (log.isDebugEnabled()) { log.d...
java
private void verifyReplication(String src, short replication, String clientName ) throws IOException { String text = "file " + src + ((clientName != null) ? " on client " + clientName : "") + ".\n" + "Requested replication " + rep...
java
private void initializeChangedMap() { // set changed flags changed.put("display_name", false); changed.put("description", false); changed.put("notes", false); changed.put("custom", false); changed.put("created", false); }
python
def endpoints(self): """ Get all the endpoints under this node in a tree like structure. Returns: (tuple): name (str): This node's name. endpoint (str): Endpoint name relative to root. children (list): ``child.endpoints for each child ...
python
def merge_from_dict(self, dct, lists_only=False): """ Merges a dictionary into this configuration object. See :meth:`ConfigurationObject.merge` for details. :param dct: Values to update the ConfigurationObject with. :type dct: dict :param lists_only: Ignore single-value...
java
public String getActiveServerAddress() { CuratorFramework client = curatorFactory.clientInstance(); String serverAddress = null; try { HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); byte...
java
public void deleteMsgsWithNoReferences() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "deleteMsgsWithNoReferences"); if (null != _pubSubRealization) //doing a sanity check with checking for not null _pubSubRealization.deleteMsgsWithNoReferen...
java
@SuppressWarnings("unchecked") public Enumeration<String> getInitParameterNames() { List<String> initParameterNames = Collections.list(servletConfig.getInitParameterNames()); initParameterNames.addAll(additionalConfigurations.keySet()); return Collections.enumeration(initParameterNames); ...
python
def _get_ilo_details(self): """Gets iLO details :raises: IloError, on an error from iLO. :raises: IloConnectionError, if iLO is not up after reset. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ manager_uri = '/r...
java
@Override public CPDefinitionGroupedEntry fetchCPDefinitionGroupedEntryByUuidAndGroupId( String uuid, long groupId) { return cpDefinitionGroupedEntryPersistence.fetchByUUID_G(uuid, groupId); }
java
@Override public int print( ChronoDisplay formattable, Appendable buffer, AttributeQuery attributes, Set<ElementPosition> positions, // optional boolean quickPath ) throws IOException { int value = formattable.getInt(this.element); if (value < 0) { ...
python
def get_outbox_fax(self, outbox_fax_id, **kwargs): # noqa: E501 """Get an outbox record # noqa: E501 Get an outbox fax record information # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thr...
python
def attribute_dependend_key(key_function, *dependencies): """Return a cache key for the specified hashable arguments with additional dependent arguments.""" def dependend_key_function(self, *args, **kwargs): key = hash_key(*args, **kwargs) if len(dependencies) > 0: dependec...
python
def filter_int(string, default=None, start=None, stop=None): """Return the input integer, or the default.""" try: i = int(string) if start is not None and i < start: raise InvalidInputError("value too small") if stop is not None and i >= stop: raise InvalidInputEr...
java
public void closeCurrentFile() { try { this.closer.close(); } catch (IOException e) { if (this.currentFile != null) { LOG.error("Failed to close file: " + this.currentFile, e); } } }
python
def prune_unrepresented(self): """ Remove nodes without sequences or children below this node. """ for node in self.depth_first_iter(self_first=False): if (not node.children and not node.sequence_ids and node is not self): ...
java
private void createNameToCodePointMap() { charNameByCodePoint = new HashMap<Integer, String>(); for (String glyphListFile : new String[] { "adobeGlyphlist.txt", "additional_glyphlist.txt" }) { Scanner scanner = new Scanner(this.getClass().getResourceAsStream( ...
java
private void cancelTimers( List<org.mobicents.slee.example.sjr.data.RegistrationBinding> removedContacts) { for (RegistrationBinding binding : removedContacts) { ActivityContextInterfaceExt aci = (ActivityContextInterfaceExt) this.activityContextNamingFacility .lookup(getACIName(binding.getContactAddress()...
python
def request_restart(self, req, msg): """Restart the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the restart succeeded. Examples -------- :: ?restart !restart ok """ if self._res...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "ArcByBulge", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "ArcStringByBulge") public JAXBElement<ArcByBulgeType> createArcByBulge(ArcByBulgeType value) { return new JAXBElement<ArcByBulgeType>(_ArcByBulge_Q...
python
def is_lambda_error_response(lambda_response): """ Check to see if the output from the container is in the form of an Error/Exception from the Lambda invoke Parameters ---------- lambda_response str The response the container returned Returns -------...
java
protected void serializeEntityReference( EntityReference node, boolean bStart) throws SAXException { if (bStart) { EntityReference eref = node; // entities=true if ((fFeatures & ENTITIES) != 0) { // perform well-formedn...
python
def RemoveMethod(self, function): """ Removes the specified function's MethodWrapper from the added_methods list, so we don't re-bind it when making a clone. """ self.added_methods = [dm for dm in self.added_methods if not dm.method is function]
python
def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
java
private String cleanAndTrimString(String text, int maxTextLength) { if (StringUtils.isNotBlank(text)) { String cleaned = text.trim().replaceAll("[\\s]+", " "); return cleaned.length() <= maxTextLength ? cleaned : cleaned.substring(0, maxTextLength)...
python
def _players(self): """Get player attributes with index. No Gaia.""" for i in range(1, self._header.replay.num_players): yield i, self._header.initial.players[i].attributes
python
def get_user_history (history_id=None): """ Get all visible dataset infos of user history. Return a list of dict of each dataset. """ history_id = history_id or os.environ['HISTORY_ID'] gi = get_galaxy_connection(history_id=history_id, obj=False) hc = HistoryClient(gi) history = h...
java
protected void onQueryCompleted(Cursor result, Uri uri, MatcherPattern target, QueryParameters parameter) { result.setNotificationUri(this.getContext().getContentResolver(), uri); }