language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected static FileSizeFilter create(RelationalOperator<Long> operator) { return new FileSizeFilter() { @Override @NullSafe public boolean accept(File file) { return (file != null && operator.evaluate(file.length())); } }; }
java
public final Response setStatusLine(final String statusLine) { this.statusLine = statusLine; final String[] statusPieces = statusLine.split(" "); if (statusPieces.length > 1) { responseCode = Integer.parseInt(statusPieces[1]); } return this; }
python
def add_inote(self, msg, idx, off=None): """ Add a message to a specific instruction by using (default) the index of the address if specified :param msg: the message :type msg: string :param idx: index of the instruction (the position in the list of the instruction) :typ...
java
public T End() { if (procceed) if (initVal != null && !initVal.equals(false)) { return body.apply(initVal); } else { return null; } else ...
python
def _interpolate(im, x, y, name): """Perform bilinear sampling on im given x,y coordiantes. Implements the differentiable sampling mechanism with bilinear kerenl in https://arxiv.org/abs/1506.02025. Modified from https://github.com/tensorflow/models/tree/master/transformer x,y are tensors specifying normal...
python
def update(self, period = None, start = None, stop = None, value = None): """Change the value for a given period. :param period: Period where the value is modified. If set, `start` and `stop` should be `None`. :param start: Start of the period. Instance of `openfisca_core.periods.Instant`. If s...
python
def init_instance(self, key): """ Create an empty instance if it doesn't exist. If the instance already exists, this is a noop. """ with self._lock: if key not in self._metadata: self._metadata[key] = {} self._metric_ids[key] = []
python
def get_labels_encoder(self, data_dir): """Builds encoder for the given class labels. Args: data_dir: data directory Returns: An encoder for class labels. """ label_filepath = os.path.join(data_dir, self.vocab_filename) return text_encoder.TokenTextEncoder(label_filepath)
java
public static <T> ArrayConstructorExpression<T> array(Class<T[]> type, Expression<T>... exprs) { return new ArrayConstructorExpression<T>(type, exprs); }
python
def firmware_download_output_fwdl_cmd_msg(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware_download = ET.Element("firmware_download") config = firmware_download output = ET.SubElement(firmware_download, "output") fwdl_cmd_msg = ET...
java
@Override public DeleteConfigurationSetEventDestinationResult deleteConfigurationSetEventDestination(DeleteConfigurationSetEventDestinationRequest request) { request = beforeClientExecution(request); return executeDeleteConfigurationSetEventDestination(request); }
python
def render(self, ctx=None): ''' Render the current value into a :class:`bitstring.Bits` object :rtype: :class:`bitstring.Bits` :return: the rendered field ''' self._initialize() if ctx is None: ctx = RenderContext() # # if we are calle...
python
def set_backend(backend_name: str): """Sets backend (local or aws)""" global _backend, _backend_name _backend_name = backend_name assert not ncluster_globals.task_launched, "Not allowed to change backend after launching a task (this pattern is error-prone)" if backend_name == 'aws': _backend = aws_backen...
python
def delete(cls, bucket_id): """Delete a bucket. Does not actually delete the Bucket, just marks it as deleted. """ bucket = cls.get(bucket_id) if not bucket or bucket.deleted: return False bucket.deleted = True return True
python
def update_access_key_full(self, access_key_id, name, is_active, permitted, options): """ Replaces the 'name', 'is_active', 'permitted', and 'options' values of a given key. A master key must be set first. :param access_key_id: the 'key' value of the access key for which the values will...
python
def put(self, name, values, request=None, timeout=5.0, throw=True, process=None, wait=None, get=True): """Write a new value of some number of PVs. :param name: A single name string or list of name strings :param values: A single value, a list of values, a dict, a `Value`. May be mo...
python
def scale_library_content(library_state_m, gaphas_editor=True): """Scales the meta data of the content of a LibraryState The contents of the `LibraryStateModel` `library_state_m` (i.e., the `state_copy` and all it children/state elements) to fit the current size of the `LibraryStateModel`. :p...
java
public synchronized static HealthCheckRegistry setDefault(String name) { final HealthCheckRegistry registry = getOrCreate(name); return setDefault(name, registry); }
java
void backupFile() { writeLock.lock(); try { if (incBackup) { if (fa.isStreamElement(backupFileName)) { fa.removeElement(backupFileName); } return; } if (fa.isStreamElement(fileName)) { ...
python
def nearestPoint(self, pos): """ Returns the nearest graphing point for this item based on the inputed graph position. :param pos | <QPoint> :return (<variant> x, <variant> y) """ # lookup subpaths for x, y, path in sel...
python
def _parse_template(self, has_content): """Parse a template at the head of the wikicode string.""" reset = self._head context = contexts.TEMPLATE_NAME if has_content: context |= contexts.HAS_TEMPLATE try: template = self._parse(context) except BadR...
python
def gateway_snapshot(self, indices=None): """ Gateway snapshot one or more indices (See :ref:`es-guide-reference-api-admin-indices-gateway-snapshot`) :keyword indices: a list of indices or None for default configured. """ path = self.conn._make_path(indices, (), '_gatewa...
java
protected String readContent(int record) throws IOException, CDKException { logger.debug("Current record ", record); if ((record < 0) || (record >= records)) { throw new CDKException("No such record " + record); } //fireFrameRead(); raFile.seek(index[record][0]); ...
python
def saveToObject(self): """Re-implemented from :meth:`AbstractComponentWidget<sparkle.gui.stim.abstract_component_editor.AbstractComponentWidget.saveToObject>`""" details = self._component.auto_details() for field, widget in self.inputWidgets.items(): self._component.set(field, widge...
python
def slice(self, start=0, end=0): """Slice the map from [start, end)""" tmp = Gauged.map_new() if tmp is None: raise MemoryError if not Gauged.map_concat(tmp, self.ptr, start, end, 0): Gauged.map_free(tmp) # pragma: no cover raise MemoryError r...
python
def jitChol(A, maxTries=10, warning=True): """Do a Cholesky decomposition with jitter. Description: U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky decomposition on the given matrix, if matrix isn't positive definite the function adds 'jitter' and tries again. Thereafter the...
java
public Observable<ServiceResponseWithHeaders<Void, JobDisableHeaders>> disableWithServiceResponseAsync(String jobId, DisableJobOption disableTasks) { if (this.client.batchUrl() == null) { throw new IllegalArgumentException("Parameter this.client.batchUrl() is required and cannot be null."); ...
java
public CmsSolrResultList search(CmsObject cms, String solrQuery) throws CmsSearchException { return search(cms, new CmsSolrQuery(null, CmsRequestUtil.createParameterMap(solrQuery)), false); }
java
public boolean matches(ResourcePathNode<Pattern> patternPath) { // currently does not support ** segments like in Ant if (isRoot()) { if (!patternPath.isRoot()) { return false; } } else if (patternPath.isRoot()) { return false; } else if (!this.parent.matches(patternPath.paren...
python
def length(self): """ Gives the length of the queue. Returns ``None`` if the queue is not connected. If the queue is not connected then it will raise :class:`retask.ConnectionError`. """ if not self.connected: raise ConnectionError('Queue is not conn...
java
public BaseBo setAttributes(Map<String, Object> attrs) { Lock lock = lockForWrite(); try { attributes = initAttributes(attrs); triggerPopulate(); return this; } finally { lock.unlock(); } }
java
public static void i(String msg, Throwable tr) { assertInitialization(); sLogger.i(msg, tr); }
java
public static void validateNotEmptyContent( String[] arrayToCheck, boolean trim, String argumentName ) throws NullArgumentException { validateNotEmpty( arrayToCheck, argumentName ); for( int i = 0; i < arrayToCheck.length; i++ ) { validateNotEmpty( arrayToCheck[ i ], arra...
python
def _request_login(self, method, **kwargs): """ Send a treq HTTP POST request to /ssllogin :param method: treq method to use, for example "treq.post" or "treq_kerberos.post". :param kwargs: kwargs to pass to treq or treq_kerberos, for example ...
java
private static void addToReceivers(final BroadcastReceiver receiver, final String action) { Set<String> actions = RECEIVERS.get(receiver); if (actions == null) { actions = new HashSet<String>(1); RECEIVERS.put(receiver, actions); } actions.add(action); }
python
def write(self, fptr): """Write a colour group box to file. """ self._validate(writing=True) self._write_superbox(fptr, b'cgrp')
python
def get(self, block_alias, context): """Main method returning block contents (static or dynamic).""" contents = [] dynamic_block_contents = self.get_contents_dynamic(block_alias, context) if dynamic_block_contents: contents.append(dynamic_block_contents) static_bloc...
python
def empty(cls, labels=None): """Creates an empty table. Column labels are optional. [Deprecated] Args: ``labels`` (None or list): If ``None``, a table with 0 columns is created. If a list, each element is a column label in a table with 0 rows....
java
public static String getHomeBeanClassName(EnterpriseBean enterpriseBean, boolean isPost11DD) // d114199 { String packageName = null; String homeInterfaceName = getHomeInterfaceName(enterpriseBean); // LIDB2281.24.2 made several changes to code below, to accommodate case // where ne...
java
public static DTMManager newInstance(XMLStringFactory xsf) throws DTMConfigurationException { DTMManager factoryImpl = null; try { factoryImpl = (DTMManager) ObjectFactory .createObject(defaultPropName, defaultClassName); } catch (ObjectFactory.ConfigurationError e) {...
java
public static void resetFocus (Stage stage) { if (focusedWidget != null) focusedWidget.focusLost(); if (stage != null) stage.setKeyboardFocus(null); focusedWidget = null; }
python
def imageInScreen(screen, image): """ Checks if image is on the screen @param screen: the screen image @param image: the partial image to look for @return: True or False @author: Perry Tsai <ripple0129@gmail.com> """ # To make sure image smaller than sc...
python
def _make_readline_peeker(self): """Make a readline-like function which peeks into the source.""" counter = itertools.count(0) def readline(): try: return self._peek_buffer(next(counter)) except StopIteration: return '' return readl...
java
public static void load( final CmsUUID structureId, final boolean includeTargets, final CmsUUID detailContentId, final String startTab, final Map<String, String> context, final CloseHandler<PopupPanel> closeHandler) { CmsRpcAction<CmsResourceStatusBean> a...
python
def get_learned_skills(self, lang): """ Return the learned skill objects sorted by the order they were learned in. """ skills = [skill for skill in self.user_data.language_data[lang]['skills']] self._compute_dependency_order(skills) return [ski...
java
private MapperMeta getMapperMeta(Configuration conf, final String statementId) throws ClassNotFoundException { MapperMeta meta = CACHED.get(statementId); if (meta == null) { int pos = statementId.lastIndexOf('.'); String namespace = statementId.substring(0, pos);// mapper类名 String methodName =...
java
public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src, int offset, int length) { final int end = offset + length; for (int i = offset; i < end; i++) { byteToHexStringPadded(dst, src[i]); } return dst; }
python
def violinplot(x=None, y=None, data=None, bw=0.2, scale='width', inner=None, ax=None, **kwargs): """Wrapper around Seaborn's Violinplot specifically for [0, 1] ranged data What's different: - bw = 0.2: Sets bandwidth to be small and the same between datasets - scale = 'width': Sets the w...
java
public DeploymentExtendedInner createOrUpdate(String resourceGroupName, String deploymentName, DeploymentProperties properties) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, deploymentName, properties).toBlocking().last().body(); }
java
public void setYmBase(Integer newYmBase) { Integer oldYmBase = ymBase; ymBase = newYmBase; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.MDD__YM_BASE, oldYmBase, ymBase)); }
java
public void setRemediationConfigurations(java.util.Collection<RemediationConfiguration> remediationConfigurations) { if (remediationConfigurations == null) { this.remediationConfigurations = null; return; } this.remediationConfigurations = new com.amazonaws.internal.SdkI...
python
def _GenerateStorageFileName(self): """Generates a name for the storage file. The result use a timestamp and the basename of the source path. Returns: str: a filename for the storage file in the form <time>-<source>.plaso Raises: BadConfigOption: raised if the source path is not set. ...
java
private void generateAttributesGroupInterface(Map<String, List<XsdAttribute>> createdAttributes, String attributeGroupName, AttributeHierarchyItem attributeHierarchyItem, String apiName){ String baseClassNameCamelCase = firstToUpper(attributeGroupName); String[] interfaces = getAttributeGroupObjectInter...
java
private Collection<Import> doImport(String url, Import previous) { try { if (url.startsWith("/")) { // absolute imports are searched in /WEB-INF/scss return resolveImport(Paths.get("/WEB-INF/scss").resolve(url)); } // find in import paths final List<Path> importPaths = new LinkedList<>(); // ...
java
@Override public R visitHidden(HiddenTree node, P p) { return scan(node.getBody(), p); }
python
def main(): '''Main routine.''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenant...
java
synchronized void collectLeafPages(Collection<PageWrapper> target) { this.pageByOffset.values().stream().filter(p -> !p.isIndexPage()).forEach(target::add); }
python
def generate_vcpu(self, vcpu_num): """ Generate <vcpu> domain XML child Args: vcpu_num(str): number of virtual cpus Returns: lxml.etree.Element: vcpu XML element """ vcpu = ET.Element('vcpu') vcpu.text = str(vcpu_num) return vcpu
java
private void addPluginConfigDefaultProperties() { for (ConfProp prop : ConfProp.values()) { if (conf.get(prop.name) == null) conf.set(prop.name, prop.defVal); } }
python
def check_runtime_errors(cmd_derived_from_alias, pos_args_table): """ Validate placeholders and their expressions in cmd_derived_from_alias to make sure that there is no runtime error (such as index out of range). Args: cmd_derived_from_alias: The command derived from the alias (inc...
java
@Override public Object sanitizeKey(Object cacheKey) throws KeySanitationExcepion { if (!(cacheKey instanceof String)) { throw new KeySanitationExcepion(DefaultKeySanitizer.class.getSimpleName() + " can only be used with Strings cache keys."); } try { return Base64.en...
java
public GitlabBadge getProjectBadge(Serializable projectId, Integer badgeId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL + "/" + badgeId; return retrieve().to(tailUrl, GitlabBadge.class); }
java
public void applyProperties(Swarm swarm) throws IOException { URL propsUrl = get(PROPERTIES_URL); if (propsUrl != null) { Properties urlProps = new Properties(); urlProps.load(propsUrl.openStream()); for (String name : urlProps.stringPropertyNames()) { ...
java
@Override public com.liferay.commerce.currency.model.CommerceCurrency getCommerceCurrencyByUuidAndGroupId( String uuid, long groupId) throws com.liferay.portal.kernel.exception.PortalException { return _commerceCurrencyLocalService.getCommerceCurrencyByUuidAndGroupId(uuid, groupId); }
python
def checkConditions(self,verbose=False,verbose_reference=False,public_call=False): ''' This method checks whether the instance's type satisfies the growth impatience condition (GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return impatience condition ...
java
public String formatDuration(Duration duration) { if (duration == null) return format(now()); TimeFormat timeFormat = getFormat(duration.getUnit()); return timeFormat.format(duration); }
python
def verify(self, signature): """Verifies the signature against the current cryptographic verifier state. :param bytes signature: The signature to verify """ prehashed_digest = self._hasher.finalize() self.key.verify( signature=signature, data=prehashed_di...
java
private void _buildInBinding( final InBinding binding, final StringBuilder stmt, final List<Object> params ) { // It's OK if null is contained. // if (n_values == 0) { // throw new SearchException( "invalid InB...
python
def userpass(self, dir="ppcoin"): """Reads config file for username/password""" source = os.path.expanduser("~/.{0}/{0}.conf").format(dir) dest = open(source, "r") with dest as conf: for line in conf: if line.startswith("rpcuser"): usernam...
java
@Override public EClass getIfcDocumentSelect() { if (ifcDocumentSelectEClass == null) { ifcDocumentSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1132); } return ifcDocumentSelectEClass; }
java
public String getAuthor() { if (SourceFile_Type.featOkTst && ((SourceFile_Type)jcasType).casFeat_author == null) jcasType.jcas.throwFeatMissing("author", "de.julielab.jules.types.ace.SourceFile"); return jcasType.ll_cas.ll_getStringValue(addr, ((SourceFile_Type)jcasType).casFeatCode_author);}
java
private void initSeLionRemoteProxySpecificValues(RemoteProxy proxy) { if (SeLionRemoteProxy.class.getCanonicalName().equals( proxy.getOriginalRegistrationRequest().getConfiguration().proxy)) { SeLionRemoteProxy srp = (SeLionRemoteProxy) proxy; // figure out if the proxy ...
python
def start(self): """ Start the daemon """ if self.is_running(): msg = "Daemon already running (pidfile:%s)" % self.pidfile self.logger.error(msg) return msg initres = self.init() if not initres[0]: return initres[1] ...
java
private File[] getSources(final List<File> sourceList) { final File[] sortedSources = new File[sourceList.size()]; sourceList.toArray(sortedSources); Arrays.sort(sortedSources, new Comparator<File>() { @Override public int compare(final File o1, final File o2) { return o1.getName().compa...
python
def due(self): """Get or set the end of the todo. | Will return an :class:`Arrow` object. | May be set to anything that :func:`Arrow.get` understands. | If set to a non null value, removes any already existing duration. | Setting to None will have unexpected beha...
java
private static void collectAllInterfaces(final ClassNode node, final Set<ClassNode> out) { if (node == null) return; Set<ClassNode> allInterfaces = node.getAllInterfaces(); out.addAll(allInterfaces); collectAllInterfaces(node.getSuperClass(), out); }
java
public byte[] getUserSessionKey(byte[] challenge) { if (hashesExternal) return null; byte[] key = new byte[16]; try { getUserSessionKey(challenge, key, 0); } catch (Exception ex) { if( log.level > 0 ) ex.printStackTrace( log ); } r...
java
public static <K1, V1, K2, V2> MutableMap<K2, V2> collectIf( Map<K1, V1> map, Function2<? super K1, ? super V1, Pair<K2, V2>> function, Predicate2<? super K1, ? super V1> predicate) { return MapIterate.collectIf(map, function, predicate, UnifiedMap.<K2, V2>newMap()); ...
java
private void addDiscriminatorClause(List<String> clauses, EntityType entityType) { if (((AbstractManagedType) entityType).isInherited()) { String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn(); String discrValue = ((AbstractManagedType) entityType).getDiscrimin...
python
def __add_location(self, type, *args): """ Defines the slot triggered by **Where_lineEdit** Widget when a context menu entry is clicked. :param type: Location type. :type type: unicode :param \*args: Arguments. :type \*args: \* """ if type == "directory"...
python
def sky2pix(self, pos): """ Convert sky coordinates into pixel coordinates. Parameters ---------- pos : (float, float) The (ra, dec) sky coordinates (degrees) Returns ------- pixel : (float, float) The (x,y) pixel coordinates ...
python
def check_database_connected(app_configs, **kwargs): """ A Django check to see if connecting to the configured default database backend succeeds. """ errors = [] try: connection.ensure_connection() except OperationalError as e: msg = 'Could not connect to database: {!s}'.for...
python
def fix_e502(self, result): """Remove extraneous escape of newline.""" (line_index, _, target) = get_index_offset_contents(result, self.source) self.source[line_index] = target.rstrip('\n\r \t\\') + '\n'
python
def couchdb_admin_party(**kwargs): """ Provides a context manager to create a CouchDB session in Admin Party mode and provide access to databases, docs etc. :param str url: URL for CouchDB server. :param str encoder: Optional json Encoder object used to encode documents for storage. Defaul...
java
@Override public void serializeToFile(File out, Object pojo) throws JSONMarshallException { try { mapper.writeValue(out, pojo); } catch (JsonMappingException e) { throw new JSONMarshallException("Unable to parse non-well-formed content", e); } catch (JsonGenerationExc...
python
def create_spot_instances(launch_specs, spot_price=26, expiration_mins=15): """ args: spot_price: default is $26 which is right above p3.16xlarge on demand price expiration_mins: this request only valid for this many mins from now """ ec2c = get_ec2_client() num_tasks = launch_specs['Mi...
java
private String partialUploadErrorMessage(String pid, int count, int total, String vitalPid) { String message = "Error submitting payload '" + pid + "' to VITAL. "; message += count + " of " + total + " payloads where successfully"; message += " sent to VITAL before this error occurre...
java
public String convertGSPTPATTToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
@NonNull public IconicsDrawable iconOffsetYDp(@Dimension(unit = DP) int sizeDp) { return iconOffsetYPx(Utils.convertDpToPx(mContext, sizeDp)); }
python
def send_messages(self, data, timeout=30, endpoint='/collab/start/'): """Send messages to server, along with user authentication.""" address = 'https://{}{}'.format(self.COLLAB_SERVER, endpoint) params = { 'client_name': 'ok-client', 'client_version': client.__version__, ...
python
def get_org_smarthost(self, orgid, serverid): """Get an organization smarthost""" return self.api_call( ENDPOINTS['orgsmarthosts']['get'], dict(orgid=orgid, serverid=serverid))
java
public static boolean addAll(LongCollection collection, long[] array) { boolean changed = false; for (long element : array) { changed |= collection.add(element); } return changed; }
java
public static JaxInfo build(Class<?> cls, JaxInfo parent) throws NoSuchFieldException, ClassNotFoundException, ParseException { return new JaxInfo(parent.name,parent.ns, cls,buildFields(cls,parent.ns),parent.isString, parent.isArray,parent.required,parent.nillable); }
python
def get_last_response_xml(self, pretty_print_if_possible=False): """ Retrieves the raw XML (decrypted) of the last SAML response, or the last Logout Response generated or processed :returns: SAML response XML :rtype: string|None """ response = None if sel...
java
private CompletableFuture<WriterFlushResult> flushNormally(TimeoutTimer timer) { assert this.state.get() == AggregatorState.Writing : "flushNormally cannot be called if state == " + this.state; long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "flushNormally", this.operations.s...
java
public static ApplicationContext contextMergedBeans(String xmlPath, Map<String, ?> extraBeans) { final DefaultListableBeanFactory parentBeanFactory = buildListableBeanFactory(extraBeans); //loads the xml and add definitions in the context GenericApplicationContext parentContext = new GenericApplicationConte...
python
def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True
java
public static <I extends StreamSourceChannel, O extends StreamSinkChannel> void initiateTransfer(long count, final I source, final O sink, final ChannelListener<? super I> sourceListener, final ChannelListener<? super O> sinkListener, final ChannelExceptionHandler<? super I> readExceptionHandler, ...
java
public static void copyAttachment(SQLDatabase db, long parentSequence, long newSequence, String filename) throws SQLException { Cursor c = null; try{ c = db.rawQuery(SQL_ATTACHMENTS_SELECT, new String[]{filename, String.valueOf(par...
python
def requires_role(self, roles): """ Require specific configured roles for access to a :mod:`flask` route. :param roles: Role or list of roles to test for access (only one role is required to pass). :type roles: str OR list(str) :raises: FlaskKeystoneForbidd...