language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public void stop(){ if (this.isStarted == false) return; synchronized (this) { if (this.isStarted == true) { getCache().refresh(); this.isStarted = false; } } }
python
def check_xups_bat_capacity(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.534.1.2.4.0 MIB Excerpt Battery percent charge. """ the_helper.add_metric( label=the_helper.options.type, value=a_snmp_value, uom='%') the_helper.set_summary("Remaining Batter...
java
protected CompletableFuture<ExecutionResult> resolveField(ExecutionContext executionContext, ExecutionStrategyParameters parameters) { return resolveFieldWithInfo(executionContext, parameters).thenCompose(FieldValueInfo::getFieldValue); }
python
def _load_roles(self): """ Load the roles, one per line, from the roles file. This is called at startup and whenever the roles file changes. Note that it is not strictly an error for the roles file to be missing but a warning is logged in case that was not intended. ...
python
def shellne(command): """ Runs 'commands' on the underlying shell; any stderr is echo'd to the console. Raises a RuntimeException on any shell exec errors. """ child = os.popen(command) data = child.read() err = child.close() if err: raise RuntimeError('%s faile...
java
public void bindDropDownView(T item, int position, View view) { bindView(item, position, view); }
python
def parse(code): """Annotate user code. Return annotated code (str) if annotation detected; return None if not. code: original user code (str) """ try: ast_tree = ast.parse(code) except Exception: raise RuntimeError('Bad Python code') transformer = Transformer() try: ...
python
def compute_affinity_matrix(adjacency_matrix, method='auto', **kwargs): """Compute the affinity matrix with the given method""" if method == 'auto': method = 'gaussian' return Affinity.init(method, **kwargs).affinity_matrix(adjacency_matrix)
java
private AuthorizeSecurityGroupIngressResponseType authorizeSecurityGroupIngress(final String groupId, final String ipProtocol, final Integer fromPort, final Integer toPort, final String cidrIp) { AuthorizeSecurityGroupIngressResponseType ret = new AuthorizeSecurityGroupIngressResponseType(); ...
java
public String getFormatName() { String result = ""; if ((m_formatHandler != null) && (m_formatHandler.getCurrentFormat() != null)) { result = m_formatHandler.getCurrentFormat().getName(); } return result; }
python
def get_operation_status(kwargs=None, conn=None, call=None): ''' .. versionadded:: 2015.8.0 Get Operation Status, based on a request ID CLI Example: .. code-block:: bash salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef ''' if call != 'function': ...
java
public static String getSLBDM(String[] soilParas) { if (soilParas != null && soilParas.length >= 3) { if (soilParas.length >= 4) { return round(calcGravePlusDensity(soilParas[0], soilParas[1], soilParas[2], divide(soilParas[3], "100")), 2); } else { return...
python
def validate_rid(model, rid): """ Ensure the resource id is proper """ rid_field = getattr(model, model.rid_field) if isinstance(rid_field, IntType): try: int(rid) except (TypeError, ValueError): abort(exceptions.InvalidURL(**{ 'detail': 'The resourc...
python
def read_data(self, **kwargs): """ get the data from the service :param kwargs: contain keyword args : trigger_id and model name :type kwargs: dict :rtype: dict """ date_triggered = kwargs.get('date_triggered') trigger_id = kwargs.get('tri...
java
private void endAnimation() { sAnimations.get().remove(this); sPendingAnimations.get().remove(this); sDelayedAnims.get().remove(this); mPlayingState = STOPPED; if (mRunning && mListeners != null) { ArrayList<AnimatorListener> tmpListeners = (ArrayL...
python
def get_data(__pkg: str, __name: str) -> str: """Return top-most data file for given package. Args: __pkg: Package name __name: Data file name """ for dname in get_data_dirs(__pkg): test_path = path.join(dname, __name) if path.exists(test_path): return test_p...
java
private static S3Recoverable castToS3Recoverable(CommitRecoverable recoverable) { if (recoverable instanceof S3Recoverable) { return (S3Recoverable) recoverable; } throw new IllegalArgumentException( "S3 File System cannot recover recoverable for other file system: " + recoverable); }
python
def find_file(path, filename, max_depth=5): """Returns full filepath if the file is in path or a subdirectory.""" for root, dirs, files in os.walk(path): if filename in files: return os.path.join(root, filename) # Don't search past max_depth depth = root[len(path) + 1:].count(os.sep) if depth...
python
def _genpath(self, filename, mhash): """Generate the path to a file in the cache. Does not check to see if the file exists. Just constructs the path where it should be. """ mhash = mhash.hexdigest() return os.path.join(self.mh_cachedir, mhash[0:2], mhash[2:4], ...
python
def get_conf_file(self): """ Get config from local config file, first try cache, then fallback. """ for conf_file in [self.collection_rules_file, self.fallback_file]: logger.debug("trying to read conf from: " + conf_file) conf = self.try_disk(conf_file, self.gpg) ...
java
public static EntityMetadata getEntityMetadata(final KunderaMetadata kunderaMetadata, Class entityClass) { if (entityClass == null) { throw new KunderaException("Invalid class provided " + entityClass); } List<String> persistenceUnits = kunderaMetadata.getApplicatio...
python
def increase_counter(self, *path, **kwargs): """Increase a counter. This method increases a counter within the application's namespace. Each element of `path` is converted to a string and normalized before joining the elements by periods. The normalization process is little mo...
python
def dot(self, other): """ Compute the dot product between the Series and the columns of other. This method computes the dot product between the Series and another one, or the Series and each columns of a DataFrame, or the Series and each columns of an array. It can also...
java
public static boolean canConnectUnixSocket(File path) { try (UnixSocketChannel channel = UnixSocketChannel.open()) { return channel.connect(new UnixSocketAddress(path)); } catch (IOException e) { return false; } }
python
def _get_vqa_v2_image_feature_dataset( directory, feature_url, feature_filename="mscoco_feat.tar.gz"): """Extract the VQA V2 feature data set to directory unless it's there.""" feature_file = generator_utils.maybe_download_from_drive( directory, feature_filename, feature_url) with tarfile.open(feature_f...
java
@Override public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { double evaluationTimeUnderlying = Math.max(evaluationTime, exerciseDate); RandomVariable underlyingValues = underlying.getValue(evaluationTimeUnderlying, model); RandomVariab...
python
def search(self, text): """ Find text in log file from current position returns a tuple containing: absolute position, position in result buffer, result buffer (the actual file contents) """ key = hash(text) searcher = self._searchers....
python
def audit_ghosts(self): """compare the list of configured jobs with the jobs in the state""" print_header = True for app_name in self._get_ghosts(): if print_header: print_header = False print ( "Found the following in the state dat...
java
@NonNull public static List<String> unmodifiableNonNullListOfStrings(@Nullable List<?> args) { if (args == null || args.isEmpty()) { return emptyList(); } else { final List<String> list = new ArrayList<String>(args.size()); for (Object arg : args) { ...
java
public int getInt(final String propertyName) { if (propertyName == null) { throw new NullPointerException("propertyName must not be null."); } Integer index = propertyMap.get(propertyName); if (index == null) { throw new IllegalArgumentException("non existent prop...
python
def _isNonAxi(Pot): """ NAME: _isNonAxi PURPOSE: Determine whether this potential is non-axisymmetric INPUT: Pot - Potential instance or list of such instances OUTPUT: True or False depending on whether the potential is non-axisymmetric (note that some potentials m...
java
public synchronized void waitForStart() throws ServerException, ClientException, IOException { try { while(!isStarted() && !hasError()) { wait(); } } catch(InterruptedException e) { // break } checkError(); }
java
@SuppressWarnings("unchecked") public EList<IfcFillAreaStyleTileShapeSelect> getTiles() { return (EList<IfcFillAreaStyleTileShapeSelect>) eGet(Ifc2x3tc1Package.Literals.IFC_FILL_AREA_STYLE_TILES__TILES, true); }
java
public void remove(final Tree<?, ?> child) { requireNonNull(child); if (!isChild(child)) { throw new IllegalArgumentException("The given child is not a child."); } remove(getIndex(child)); }
java
public String edit() { Entity<?> entity = getEntity(); put(getShortName(), entity); editSetting(entity); return forward(); }
python
def interprocess_locked(path): """Acquires & releases a interprocess lock around call into decorated function.""" lock = InterProcessLock(path) def decorator(f): @six.wraps(f) def wrapper(*args, **kwargs): with lock: return f(*args, **kwargs) re...
java
@BetaApi public final Operation insertSslCertificate( String project, SslCertificate sslCertificateResource) { InsertSslCertificateHttpRequest request = InsertSslCertificateHttpRequest.newBuilder() .setProject(project) .setSslCertificateResource(sslCertificateResource) ...
java
public void receiveAndProcess() { if (this.shouldContinue()) { this.receiver.receive(this.onReceiveHandler.getMaxEventCount()) .handleAsync(this.processAndReschedule, this.executor); } else { if (TRACE_LOGGER.isInfoEnabled()) { TRACE_LOGGER.inf...
java
public DescribePendingAggregationRequestsResult withPendingAggregationRequests(PendingAggregationRequest... pendingAggregationRequests) { if (this.pendingAggregationRequests == null) { setPendingAggregationRequests(new com.amazonaws.internal.SdkInternalList<PendingAggregationRequest>(pendingAggregat...
java
@XmlElementDecl(namespace = "http://www.ibm.com/websphere/wim", name = "pager") public JAXBElement<String> createPager(String value) { return new JAXBElement<String>(_Pager_QNAME, String.class, null, value); }
python
def create_shot_model(self, project, releasetype): """Create and return a new tree model that represents shots til descriptors The tree will include sequences, shots, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :da...
java
protected Optional<ProviderLoginPageConfiguration> buildProviderConfiguration(final IndirectClient client, final WebContext webContext, final WebApplicationService service) { val name = client.getName(); val matcher = PAC4...
java
public Endpoint getEndpoint(ModuleIdentifier identifier) { for (Endpoint endpoint : getEndpoints()) { if (endpoint.getIdentifier().equals(identifier)) { return endpoint; } } return null; }
python
def fetch_resource(self): """ Fetch & return the resource that the action operated on, or `None` if the resource no longer exists (specifically, if the API returns a 404) :rtype: `Droplet`, `Image`, `FloatingIP`, or `None` :raises ValueError: if the action has an unknown ``resou...
python
def produce_pdf(rst_content=None, doctree_content=None, filename=None): """produce a pdf content based of a given rst content If filename is given, it will store the result using the given filename if no filename is given, it will generate a pdf in /tmp/ with a random name """ if filename is No...
python
def remove_object_metadata_key(self, container, obj, key, prefix=None): """ Removes the specified key from the storage object's metadata. If the key does not exist in the metadata, nothing is done. """ self.set_object_metadata(container, obj, {key: ""}, prefix=prefix)
python
def expand_includes(text, path='.'): """Recursively expands includes in given text.""" def read_and_expand(match): filename = match.group('filename') filename = join(path, filename) text = read(filename) return expand_includes( text, path=join(path, dirname(filename))...
python
def extend(self, **kwargs): """Returns a new instance with this instance's data overlayed by the key-value args.""" props = self.copy() props.update(kwargs) return TemplateData(**props)
java
public List<HalResource<?>> resolve(HalRelation relation, ProcessEngine processEngine) { HalLinkResolver linkResolver = hal.getLinkResolver(relation.resourceType); if(linkResolver != null) { Set<String> linkedIds = getLinkedResourceIdsByRelation(relation); if(!linkedIds.isEmpty()) { return l...
python
def merge_components( *components: typing.List[typing.Union[list, tuple, COMPONENT]] ) -> COMPONENT: """ Merges multiple COMPONENT instances into a single one by merging the lists of includes and files. Has support for elements of the components arguments list to be lists or tuples of COMPONENT ...
java
@Deprecated @Nullable public V get() { V value = pop(); if (value != null) { mInUseLength++; } return value; }
python
def safe_display_name(numobj, lang, script=None, region=None): """Gets the name of the carrier for the given PhoneNumber object only when it is 'safe' to display to users. A carrier name is onsidered safe if the number is valid and for a region that doesn't support mobile number portability (http://en....
java
public static InternetAddress parseEmail(Object value, InternetAddress defaultValue) { String str = Caster.toString(value, ""); if (str.indexOf('@') > -1) { try { str = fixIDN(str); InternetAddress addr = new InternetAddress(str); // fixIDN( addr ); return addr; } catch (AddressException ex) {}...
python
def list_models(self, limit=-1, offset=-1): """Get a list of models in the registry. Parameters ---------- limit : int Limit number of items in the result set offset : int Set offset in list (order as defined by object store) Returns ------- li...
java
public void setSharingPolicy(int sharingPolicy) { if (lock == SET) { throw new IllegalStateException("EntryInfo is locked"); } sharingPolicyFlag = SET; this.sharingPolicy = sharingPolicy; if ((sharingPolicy != NOT_SHARED) && (sharingPolicy != SHARED_PUSH) && (sharingPolicy != SHARED_PULL) && (sharingP...
java
private void writeTextHandleTransformAs(String transformName, ExtensionMetadata metadata, Object source, String transformType) throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException { if (source == null) { throw new IllegalArgumentException("no sou...
java
public static <T> Subscription listBind( List<? super T> target, ObservableList<? extends T> source) { target.clear(); target.addAll(source); ListChangeListener<? super T> listener = change -> { while(change.next()) { int from = change.getFrom(...
python
def _print_summary_map(strm, result_map, ftype): """Print summary of certain result map.""" if len(result_map) == 0: return 0 npass = len([x for k, x in result_map.iteritems() if len(x) == 0]) strm.write('=====%d/%d %s files passed check=====\n' % (npass, len(result_map), fty...
python
def _get_forecast(api_result: dict) -> List[SmhiForecast]: """Converts results fråm API to SmhiForeCast list""" forecasts = [] # Need the ordered dict to get # the days in order in next stage forecasts_ordered = OrderedDict() forecasts_ordered = _get_all_forecast_from_api(api_result) ...
python
def to_title_caps(underscore_case): r""" Args: underscore_case (?): Returns: str: title_str CommandLine: python -m utool.util_str --exec-to_title_caps Example: >>> # DISABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> underscore_case = 'the...
java
public static String newWwwUrlEncodedUrl(final String baseUrl, final Map<String, String> paramMap) { final StringBuilder sb = new StringBuilder(); sb.append(baseUrl); sb.append(getUrlParameters(paramMap, false)); return sb.toString(); }
python
def addFailure(self, test: unittest.case.TestCase, exc_info: tuple) -> None: """ Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save :param exc_info: tuple of the form (Exception class, Exception instance, traceb...
java
public static String getDataSourceIdentifier(WSJdbcWrapper jdbcWrapper) { DSConfig config = jdbcWrapper.dsConfig.get(); return config.jndiName == null ? config.id : config.jndiName; }
java
public void getFileTarHeader(TarHeader hdr, File file) throws InvalidHeaderException { this.file = file; String name = file.getPath(); String osname = System.getProperty("os.name"); if (osname != null) { // Strip off drive letters! // REVIEW Would a better...
java
private void updateImage() { if (!over) { currentImage = normalImage; currentColor = normalColor; state = NORMAL; mouseUp = false; } else { if (mouseDown) { if ((state != MOUSE_DOWN) && (mouseUp)) { if (mouseDownSound != null) { mouseDownSound.play(); } currentIma...
python
def make_publication_epub(binders, publisher, publication_message, file): """Creates an epub file from a binder(s). Also requires publication information, meant to be used in a EPUB publication request. """ if not isinstance(binders, (list, set, tuple,)): binders = [binders] packages = [...
python
def new(cls, shapes, start_x, start_y, x_scale, y_scale): """Return a new |FreeformBuilder| object. The initial pen location is specified (in local coordinates) by (*start_x*, *start_y*). """ return cls( shapes, int(round(start_x)), int(round(start_y)), x...
python
def loads(xml, force_list=None): """Cria um dicionário com os dados do XML. O dicionário terá como chave o nome do nó root e como valor o conteúdo do nó root. Quando o conteúdo de um nó é uma lista de nós então o valor do nó será um dicionário com uma chave para cada nó. Entretanto, se existir nós,...
java
private static Boolean openURLinUnixOS(final String url) throws InterruptedException, IOException, Exception { Boolean executed = false; for (final Browsers browser : Browsers.values()) { if (!executed) { executed = Runtime.getRuntime() .exec(new String[] { UNIX_COMMAND_WHICH, browser.getBrowser...
python
def triangle_plots(self, basename=None, format='png', **kwargs): """Returns two triangle plots, one with physical params, one observational :param basename: If basename is provided, then plots will be saved as "[basename]_physical.[format]" and "[basename]...
java
public static void checkState(boolean condition, String message, Object ... values) { if (!condition) { throw new EvalError(String.format(message, values)); } }
java
public TableAlias addTable(String table, String aliasPrefix) { String alias = makeAlias(aliasPrefix); m_tables.add(table + " " + alias); return new TableAlias(alias); }
python
def gpg_decrypt(cfg, gpg_config=None): """Decrypt GPG objects in configuration. Args: cfg (dict): configuration dictionary gpg_config (dict): gpg configuration dict of arguments for gpg including: homedir, binary, and keyring (require all if any) example:...
java
public static boolean startAny(String target, String... startWith) { return startAny(target, 0, Arrays.asList(startWith)); }
java
@POST @Path("refresh") @Consumes(MediaType.APPLICATION_JSON) public Response refreshAccessToken(RefreshTokenRequest refreshToken) { // Perform all validation here to control the exact error message returned to comply with the Oauth2 standard if (null == refreshToken.getRefresh_token() || null == ...
java
protected void addConstructedGuardToMethodBody(final ClassMethod classMethod, String className) { if (!useConstructedFlag()) { return; } // now create the conditional final CodeAttribute cond = classMethod.getCodeAttribute(); cond.aload(0); cond.getfield(class...
python
def simple_decorator(decorator): """This decorator can be used to turn simple functions into well-behaved decorators, so long as the decorators are fairly simple. If a decorator expects a function and returns a function (no descriptors), and if it doesn't modify function attributes or docstring...
java
public void actionPurgeJspRepository() throws JspException { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_FLEX_PURGE_JSP_REPOSITORY, Collections.<String, Object> emptyMap())); OpenCms.fireCmsEvent( new CmsEvent( I_CmsEventListener.EVENT_FLEX_CACHE_...
java
static URI checkType(final URI type) { Preconditions.checkNotNull(type, "No type specified"); if (!type.equals(KS.RESOURCE) && !type.equals(KS.MENTION) && !type.equals(KS.ENTITY) && !type.equals(KS.AXIOM)) { throw new IllegalArgumentException("Invalid type: " + type); ...
java
public Scanner reset() { delimPattern = WHITESPACE_PATTERN; useLocale(Locale.getDefault(Locale.Category.FORMAT)); useRadix(10); clearCaches(); return this; }
java
public Project getProject(String namespace, String project, Boolean includeStatistics) throws GitLabApiException { if (namespace == null) { throw new RuntimeException("namespace cannot be null"); } if (project == null) { throw new RuntimeException("project cannot be nul...
java
public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) { messageQueue.add(new AttributeLogEntry(address, operation, message, attributes)); }
java
@SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Findbugs believes readRecord(null) is non-null. This is not true.") protected RecordEnvelope<D> readRecordEnvelopeImpl() throws DataRecordException, IOException { D record = readRecordImpl(null); return record == nul...
python
def _ret16(ins): """ Returns from a procedure / function a 16bits value """ output = _16bit_oper(ins.quad[1]) output.append('#pragma opt require hl') output.append('jp %s' % str(ins.quad[2])) return output
python
def get_learning_rate(learning_rate, hidden_size, learning_rate_warmup_steps): """Calculate learning rate with linear warmup and rsqrt decay.""" with tf.name_scope("learning_rate"): warmup_steps = tf.to_float(learning_rate_warmup_steps) step = tf.to_float(tf.train.get_or_create_global_step()) learning_...
python
def produce_upgrade_operations( ctx=None, metadata=None, include_symbol=None, include_object=None, **kwargs): """Produce a list of upgrade statements.""" if metadata is None: # Note, all SQLAlchemy models must have been loaded to produce # accurate results. metadata = db....
java
@Override protected void addNavDetailLink(boolean link, Content liNav) { if (link) { liNav.addContent(writer.getHyperLink( SectionName.FIELD_DETAIL, contents.navField)); } else { liNav.addContent(contents.navField); } }
python
def _users_watching(self, **kwargs): """Return users watching this instance.""" return self._users_watching_by_filter(object_id=self.instance.pk, **kwargs)
java
protected ActiveMqQueue<ID, DATA> setConnectionFactory( ActiveMQConnectionFactory connectionFactory, boolean setMyOwnConnectionFactory) { if (myOwnConnectionFactory && this.connectionFactory != null) { // destroy this.connectionFactory } this.connectionFactory = connectio...
java
public synchronized void receivePacketAndRespond(IQ iq) throws XMPPException, SmackException, InterruptedException { List<IQ> responses = new ArrayList<>(); String responseId; LOGGER.fine("Packet: " + iq.toXML()); try { // Dispatch the packet to the JingleNegotiators and ...
java
public void addRow(Component component) { Component actualComponent = component == null ? m_newComponentFactory.get() : component; I_CmsEditableGroupRow row = m_rowBuilder.buildRow(this, actualComponent); m_container.addComponent(row); updatePlaceholder(); updateButtonBars(); ...
java
public int getNumberOfSignaturesRequiredToSpend() { if (ScriptPattern.isSentToMultisig(this)) { // for N of M CHECKMULTISIG script we will need N signatures to spend ScriptChunk nChunk = chunks.get(0); return Script.decodeFromOpN(nChunk.opcode); } else if (ScriptPatte...
java
private static int readCode(boolean[] rawbits, int startIndex, int length) { int res = 0; for (int i = startIndex; i < startIndex + length; i++) { res <<= 1; if (rawbits[i]) { res |= 0x01; } } return res; }
python
def qstd(x,quant=0.05,top=False,bottom=False): """returns std, ignoring outer 'quant' pctiles """ s = np.sort(x) n = np.size(x) lo = s[int(n*quant)] hi = s[int(n*(1-quant))] if top: w = np.where(x>=lo) elif bottom: w = np.where(x<=hi) else: w = np.where((x>=lo...
java
public void marshall(BatchListIndex batchListIndex, ProtocolMarshaller protocolMarshaller) { if (batchListIndex == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(batchListIndex.getRangesOnIndexedValu...
python
def _get_patches(installed_only=False, root=None): ''' List all known patches in repos. ''' patches = {} for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'): installed = element.getAttribute('status') == 'installed' if (installed...
java
@Override public ORB createServerORB(Map<String, Object> config, Map<String, Object> extraConfig, List<IIOPEndpoint> endpoints, Collection<SubsystemFactory> subsystemFactories) throws ConfigException { ORB orb = createORB(translateToTargetArgs(config, subsystemFactories), translateToTargetProps(config, extr...
python
def check_error_code(self): """ For CredSSP version of 3 or newer, the server can response with an NtStatus error code with details of what error occurred. This method will check if the error code exists and throws an NTStatusException if it is no STATUS_SUCCESS. """ ...
python
def _search_keys(text, keyserver, user=None): ''' Helper function for searching keys from keyserver ''' gpg = _create_gpg(user) if keyserver: _keys = gpg.search_keys(text, keyserver) else: _keys = gpg.search_keys(text) return _keys
python
def page_title(step, title): """ Check that the page title matches the given one. """ with AssertContextManager(step): assert_equals(world.browser.title, title)