language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private CompletableFuture<UpdateablePageCollection> applyUpdates(Iterator<PageEntry> updates, TimeoutTimer timer) { UpdateablePageCollection pageCollection = new UpdateablePageCollection(this.state.get().length); AtomicReference<PageWrapper> lastPage = new AtomicReference<>(null); val lastPageUp...
java
private int[] determineAll_Buckets_Sarray_Sptrmap(int q) { int[] buckets = determineAll_Buckets_Sarray(q); int strLen = length; sufPtrMap = new int[strLen + 2 * q + 1]; /* computation of first hashvalue */ int alphabetSize = alphabet.size; int mappedUcharArray = 0; ...
python
def init_node(cls, *args, **kwargs): """Initializes an ast node with the provided attributes. Python 2.6+ supports this in the node class initializers, but Python 2.5 does not, so this is intended to be an equivalent. """ node = cls() for name, value in zip(cls._fields, args): seta...
java
public ChannelHandler[] getClientChannelHandlers() { NetworkClientHandler networkClientHandler = creditBasedEnabled ? new CreditBasedPartitionRequestClientHandler() : new PartitionRequestClientHandler(); return new ChannelHandler[] { messageEncoder, new NettyMessage.NettyMessageDecoder(!creditBasedEnab...
java
@SuppressWarnings("unchecked") public static <T> Stream<Class<? extends T>> streamClasses(Collection<Class<?>> classes, Class<? extends T> baseClass) { return classes .stream() .filter(ClassPredicates.classIsDescendantOf(baseClass)) .map(c -> (Clas...
python
def get_field(self, field, idx): """ Return the field ``field`` of elements ``idx`` in the group :param field: field name :param idx: element idx :return: values of the requested field """ ret = [] scalar = False # TODO: ensure idx is unique in t...
python
def pop(self): """ Removes the last traversal path node from this traversal path. """ node = self.nodes.pop() self.__keys.remove(node.key)
python
def _clean_options(method, provided_options): """Clean the given input options. This will make sure that all options are present, either with their default values or with the given values, and that no other options are present then those supported. Args: method (str): the method name p...
python
def run_experiments(experiments, search_alg=None, scheduler=None, with_server=False, server_port=TuneServer.DEFAULT_PORT, verbose=2, resume=False, queue_trials=False, ...
python
def remove_epoch(self, epoch_name): '''This function removes an epoch from your recording extractor. Parameters ---------- epoch_name: str The name of the epoch to be removed ''' if isinstance(epoch_name, str): if epoch_name in list(self._epochs.k...
java
public static String throwableToString(Throwable t) { StringWriter s = new StringWriter(); PrintWriter p = new PrintWriter(s); t.printStackTrace(p); return s.toString(); }
python
def create_resource(self, path, transaction): """ Render a POST request. :param path: the path of the request :param transaction: the transaction :return: the response """ t = self._parent.root.with_prefix(path) max_len = 0 imax = None for...
java
public Set<de.uniulm.omi.cloudiator.flexiant.client.domain.Server> getServers( final String prefix, @Nullable String locationUUID) throws FlexiantException { return this .getResources(prefix, "resourceName", ResourceType.SERVER, Server.class, locationUUID) .stream() ....
java
public static MsgPhrase get(final String _name) throws EFapsException { final Cache<String, MsgPhrase> cache = InfinispanCache.get().<String, MsgPhrase>getCache(MsgPhrase.NAMECACHE); if (!cache.containsKey(_name)) { MsgPhrase.loadMsgPhrase(_name); } return cache.g...
java
@Override public Element unparseServiceCreationConfiguration(final ServiceCreationConfiguration<ClusteringService> serviceCreationConfiguration) { Element rootElement = unparseConfig(serviceCreationConfiguration); return rootElement; }
java
public void detail(MethodNode methodNode, MethodAttributes attrs, StringBuilder output) { Validate.notNull(methodNode); Validate.notNull(attrs); Validate.notNull(output); int methodId = attrs.getSignature().getMethodId(); output.append("Class Name: ").append(attrs.getSignature(...
java
@Override public Sequence<?> getBJSequence() { String seq = getSeqResSequence(); Sequence<AminoAcidCompound> s = null; try { s = new ProteinSequence(seq); } catch (CompoundNotFoundException e) { logger.error("Could not create sequence object from seqres sequence. Some unknown compound: {}",e.getMessa...
java
public Entry remove(Entry removePointer) { if (tc.isEntryEnabled()) SibTr.entry(tc, "remove", new Object[] { removePointer }); Entry removedEntry = null; //check that the entry to be removed is not null and is in this list if(contains(removePointer)) { //call the int...
java
public void writeTo(Writer writer) throws IOException { JsonSerializer.write(Json.jObject("template", asJson()), writer); writer.flush(); }
java
public static Object invokeMethod(Object object, Method method, Object... args) throws Throwable { try { return method.invoke(object, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } }
python
def parameters(self): """ Returns the list of currently set search parameters. :return: the list of AbstractSearchParameter objects :rtype: list """ array = JavaArray(javabridge.call(self.jobject, "getParameters", "()[Lweka/core/setupgenerator/AbstractParameter;")) ...
java
public static Scriptable newObject(Object fun, Context cx, Scriptable scope, Object[] args) { if (!(fun instanceof Function)) { throw notFunctionError(fun); } Function function = (Function)fun; return function.construct(cx, scope, ar...
java
public RespectBindingType<PortComponentRefType<T>> getOrCreateRespectBinding() { Node node = childNode.getOrCreate("respect-binding"); RespectBindingType<PortComponentRefType<T>> respectBinding = new RespectBindingTypeImpl<PortComponentRefType<T>>(this, "respect-binding", childNode, node); return r...
java
public static BandedSemiLocalResult alignSemiLocalLeft0(LinearGapAlignmentScoring scoring, NucleotideSequence seq1, NucleotideSequence seq2, int offset1, int length1, int offset2, int length2, int wid...
java
public static <T extends Serializable> Flowable<T> read(final File file) { return read(file, DEFAULT_BUFFER_SIZE); }
java
@SuppressWarnings("checkstyle:npathcomplexity") private void createImplicitActionReturnType(XtextResource resource, IAcceptor<? super ICodeMining> acceptor) { final List<XtendFunction> actions = EcoreUtil2.eAllOfType(resource.getContents().get(0), XtendFunction.class); for (final XtendFunction action : actions) {...
java
public MicroMetaBean getMetaBeanById(String tableName, String id) { /* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder .getDbSource(dbName);*/ JdbcTemplate jdbcTemplate = getMicroJdbcTemplate(); String sql = "select * from " + tableName + " where id=?"; logger.debug(sql); logger.debug("["+id...
python
def function_table(self, function_id=None): """Fetch and parse the function table. Returns: A dictionary that maps function IDs to information about the function. """ self._check_connected() function_table_keys = self.redis_client.keys( ra...
java
@Override public RemoteObjectInstance getRemoteObjectInstance(String appName, String moduleName, String compName, String namespaceString, String jndiName) throws NamingException, RemoteException { NamingConstants.JavaColonNamespace namespace = NamingCo...
python
def StringV(value, length=None, **kwargs): """ Create a new Concrete string (analogous to z3.StringVal()) :param value: The constant value of the concrete string :returns: The String object representing the concrete string """ if length is None: length = len(value) ...
python
def norm(A): """computes the L2-norm along axis 1 (e.g. genes or embedding dimensions) equivalent to np.linalg.norm(A, axis=1) """ return np.sqrt(A.multiply(A).sum(1).A1) if issparse(A) else np.sqrt(np.einsum('ij, ij -> i', A, A))
python
def running_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.known_statuses.RUNNING]]
python
def write(self, chunk): """WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application). """ if not self.started_response: raise AssertionError("...
python
def set_mode(self, mode, custom_mode = 0, custom_sub_mode = 0): '''set arbitrary flight mode''' mav_autopilot = self.field('HEARTBEAT', 'autopilot', None) if mav_autopilot == mavlink.MAV_AUTOPILOT_PX4: self.set_mode_px4(mode, custom_mode, custom_sub_mode) else: se...
python
def get(self, url, params=None): """ Initiate a GET request """ r = self.session.get(url, params=params) return self._response_parser(r, expect_json=False)
java
public void setDoubleValueForIn(double value, String name, Map<String, Object> map) { setValueForIn(Double.valueOf(value), name, map); }
java
public CustomFormatter create(final String pattern) { final CustomFormatTokenizer tokenizer = new CustomFormatTokenizer(); final TokenStore allStore = tokenizer.parse(pattern); if(allStore.getTokens().isEmpty()) { // 標準のフォーマッタ return CustomFormatter.DEFAULT...
java
static void mapAutomatically() { Order order = createOrder(); ModelMapper modelMapper = new ModelMapper(); OrderDTO orderDTO = modelMapper.map(order, OrderDTO.class); assertOrdersEqual(order, orderDTO); }
java
@Override public AnnotationDefinition convert(XBELExternalAnnotationDefinition t) { if (t == null) { return null; } String id = t.getId(); String url = t.getUrl(); AnnotationDefinition dest = CommonModelFactory.getInstance() .createAnnotationDefi...
python
def corethreads(self): """ Create a .cds file consisting of fasta records of CDS features for each strain """ printtime('Creating CDS files and finding core genes', self.start) # Create and start threads for i in range(self.cpus): # Send the threads to the app...
python
def _clean(self, t, capitalize=None): """Convert to normalized unicode and strip trailing full stops.""" if self._from_bibtex: t = latex_to_unicode(t, capitalize=capitalize) t = ' '.join([el.rstrip('.') if el.count('.') == 1 else el for el in t.split()]) return t
python
def order_quote(self, quote_id, extra): """Places an order using a quote :: extras = { 'hardware': {'hostname': 'test', 'domain': 'testing.com'}, 'quantity': 2 } manager = ordering.OrderingManager(env.client) result = mana...
java
protected final void addValidator(String name, String validatorId, Class<? extends TagHandler> type) { _factories.put(name, new UserValidatorHandlerFactory(validatorId, type)); }
python
def prune_directory(self): """Delete any objects that can be loaded and are expired according to the current lifetime setting. A file will be deleted if the following conditions are met: - The file extension matches :py:meth:`bucketcache.backends.Backend.file_extension` - The o...
java
public int deleteCascade(TableIndex tableIndex) throws SQLException { int count = 0; if (tableIndex != null) { // Delete Geometry Indices GeometryIndexDao geometryIndexDao = getGeometryIndexDao(); if (geometryIndexDao.isTableExists()) { DeleteBuilder<GeometryIndex, GeometryIndexKey> db = geometryInde...
java
void switchTwoRows(int rowIndex, int rowToIndex) { for (int i = 0; i < getItems().length; i++) { Object cellData = getItems()[rowToIndex][i]; getItems()[rowToIndex][i] = getItems()[rowIndex][i]; getItems()[rowIndex][i] = cellData; } }
python
def damping_maintain_sign(x, step, damping=1.0, factor=0.5): '''Famping function which will maintain the sign of the variable being manipulated. If the step puts it at the other sign, the distance between `x` and `step` will be shortened by the multiple of `factor`; i.e. if factor is `x`, the new value...
java
public void marshall(BillingRecord billingRecord, ProtocolMarshaller protocolMarshaller) { if (billingRecord == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(billingRecord.getDomainName(), DOMAINNAM...
java
public int getIndexForColor(int rgb) { int red = (rgb >> 16) & 0xff; int green = (rgb >> 8) & 0xff; int blue = rgb & 0xff; OctTreeNode node = root; for (int level = 0; level <= MAX_LEVEL; level++) { OctTreeNode child; int bit = 0x80 >> level; int index = 0; if ((red & bit) != 0) index += 4;...
java
private static ProteinSequence getProteinSequence(String str) { try { ProteinSequence s = new ProteinSequence(str); return s; } catch (CompoundNotFoundException e) { logger.error("Unexpected error when creating ProteinSequence",e); } return null; }
python
def write(self, outfile, rows): """ Write a PNG image to the output file. `rows` should be an iterable that yields each row (each row is a sequence of values). The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.wid...
python
def open(self, file, mode='r', perm=0o0644): """ Opens a file on the node :param file: file path to open :param mode: open mode :param perm: file permission in octet form mode: 'r' read only 'w' write only (truncate) '+' read/write ...
python
def _hexencode(bytestring, insert_spaces = False): """Convert a byte string to a hex encoded string. For example 'J' will return '4A', and ``'\\x04'`` will return '04'. Args: bytestring (str): Can be for example ``'A\\x01B\\x45'``. insert_spaces (bool): Insert space characters between pair...
python
def list(self): """List Reserved Capacities""" mask = """mask[availableInstanceCount, occupiedInstanceCount, instances[id, billingItem[description, hourlyRecurringFee]], instanceCount, backendRouter[datacenter]]""" results = self.client.call('Account', 'getReservedCapacityGroups', mask=mask) ...
python
def write_ast(patched_ast_node): """Extract source form a patched AST node with `sorted_children` field If the node is patched with sorted_children turned off you can use `node_region` function for obtaining code using module source code. """ result = [] for child in patched_ast_node.sorted_chi...
java
private static GMetricType getType(final Object obj) { // FIXME This is far from covering all cases. // FIXME Wasteful use of high capacity types (eg Short => INT32) // Direct mapping when possible if (obj instanceof Long || obj instanceof Integer || obj instanceof Byte || obj instanceof Short) return GMet...
python
def _print_map_dict(self, argkey, filename, append): """Prints a dictionary that has variable => value mappings.""" result = [] skeys = list(sorted(self.curargs[argkey].keys())) for key in skeys: result.append("'{}' => {}".format(key, self.curargs[argkey][key])) self....
python
def _pop(line, key, use_rest): ''' Helper for the line parser. If key is a prefix of line, will remove ir from the line and will extract the value (space separation), and the rest of the line. If use_rest is True, the value will be the rest of the line. Return a tuple with the value and the r...
python
def make_logger(name, stream_type, jobs): """Create a logger component. :param name: name of logger child, i.e. logger will be named `noodles.<name>`. :type name: str :param stream_type: type of the stream that this logger will be inserted into, should be |pull_map| or |push_map|. :...
java
public static SourceLineAnnotation createUnknown(@DottedClassName String className, String sourceFile) { return createUnknown(className, sourceFile, -1, -1); }
java
private static void listHierarchy(Task task, String indent) { for (Task child : task.getChildTasks()) { System.out.println(indent + "Task: " + child.getName() + "\t" + child.getStart() + "\t" + child.getFinish()); listHierarchy(child, indent + " "); } }
python
def restore_artifact(src_path: str, artifact_hash: str, conf: Config): """Restore the artifact whose hash is `artifact_hash` to `src_path`. Return True if cached artifact is found, valid, and restored successfully. Otherwise return False. """ cache_dir = conf.get_artifacts_cache_dir() if not is...
java
public void process(Class<?> clazz, Object testInstance) { processIndependentAnnotations(testInstance.getClass(), testInstance); injectMocks(testInstance); }
python
def exists(self): """ Check whether the directory exists on the camera. """ if self.name in ("", "/") and self.parent is None: return True else: return self in self.parent.directories
java
public void initValues( int mtLv, String superiorModuleCode, PrintStream out, PrintStream err ) { // mtLv ++; // moduleCode = superiorModuleCode + "." + baseModuleCode; // this.out = out; this.err = err; // }
python
def open(self): ''' Open the channel for communication. ''' args = Writer() args.write_shortstr('') self.send_frame(MethodFrame(self.channel_id, 20, 10, args)) self.channel.add_synchronous_cb(self._recv_open_ok)
python
def leftcontext(self, size, placeholder=None, scope=None): """Returns the left context for an element, as a list. This method crosses sentence/paragraph boundaries by default, which can be restricted by setting scope""" if size == 0: return [] #for efficiency context = [] e = self ...
java
public final void setRecurrenceRule(String rec) { if (recurrenceRule == null && rec == null) { // no unnecessary property creation if everything is null return; } recurrenceRuleProperty().set(rec); }
java
public BinaryOWLMetadata createCopy() { BinaryOWLMetadata copy = new BinaryOWLMetadata(); copy.stringAttributes.putAll(stringAttributes); copy.intAttributes.putAll(intAttributes); copy.longAttributes.putAll(longAttributes); copy.doubleAttributes.putAll(doubleAttributes); ...
java
public InputStream getInputStream() { try { int responseCode = this.urlConnection.getResponseCode(); try { // HACK: manually follow redirects, for the login to work // HTTPUrlConnection auto redirect doesn't respect the provided header...
python
def loop(bot, config, interval, settings): """Schedule a BOT (by label) to run on an interval, e.g. 'MyBot -i 60'""" print_options(bot, config, settings) click.echo(f'- Interval: {interval}s') click.echo() bot_task = BotTask(bot, config) bot_task.run_loop(interval)
python
def memberships(self, group, include=None): """ Return the GroupMemberships for this group. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param group: Group object or id """ ...
java
@Override public void debug(String message) { if(this.logger.isDebugEnabled()) { this.logger.debug(buildMessage(message)); } }
python
def get_throttled_by_provisioned_write_event_percent( table_name, gsi_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled write events during a given time frame :type table_name: str :param table_name: Name of the DynamoDB table :type gsi_name: str :param...
java
@Override public String toReplacerPattern(boolean escapeUnprintable) { StringBuilder rule = new StringBuilder("&"); rule.append(translit.getID()); rule.append("( "); rule.append(replacer.toReplacerPattern(escapeUnprintable)); rule.append(" )"); return rule.toString();...
java
public static Object issueRequest( MessageProcessor MP, ControlMessage msg, SIBUuid8 remoteUuid, long retry, int tries, long requestID) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "issueRequest", new Object[] {MP, msg, remoteUuid, new...
python
def _get_completions(self): """Return a list of possible completions for the string ending at the point. Also set begidx and endidx in the process.""" completions = [] self.begidx = self.l_buffer.point self.endidx = self.l_buffer.point buf=self.l_buffer.line_buffer ...
java
public char getPositionKey() { String value = Optional.fromNullable(getParameter(SignalParameters.POSITION_KEY.symbol())).or(""); return value.isEmpty() ? ' ' : value.charAt(0); }
java
public final boolean start() { if (running || booting || stopping || terminated) { // do nothing if this instance is not stopped return false; } else { // mark this instance started booting = true; running = true; onStarted(); ...
python
def args_update(self): """Update the argparser namespace with any data from configuration file.""" for key, value in self._config_data.items(): setattr(self._default_args, key, value)
python
def add_files(self, common_name, x509s, files=None, parent_ca='', is_ca=False, signees=None, serial=0, overwrite=False): """Add a set files comprising a certificate to Certipy Used with all the defaults, Certipy will manage creation of file paths to be used to store these file...
java
public final CartLn makeTxdLine(final List<CartLn> pTxdLns, final Long pTdlId, final Long pCatId, final Tax pTax, final Double pPercent, final AccSettings pAs) { CartLn txdLn = null; for (CartLn tdl : pTxdLns) { if (tdl.getItsId().equals(pTdlId)) { txdLn = tdl; } } if (txd...
python
def push_all(collector, **kwargs): """Push all the images""" configuration = collector.configuration configuration["harpoon"].do_push = True configuration["harpoon"].only_pushable = True make_all(collector, **kwargs)
python
def find_genus(files, database, threads=12): """ Uses MASH to find the genus of fasta files. :param files: File dictionary returned by filer method. :param database: Path to reduced refseq database sketch. :param threads: Number of threads to run mash with. :return: genus_dict: Dictionary of gen...
java
@SuppressWarnings("unchecked") protected void processInitialWsLogHandlerServices() throws InvalidSyntaxException { ServiceReference<WsLogHandler>[] servRefs = (ServiceReference<WsLogHandler>[]) bundleContext.getServiceReferences(WsLogHandler.class.getName(), null); if (servR...
python
def media(soup): """ All media tags and some associated data about the related component doi and the parent of that doi (not always present) """ media = [] media_tags = raw_parser.media(soup) position = 1 for tag in media_tags: media_item = {} copy_attribute(tag.attrs...
java
public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case KEY: return isSetKey(); case COLUMN_PARENT: return isSetColumn_parent(); case COLUMN_SLICES: return isSetColumn_slices(); case REVERSED: ret...
python
def _bowtie_major_version(stdout): """ bowtie --version returns strings like this: bowtie version 0.12.7 32-bit Built on Franklin.local Tue Sep 7 14:25:02 PDT 2010 """ version_line = stdout.split("\n")[0] version_string = version_line.strip().split()[2] major_version = int(versi...
python
def encode(self, envelope, session, **kwargs): """ :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation. :param envelope: original envelope :param session: original session :param kwargs: additional arguments :return: WMessengerBytesEnvelope """ return WMessengerBytesEnvelope(b64encode(e...
java
private List<SequenceState<S, O, D>> retrieveMostLikelySequence() { // Otherwise an HMM break would have occurred and message would be null. assert !message.isEmpty(); final S lastState = mostLikelyState(); // Retrieve most likely state sequence in reverse order final List<Sequ...
java
@EventListener(classes = TargetDeletedEvent.class) protected void targetDelete(final TargetDeletedEvent deleteEvent) { if (isNotFromSelf(deleteEvent)) { return; } sendDeleteMessage(deleteEvent.getTenant(), deleteEvent.getControllerId(), deleteEvent.getTargetAddress()); }
java
public static <T> Collector<T, ?, List<T>> tail(int n) { if (n <= 0) return empty(); return Collector.<T, Deque<T>, List<T>> of(ArrayDeque::new, (acc, t) -> { if (acc.size() == n) acc.pollFirst(); acc.addLast(t); }, (acc1, acc2) -> { ...
python
def relativeAreaSTE(self): ''' return STE area - relative to image area ''' s = self.noSTE.shape return np.sum(self.mask_STE) / (s[0] * s[1])
java
public Map<String, CmsJspImageBean> getScaleWidth() { if (m_scaleWidth == null) { m_scaleWidth = CmsCollectionsGenericWrapper.createLazyMap(new CmsScaleWidthTransformer()); } return m_scaleWidth; }
java
protected void connectLeftRight(GrayS32 input, GrayS32 output) { for( int y = 0; y < input.height; y++ ) { int x = input.width-1; int inputLabel = input.unsafe_get(x, y); int outputLabel = output.unsafe_get(x, y); if( outputLabel == -1 ) { // see if it needs to create a new output segment outputLabe...
python
def get_xml_parser(encoding=None): """Returns an ``etree.ETCompatXMLParser`` instance.""" parser = etree.ETCompatXMLParser( huge_tree=True, remove_comments=True, strip_cdata=False, remove_blank_text=True, resolve_entities=False, encoding=encoding ) return...
java
public static void depthTo3D(CameraPinholeBrown param , GrayU16 depth , FastQueue<Point3D_F64> cloud ) { cloud.reset(); Point2Transform2_F64 p2n = LensDistortionFactory.narrow(param).undistort_F64(true,false); Point2D_F64 n = new Point2D_F64(); for( int y = 0; y < depth.height; y++ ) { int index = depth.s...
python
def getbalance(self, user_id="", as_decimal=True): """Calculate the total balance in all addresses belonging to this user. Args: user_id (str): this user's unique identifier as_decimal (bool): balance is returned as a Decimal if True (default) or a strin...
java
@Override protected void initView() { super.initView(); this.box = new VBox(); this.box.setAlignment(Pos.CENTER); final ScrollPane scrollPane = new ScrollPane(); scrollPane.setPrefSize(600, 600); scrollPane.setContent(this.box); node().setCenter(scrollPane)...
java
public PagedList<DenyAssignmentInner> listForResource(final String resourceGroupName, final String resourceProviderNamespace, final String parentResourcePath, final String resourceType, final String resourceName) { ServiceResponse<Page<DenyAssignmentInner>> response = listForResourceSinglePageAsync(resourceGrou...