language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public java.util.concurrent.Future<CreateStreamResult> createStreamAsync(String streamName, Integer shardCount) { return createStreamAsync(new CreateStreamRequest().withStreamName(streamName).withShardCount(shardCount)); }
java
public static void unregister(String ID) { displayNameCache.remove(new CaseInsensitiveString(ID)); registry.remove(ID); }
python
def _find_title(html_file): """Finds the <title> for the given HTML file, or (Unknown).""" # TODO Is it necessary to read files like this? with html_file.open() as f: for line in f: if '<title>' in line: # + 7 to skip len('<title>') return line[line.index(...
java
protected List<MavenArtifact> fetchMavenArtifacts(Dependency dependency) throws IOException { IOException lastException = null; long sleepingTimeBetweenRetriesInMillis = BASE_RETRY_WAIT; int triesLeft = numberOfRetries; while (triesLeft-- > 0) { try { return s...
java
private static long parseDuration(String value) throws ParseException { // Must ended with "s". if (value.isEmpty() || value.charAt(value.length() - 1) != 's') { throw new ParseException("Invalid duration string: " + value, 0); } boolean negative = false; if (value.charAt(0) == '-') { ne...
java
public void setIntProperty( String key , int value ) { settings.setProperty(key, String.valueOf(value)); }
python
def add_tasks(self, pcs_files, dirname=''): '''建立批量下载任务, 包括目录''' def on_list_dir(info, error=None): path, pcs_files = info if error or not pcs_files: dialog = Gtk.MessageDialog(self.app.window, Gtk.DialogFlags.MODAL, ...
java
@Nonnull public static byte[] encode( final long maxInactiveInterval, final long lastAccessedTime, final long thisAccessedTime ) { int idx = 0; final byte[] data = new byte[ 4 + 2 * 8 ]; encodeNum( maxInactiveInterval, data, idx, 4 ); encodeNum( lastAccessedTime, data, idx += 4, 8 );...
python
def GetMessage(self, log_source, lcid, message_identifier): """Retrieves a specific message for a specific Event Log source. Args: log_source (str): Event Log source. lcid (int): language code identifier (LCID). message_identifier (int): message identifier. Returns: str: message st...
python
def load(self, ): """If the reference is in the scene but unloaded, load it. .. Note:: Do not confuse this with reference or import. Load means that it is already referenced. But the data from the reference was not read until now. Load loads the data from the reference. This ...
java
@SuppressWarnings("unchecked") @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LOG.info("POST from address: " + req.getRemoteAddr() + " Values trying to set: " + mapToString(req.getParameterMap())); PrintWriter out = resp....
java
public synchronized void stop(boolean graceful) throws InterruptedException { boolean ov=_gracefulStop; try { _gracefulStop=graceful; stop(); } finally { _gracefulStop=ov; } }
python
def base_path(self): """Base absolute path of container.""" return os.path.join(self.container.base_path, self.name)
java
private boolean detectLogFromBugsnag(Throwable throwable) { // Check all places that LOGGER is called with an exception in the Bugsnag library for (StackTraceElement element : throwable.getStackTrace()) { for (String excludedClass : EXCLUDED_CLASSES) { if (element.getClassNam...
java
protected void configureWebApp () throws Exception { //finally, finish configuring the webapp for (int i=0;i<_configurations.length;i++) { _configurations[i].setWebApplicationContext(this); _configurations[i].configureWebApp(); } }
java
private static String createNewKey(final List<String> _names, final Class<?> _bundleclass) throws EFapsException { final StringBuilder builder = new StringBuilder(); final List<String> oids = new ArrayList<>(); String ret = null; try { ...
python
def dim_extents(self, *args, **kwargs): """ Returns extent tuples of the dimensions in args. .. code-block:: python (tl, tu), (bl, bu) = cube.dim_extents('ntime', 'nbl') or .. code-block:: python (tl, tu), (bl, bu) = cube.dim_upper_extent('ntime,nbl')...
java
public static <T, B extends ThreadLocalBuilder<T>> T build( final Class<B> threadLocalBuilderClass, final Consumer<B> builderConsumer) { return buildGeneric(threadLocalBuilderClass, builderConsumer); }
python
def weibull(target, seeds, shape, scale, loc): r""" Produces values from a Weibull distribution given a set of random numbers. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also pro...
java
public Observable<Page<AvailabilitySetInner>> listByResourceGroupAsync(String resourceGroupName) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName).map(new Func1<ServiceResponse<List<AvailabilitySetInner>>, Page<AvailabilitySetInner>>() { @Override public Page<Availa...
java
public void register(DescribeService service, String describeService) throws POIProxyException { serviceManager.registerServiceConfiguration(service.getId(), describeService, service); }
java
public boolean containsKey(Object key) { if (key == null) { return false; } Entry tab[] = mTable; int hash = System.identityHashCode(key); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; e = e.mNext) { ...
java
@Override public IClasspathEntry[] getClasspathEntries() { // TODO Auto-generated method stub List<IClasspathEntry> libraries = Activator.getDefault().libraries(); return libraries.toArray(new IClasspathEntry[libraries.size()]); }
python
def to_array(self): """ Serializes this SuccessfulPayment to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(SuccessfulPayment, self).to_array() array['currency'] = u(self.currency) # py2: type unicode, py3: type s...
java
public SDVariable layerNorm(SDVariable input, SDVariable gain, int... dimensions) { return layerNorm((String)null, input, gain, dimensions); }
python
def _write_reads(reads, prefix): """ Write fasta file, ma file and real position """ out_ma = prefix + ".ma" out_fasta = prefix + ".fasta" out_real = prefix + ".txt" with open(out_ma, 'w') as ma_handle: print("id\tseq\tsample", file=ma_handle, end="") with open(out_fasta, 'w'...
java
public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es = entrySet; return es != null ? es : (entrySet = new EntrySet()); }
java
protected boolean startAuthentication(final C context, final List<Client> currentClients) { return isNotEmpty(currentClients) && currentClients.get(0) instanceof IndirectClient; }
java
@Override public List<SAXParseException> validateWithErrors(final File f) throws SAXException, IOException { final Validator errorValidator = createNewErrorValidator(); errorValidator.validate(utf8SourceForFile(f), null); return ((Handler) errorValidator.getErrorHandler()).excep...
java
public static String methodToEventName(ExecutableElement method) { Emit emitAnnotation = method.getAnnotation(Emit.class); if (!"".equals(emitAnnotation.value())) { return emitAnnotation.value(); } return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getSimpleName().toString()) ...
java
public static String replaceVariables( final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose ) { final char[] open = pOpen.toCharArray(); final char[] close = pClose.toCharArray(); final StringBuilder out = new StringBuilder(); StringBuilder...
java
synchronized long getNextIndex(String server) { checkState(role == Role.LEADER, "role:%s", role); checkState(self.equals(leader), "self:%s leader:%s", self, leader); checkState(serverData.containsKey(server), "server:%s", server); return serverData.get(server).nextIndex; }
java
public EList<Byte> getValues() { if (values == null) { values = new EDataTypeEList<Byte>(Byte.class, this, TypesPackage.JVM_BYTE_ANNOTATION_VALUE__VALUES); } return values; }
java
public BoxLegalHoldAssignment.Info assignTo(BoxResource resource) { return BoxLegalHoldAssignment.create( this.getAPI(), this.getID(), BoxResource.getResourceType(resource.getClass()), resource.getID()); }
python
def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without...
python
def insert_arguments_into_sql_query(compilation_result, arguments): """Insert the arguments into the compiled SQL query to form a complete query. Args: compilation_result: CompilationResult, compilation result from the GraphQL compiler. arguments: Dict[str, Any], parameter name -> value, for ev...
java
public Set<Entry<K, T, V>> entrySet() { Set<Entry<K, T, V>> ret = new HashSet<>(); for (Pair<K, T> pair : backedMap.keySet()) { ret.add(new Entry<>(pair.getFirst(), pair.getSecond(), backedMap.get(pair))); } return ret; }
java
private void failTask(Throwable cause) { TaskStatus taskStatus = getTaskStatus(); if (!taskStatus.getState().isDone()) { log.debug(cause, "Remote task %s failed with %s", taskStatus.getSelf(), cause); } abort(failWith(getTaskStatus(), FAILED, ImmutableList.of(toFailure(c...
java
@Benchmark @OperationsPerInvocation(20) public void benchmarkByteBuddyWithPrefix(Blackhole blackHole) { blackHole.consume(byteBuddyWithPrefixInstance.method(booleanValue)); blackHole.consume(byteBuddyWithPrefixInstance.method(byteValue)); blackHole.consume(byteBuddyWithPrefixInstance.met...
java
public static StringIsLessThanOrEqual isLessThanOrEqual(StringExpression left, Object constant) { if (!(constant instanceof String)) throw new IllegalArgumentException("constant is not a String"); return new StringIsLessThanOrEqual(left, constant((String)constant)); }
python
def calculate_totals( self, children, local_children=None ): """Calculate our cumulative totals from children and/or local children""" for field,local_field in (('recursive','calls'),('cumulative','local')): values = [] for child in children: if isinstance( child,...
java
public static FloatBuffer allocate (int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } ByteBuffer bb = ByteBuffer.allocateDirect(capacity * 4); bb.order(ByteOrder.nativeOrder()); return bb.asFloatBuffer(); }
java
void index(BioPAXElement bpe, IndexWriter indexWriter) { // create a new document final Document doc = new Document(); // save URI (not indexed field) Field field = new StoredField(FIELD_URI, bpe.getUri()); doc.add(field); // index and store but not analyze/tokenize the biopax class name: field = ...
python
def group_shelf_fqfn(self): """Return groups shelf fully qualified filename. For testing/debugging a previous shelf file can be copied into the tc_temp_path directory instead of creating a new shelf file. """ if self._group_shelf_fqfn is None: # new shelf file ...
python
def bottom(self): """Bottom coordinate.""" if self._has_real(): return self._data.real_bottom return self._data.bottom
python
def save_storage(self, instance, schema): """Save basic:json values to a Storage collection.""" for field_schema, fields in iterate_fields(instance, schema): name = field_schema['name'] value = fields[name] if field_schema.get('type', '').startswith('basic:json:'): ...
java
@Override public SqlContext param(final String parameterName, final Object value, final int sqlType) { if (value instanceof Optional) { Optional<?> optionalValue = (Optional<?>) value; if (optionalValue.isPresent()) { param(new Parameter(parameterName, optionalValue.get(), sqlType)); } else { param(...
python
def _repopulate_pool(self): """ Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ for i in range(self._processes - len(self._pool)): w = self.Process(target=worker, args=(se...
java
public @CheckForNull Computer toComputer() { Jenkins j = Jenkins.getInstanceOrNull(); if (j != null) { for (Computer c : j.getComputers()) { if (getChannel()==c.getChannel()) { return c; } } } return null; }
java
public void releaseExceptionally(Throwable e) { ArrayList<CompletableFuture<T>> toComplete = null; synchronized (lock) { if (!waitingFutures.isEmpty()) { toComplete = new ArrayList<>(waitingFutures); waitingFutures.clear(); } this.e = e...
python
def get_singular_and_plural_dtype(self, dtype): """ Parameters ---------- dtype : str MagIC table type (specimens, samples, contribution, etc.) Returns --------- name : str singular name for MagIC table ('specimen' for specimens table, etc....
python
def color(self): """Line color in IDA View""" color = idc.GetColor(self.ea, idc.CIC_ITEM) if color == 0xFFFFFFFF: return None return color
python
def npci_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" if _debug: NPCI._debug("npci_contents use_dict=%r as_class=%r", use_dict, as_class) # make/extend the dictionary of content if use_dict is None: if _debug: NPCI._debug(" ...
python
def convert_to_mb(s): """Convert memory size from GB to MB.""" s = s.upper() try: if s.endswith('G'): return float(s[:-1].strip()) * 1024 elif s.endswith('T'): return float(s[:-1].strip()) * 1024 * 1024 else: return float(s[:-1].strip()) except...
python
def get_self_url_host(request_data): """ Returns the protocol + the current host + the port (if different than common ports). :param request_data: The request as a dict :type: dict :return: Url :rtype: string """ current_host = OneLogin_Saml2_Uti...
java
private void sortPoints() { final ControlPoint firstPt = (ControlPoint)list.get(0); final ControlPoint lastPt = (ControlPoint)list.get(list.size()-1); Comparator compare = new Comparator() { public int compare(Object first, Object second) { if (first == firstPt) { return -1; } if (sec...
java
public Collection<Defect> defects(DefectFilter filter) { return get(Defect.class, (filter != null) ? filter : new DefectFilter()); }
python
def is_exponent_push_token(cls, token): """Returns `True` if the token is an Exponent push token""" import six return ( isinstance(token, six.string_types) and token.startswith('ExponentPushToken'))
java
public UnusedStubbings getUnusedStubbings(Iterable<Object> mocks) { Set<Stubbing> stubbings = AllInvocationsFinder.findStubbings(mocks); List<Stubbing> unused = filter(stubbings, new Filter<Stubbing>() { public boolean isOut(Stubbing s) { return !UnusedStubbingReporting.shou...
python
def get_installed_classes(cls): """ Iterates over installed plugins associated with the `entry_point` and returns a dictionary of viable ones keyed off of their names. A viable installed plugin is one that is both loadable *and* a subclass of the Pluggable subclass in question. ...
java
private void setTree(ComponentTree tree) { synchronized (this) { this.tree = tree; for (ComponentVertex child : children) { child.setTree(tree); } } }
java
private String[] requiredLibraries() { List<String> libraries = new ArrayList<String>(Arrays.asList( "org.dbunit", "org.apache.commons", "org.apache.log4j", "org.slf4j", "org.yaml", "org.codehaus.jackson" )); if (!dbunitCon...
python
def append(self, message_level, message_text): """ Adds a message level/text pair to this MessagesHeader """ if not message_level in MessagesHeader._message_levels: raise ValueError('message_level="%s"' % message_level) self._messages.append((message_level, message_text))
python
def mean(name, add, match): ''' Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field ...
python
def _on_del_route(self, msg): """ Stub :data:`DEL_ROUTE` handler; fires 'disconnect' events on the corresponding :attr:`_context_by_id` member. This is replaced by :class:`mitogen.parent.RouteMonitor` in an upgraded context. """ LOG.error('%r._on_del_route() %r', self, ms...
java
public static void addValuesEqualCall(final CodeBuilder b, final TypeDesc valueType, final boolean testForNull, final Label label, final boolean cho...
python
def get_files_by_layer(self, layer_name, file_pattern='*'): """ returns a list of all files with the given filename pattern in the given PCC annotation layer """ layer_path = os.path.join(self.path, layer_name) return list(dg.find_files(layer_path, file_pattern))
python
def monitor(self, job_id, timeout=5): """ Monitor the status of a job. ## Arguments * `job_id` (int): The job to check. * `timeout` (float): The time to wait between checks (in sec). ## Returns * `code` (int): The status. * `status` (str): The human-re...
java
public ResponseBuilder deleteResource(final Resource res) { final String baseUrl = getBaseUrl(); final String identifier = baseUrl + req.getPartition() + req.getPath(); final Session session = ofNullable(req.getSession()).orElseGet(HttpSession::new); // Check if this is already deleted...
python
def separation_in_list(separation_indices, separation_indices_list): """ Checks if the separation indices of a plane are already in the list :param separation_indices: list of separation indices (three arrays of integers) :param separation_indices_list: list of the list of separation indices to be compa...
java
private List<Integer> collapseGT(List<String> gtsStr) { if (gtsStr.isEmpty()) { return Collections.emptyList(); } if (gtsStr.size() == 1) { return Collections.singletonList(0); } List<Genotype> gts = gtsStr.stream().map(Genotype::new).collect(Collectors.t...
java
private static void tryForceNotJava1() { String version = System.getProperty("java.version"); // N.B. Log4j has issues with JVM versions written like "9" and "10" if (version != null && !version.startsWith("1.")) { try { Class<Loader> loader = Loader.class; for (Field field : loader.getDeclared...
java
public static int decodeLinear( byte[] data, int dataSize, double[] result ) { int ri = 2; long[] ints = new long[3]; long extrapol; long y; IntDecoder dec = new IntDecoder(data, 16); if (dataSize < 8) { return -1; } double fixedPoint = decodeFixe...
java
protected boolean register(IEventListener listener) { log.debug("register - listener: {}", listener); boolean registered = listeners.add(listener); if (registered) { listenerStats.increment(); // prepare response for new client ownerMessage.addEvent(Type...
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, EntityType instance) throws SerializationException { serialize(streamWriter, instance); }
python
def _humanize_bytes(num_bytes, precision=1): """ Return a humanized string representation of a number of num_bytes. from: http://code.activestate.com/recipes/ 577081-humanized-representation-of-a-number-of-num_bytes/ Assumes `from __future__ import division`. >>> humanize_bytes(1) ...
java
@SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TypesPackage.JVM_CUSTOM_ANNOTATION_VALUE__VALUES: getValues().clear(); getValues().addAll((Collection<? extends EObject>)newValue); return; } super.eSet(featureID, newValue); ...
java
public T validator(MessageValidator<? extends ValidationContext> ... validators) { Stream.of(validators).forEach(getAction()::addValidator); return self; }
java
public void setCapacity(String queue,float capacity) { rmConf.setFloat(toFullPropertyName(queue, CAPACITY_PROPERTY),capacity); }
python
def write_multiple_files(args, base_dir, crawler): """Write to multiple output files and/or subdirectories.""" for i, query in enumerate(args['query']): if query in args['files']: # Write files if args['out'] and i < len(args['out']): outfilename = args['out'][i] ...
java
public OpenPgpMetadata addOxMessage(Message message, Set<OpenPgpContact> contacts, List<ExtensionElement> payload) throws SmackException.NotLoggedInException, IOException, PGPException { HashSet<OpenPgpContact> recipients = new HashSet<>(contacts); OpenPgpContact self = openPgpManager.getOp...
python
def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ source = None if loader is not None and ...
java
private static boolean mergeAllowed(Element child, IAuthorizationPrincipal ap) throws AuthorizationException { if (!child.getTagName().equals("channel")) return true; String channelPublishId = child.getAttribute("chanID"); return ap.canRender(channelPublishId); }
python
def search_index_path(self, index=None, **options): """ Builds a Yokozuna search index URL. :param index: optional name of a yz index :type index: string :param options: optional list of additional arguments :type index: dict :rtype URL string """ ...
java
private int importTables(Referenceable databaseReferenceable, String databaseName, final boolean failOnError) throws Exception { int tablesImported = 0; List<String> hiveTables = hiveClient.getAllTables(databaseName); LOG.info("Importing tables {} for db {}", hiveTables.toString(), databaseName)...
python
def _set_pyqtgraph_title(layout): """ Private function to add a title to the first row of the window. Returns True if a Title is set. Else, returns False. """ if 'title_size' in pytplot.tplot_opt_glob: size = pytplot.tplot_opt_glob['title_size'] if 'title_text' in pytplot.tplot_opt_glob...
python
def add_entry_points(self, names): """ adds `names` to the internal collection of entry points to track `names` can be a single object or an iterable but must be a string or iterable of strings. """ names = util.return_set(names) self.entry_point_names.update(nam...
java
public JSONObject elementOpt( String key, Object value ) { return elementOpt( key, value, new JsonConfig() ); }
python
def _wrap_result(self, result, block=None, obj=None): """ Wrap a single result. """ if obj is None: obj = self._selected_obj index = obj.index if isinstance(result, np.ndarray): # coerce if necessary if block is not None: ...
java
public static <T> Collector<T, ?, List<T>> maxAll(Comparator<? super T> comparator) { return maxAll(comparator, Collectors.toList()); }
java
public static int decoratorNames(int ecflags, byte[][] decorators) { switch (ecflags & NEWLINE_DECORATOR_MASK) { case UNIVERSAL_NEWLINE_DECORATOR: case CRLF_NEWLINE_DECORATOR: case CR_NEWLINE_DECORATOR: case 0: break; default: return -1; } ...
java
public static CommerceDiscount fetchByLtD_S_First(Date displayDate, int status, OrderByComparator<CommerceDiscount> orderByComparator) { return getPersistence() .fetchByLtD_S_First(displayDate, status, orderByComparator); }
python
def create_vpn_connection(self, type, customer_gateway_id, vpn_gateway_id): """ Create a new VPN Connection. :type type: str :param type: The type of VPN Connection. Currently only 'ipsec.1' is supported :type customer_gateway_id: str :param custom...
java
public static Queue asRef( Queue queue ) throws JMSException { if (queue == null) return null; if (queue instanceof QueueRef) return queue; return new QueueRef(queue.getQueueName()); }
java
@Override public URL getResource( String path ) { URL url = null; if ( baseLoader != null ) // classloader wants no leading slash url = baseLoader.getResource( path.substring(1) ); if ( url == null ) url = super.getResource( path ); return url;...
java
public boolean existsCollection(String collectionName) throws SolrException { try { List<String> collections = CollectionAdminRequest.listCollections(solrClient); for (String collection : collections) { if (collection.equals(collectionName)) { return t...
java
@Deprecated public void login(String username, String password) throws LoginFailedException { try { String token = fetchToken("login"); try { this.confirmLogin(token, username, password); } catch (NeedLoginTokenException e) { // try once more token = fetchToken("login"); this.confirmLogin(tok...
python
def save(self, filename, binary=True): """ Writes a structured grid to disk. Parameters ---------- filename : str Filename of grid to be written. The file extension will select the type of writer to use. ".vtk" will use the legacy writer, while ...
java
public static void touchLdpMembershipResource(final Node node, final Calendar date, final String user) { getContainingNode(node).filter(uncheck(parent -> parent.hasProperty(LDP_MEMBER_RESOURCE))).ifPresent(parent -> { try { final Optional<String> hasInsertedContentProperty = ldpInser...
java
@Override @Transactional(enabled = false) public CommerceAccount createCommerceAccount(long commerceAccountId) { return commerceAccountPersistence.create(commerceAccountId); }