language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void plain(String response) { HttpHandlers.registerPredefined(setup, verb, path, plainOpts(), response); }
java
public OvhDelegation domain_account_accountName_delegation_accountId_GET(String domain, String accountName, String accountId) throws IOException { String qPath = "/email/domain/{domain}/account/{accountName}/delegation/{accountId}"; StringBuilder sb = path(qPath, domain, accountName, accountId); String resp = exe...
python
def echo_results_file(results_file, no_color, verbose=False): """Print test results in nagios style format.""" try: data = collect_results(results_file) except ValueError: echo_style( 'The results file is not the proper json format.', no_color, fg='red' ...
java
@Override public boolean process(ContentEvent event) { InstanceContentEvent inEvent = (InstanceContentEvent) event; Instance instance = inEvent.getInstance(); if (inEvent.getInstanceIndex() < 0) { //end learning ResultContentEvent outContentEvent = new ResultContentEvent(-1, instance, 0, new doub...
java
private void createOrUpdateSchema(Boolean isUpdate) { createNamespace(isUpdate); readExternalProperties(); Map<Class<?>, EntityType<?>> entityMap = kunderaMetadata.getApplicationMetadata() .getMetaModelBuilder(puMetadata.getPersistenceUnitName()).getManagedTypes(); /...
python
def set_completions(self, completions, go_to_first=True, go_to_last=False): """ Start completions. (Generate list of completions and initialize.) """ assert not (go_to_first and go_to_last) # Generate list of all completions. if completions is None: if self.c...
python
def _get_transitions(self, indexes): """ Return batch with given indexes """ transition_tensors = self.backend.get_transitions(indexes) return Trajectories( num_steps=indexes.shape[0], num_envs=indexes.shape[1], environment_information=None, trans...
java
public byte[] getArray (final int length) { for (int i = 0; i < size; ++i) { if (length == arrays[i].length) { // swap (if not already at the front) and return if (i > 0) { tmp = arrays[i]; arrays[i] = arrays[i - 1]; ...
java
@Override public DeleteTableResult deleteTable(DeleteTableRequest request) { request = beforeClientExecution(request); return executeDeleteTable(request); }
python
def evaluate(reference_sources, estimated_sources, **kwargs): """Compute all metrics for the given reference and estimated signals. NOTE: This will always compute :func:`mir_eval.separation.bss_eval_images` for any valid input and will additionally compute :func:`mir_eval.separation.bss_eval_sources` f...
java
public static synchronized void serializeSessionAttributes(final HttpSession session) { if (session != null) { File file = new File(SERIALIZE_SESSION_NAME); if (!file.exists() || file.canWrite()) { // Retrieve the session attributes List data = new ArrayList(); for (Enumeration keyEnum = session.g...
java
public static final Function<String, LocalTime> strToLocalTime(String pattern, String locale, DateTimeZone dateTimeZone) { return FnLocalTime.strToLocalTime(pattern, locale, dateTimeZone); }
java
public AABBd union(AABBd other, AABBd dest) { dest.minX = this.minX < other.minX ? this.minX : other.minX; dest.minY = this.minY < other.minY ? this.minY : other.minY; dest.minZ = this.minZ < other.minZ ? this.minZ : other.minZ; dest.maxX = this.maxX > other.maxX ? this.maxX : other.maxX...
python
def extract_subset(self, subset, contract=True): """ Return all nodes in a subset. We assume the oboInOwl encoding of subsets, and subset IDs are IRIs, or IR fragments """ return [n for n in self.nodes() if subset in self.subsets(n, contract=contract)]
python
def get_line_bad_footnotes(line, tag=None, include_tags=None): """ Return [original_line, url_footnote1, url_footnote2, ... url_footnoteN] for N bad footnotes in the line """ if tag is None or include_tags is None or tag in include_tags or any((tag.startswith(t) for t in include_tags)): found_baddies =...
python
def content(self, value): """ Set content to byte string, encoding if necessary """ if isinstance(value, bytes): self._content = value else: self._content = value.encode(ENCODING) self.size = len(value)
java
public WebTarget appendPathAndQueryParameters(final WebTarget webTarget) { ArgumentChecker.notNull(webTarget, "webTarget"); WebTarget resultTarget = webTarget; resultTarget = resultTarget.path(DATASETS_RELATIVE_URL + EXTENSION); if (_databaseCode != null) { resultTarget = resultTarget.queryParam(D...
python
def is_valid(self): ''' Validate form. Return True if Django validates the form, the username obeys the parameters, and passwords match. Return False otherwise. ''' if not super(ProfileRequestForm, self).is_valid(): return False validity = True if self...
java
public void startPrepareFixture(final String containerUuid, final String uuid, final FixtureResult result) { storage.getContainer(containerUuid).ifPresent(container -> { synchronized (storage) { container.getBefores().add(result); } }); notifier.beforeFixt...
java
public UnionOperator<T> union(DataSet<T> other){ return new UnionOperator<>(this, other, Utils.getCallLocationName()); }
python
def update(self, dialing_permissions_inheritance=values.unset): """ Update the SettingsInstance :param bool dialing_permissions_inheritance: `true` for this sub-account to inherit voice dialing permissions from the Master Project; otherwise `false` :returns: Updated SettingsInstance ...
java
private void writeNewLineIndent() throws IOException { if (m_pretty) { if (!m_indent.isEmpty()) { m_writer.write('\n'); m_writer.write(m_indent); } } }
python
def remove_widget(self): """ Removes the Component Widget from the engine. :return: Method success. :rtype: bool """ LOGGER.debug("> Removing '{0}' Component Widget.".format(self.__class__.__name__)) self.__preferences_manager.findChild(QGridLayout, "Others_Pre...
java
public static boolean isArchiveFileName(String fileName) { String extension = getExtension(fileName); return ARCHIVE_EXTENSION_SET.contains(extension); }
java
public void marshall(ModelArtifacts modelArtifacts, ProtocolMarshaller protocolMarshaller) { if (modelArtifacts == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(modelArtifacts.getS3ModelArtifacts(),...
python
def get_families(self): """Pass through to provider FamilyLookupSession.get_families""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('family_lookup_session').get_families() cat_list = [] ...
python
async def send_file(self, file_type, method, file, payload) -> Union[Dict, base.Boolean]: """ Send file https://core.telegram.org/bots/api#inputfile :param file_type: field name :param method: API method :param file: String or io.IOBase :param payload: request p...
java
public DTMIterator cloneWithReset() throws CloneNotSupportedException { OneStepIterator clone = (OneStepIterator) super.cloneWithReset(); clone.m_iterator = m_iterator; return clone; }
python
def get_public_url(self, doc_id, branch='master'): """Returns a GitHub URL for the doc in question (study, collection, ...) """ name, path_frag = self.get_repo_and_path_fragment(doc_id) return 'https://raw.githubusercontent.com/OpenTreeOfLife/' + name + '/' + branch + '/' + path_frag
python
def where(self, other, cond, align=True, errors='raise', try_cast=False, axis=0, transpose=False): """ evaluate the block; return result block(s) from the result Parameters ---------- other : a ndarray/object cond : the condition to respect align :...
java
@SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity", "PMD.CollapsibleIfStatements", "PMD.DataflowAnomalyAnalysis" }) public int matches(URI resource) { if (protocol != null && !protocol.equals("*")) { if (resource.getScheme() == null) { return -1; ...
python
def _isCompatible(self, other, reporter): """ This is the environment implementation of :meth:`BaseSegment.isCompatible`. Subclasses may override this method. """ segment1 = self segment2 = other # type if segment1.type != segment2.type: ...
java
public int read_attribute_asynch(final DeviceProxy deviceProxy, final String attname) throws DevFailed { final String[] attnames = new String[1]; attnames[0] = attname; return read_attribute_asynch(deviceProxy, attnames); }
java
private CharSequence iterableContext(final Iterable<Object> context, final Options options) throws IOException { StringBuilder buffer = new StringBuilder(); if (options.isFalsy(context)) { buffer.append(options.inverse()); } else { Iterator<Object> iterator = context.iterator(); int ...
python
def random_array(shape, mean=128., std=20.): """Creates a uniformly distributed random array with the given `mean` and `std`. Args: shape: The desired shape mean: The desired mean (Default value = 128) std: The desired std (Default value = 20) Returns: Random numpy array of given `...
python
def write_biom(biom_tbl, output_fp, fmt="hdf5", gzip=False): """ Write the BIOM table to a file. :type biom_tbl: biom.table.Table :param biom_tbl: A BIOM table containing the per-sample OTU counts and metadata to be written out to file. :type output_fp str :param output_fp: Pat...
python
def info(self): """Return info about the dimension instance. Args:: no argument Returns:: 4-element tuple holding: - dimension name; 'fakeDimx' is returned if the dimension has not been named yet, where 'x' is the dimension index number ...
python
def list(self, category=values.unset, start_date=values.unset, end_date=values.unset, include_subaccounts=values.unset, limit=None, page_size=None): """ Lists RecordInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` r...
python
def longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. """ if string is None: return 0 start, max_len = 0, 0 used_char = {} for index, char in enumerate(string): if char in used_char an...
python
def get_banks_by_query(self, bank_query): """Gets a list of ``Bank`` objects matching the given bank query. arg: bank_query (osid.assessment.BankQuery): the bank query return: (osid.assessment.BankList) - the returned ``BankList`` raise: NullArgument - ``bank_query`` is ``null`` ...
python
def ifar(self, coinc_stat): """Return the far that would be associated with the coincident given. """ n = self.coincs.num_greater(coinc_stat) return self.background_time / lal.YRJUL_SI / (n + 1)
java
protected void onDouble(Double floating, String fieldName, JsonParser jp) { log.trace(fieldName + " " + floating); }
java
public String getString(int resId) { Activity activity = getCurrentActivity(false); if(activity == null){ return ""; } return activity.getString(resId); }
java
private boolean paramAppend(StringBuilder sb, String name, String value, ParameterParser parser) { boolean isEdited = false; if (name != null) { sb.append(name); isEdited = true; } if (value != null) { sb.append(parser.getDef...
python
def get_final_numbers(filename, out_dir): """Copy the final_files file and get the number of markers and samples. :param filename: the name of the file. :param out_dir: the output directory. :type filename: str :type out_dir: str :returns: the final number of markers and samples :rtype: t...
python
def _create_checkable_action(self, text, conf_name, editorstack_method): """Helper function to create a checkable action. Args: text (str): Text to be displayed in the action. conf_name (str): configuration setting associated with the action editorstack_method ...
python
def _make_sql_params(self,kw): """Make a list of strings to pass to an SQL statement from the dictionary kw with Python types""" vals = [] for k,v in kw.iteritems(): vals.append('%s=%s' %(k,self._conv(v))) return vals
java
public static <T> T toBean(String text, Class<T> clazz) { return JSON.parseObject(text, clazz); }
python
def install_host(use_threaded_wrapper): """Install required components into supported hosts An unsupported host will still run, but may encounter issues, especially with threading. """ for install in (_install_maya, _install_houdini, _install_nuke, ...
python
def process_line(self, line): """Process a line of data. Sends the data through the pipe to the process and flush it. Reads a resulting line and returns it. Parameters ---------- line: str The data sent to process. Make sur...
python
def run(self, args): """ Gives user permission based on auth_role arg and sends email to that user. :param args Namespace arguments parsed from the command line """ email = args.email # email of person to send email to username = args.username ...
java
public void setTargetCheckNames(java.util.Collection<String> targetCheckNames) { if (targetCheckNames == null) { this.targetCheckNames = null; return; } this.targetCheckNames = new java.util.ArrayList<String>(targetCheckNames); }
python
def valid_env_vars() -> bool: """Validate that required env vars exist. :returns: True if required env vars exist. .. versionadded:: 0.0.12 """ for envvar in _REQUIRED_ENV_VARS: try: _check_env_var(envvar) except KeyError as ex: LOG.error(ex) sys...
java
private synchronized void removeTail() { I_CmsLruCacheObject oldTail = m_listTail; if (oldTail != null) { I_CmsLruCacheObject newTail = oldTail.getNextLruObject(); // set the list pointers correct if (newTail != null) { // there are still objects rem...
java
@Override public void fireValueNodeAdded(IValueNode valueNode) { for (IDatabaseListener iDatabaseListener : listeners) { iDatabaseListener.valueNodeAdded(valueNode); } }
java
public static List<Invocation> findMatchingChunk(List<Invocation> invocations, MatchableInvocation wanted, int wantedCount, InOrderContext context) { List<Invocation> unverified = removeVerifiedInOrder(invocations, context); List<Invocation> firstChunk = getFirstMatchingChunk(wanted, unverified); ...
python
def as_view(cls, *class_args, **class_kwargs): """Return view function for use with the routing system, that dispatches request to appropriate handler method. """ def view(*args, **kwargs): self = view.view_class(*class_args, **class_kwargs) return self.dispatch_...
java
public <T> T get(ConfigKey key, T def) { Object o = data.get(key); if (null == o) { o = key.val(raw); if (null == o) { o = null == def ? NULL : def; } data.put(key, o); } if (isDebugEnabled()) { debug("config[%s]...
java
public Revision forward(int count) { if (count == 0) { return this; } if (count < 0) { throw new IllegalArgumentException("count " + count + " (expected: a non-negative integer)"); } return new Revision(add(major, count)); }
java
@Inline(value = "$1.remove($2)", statementExpression = true) public static <K, V> V operator_remove(Map<K, V> map, K key) { return map.remove(key); }
python
def get_synset_by_id(self, mongo_id): ''' Builds a Synset object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._synset_cache is not None: cache_hit = self...
python
def unique_index(df): """ Assert that the index is unique Parameters ========== df : DataFrame Returns ======= df : DataFrame """ try: assert df.index.is_unique except AssertionError as e: e.args = df.index.get_duplicates() raise return df
java
public OffsetTime getInternalOffsetTime(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } ZoneId zoneId = timeZone.toZoneId().normalized(); ...
java
static boolean isNestedObjectPattern(Node n) { checkState(n.isObjectPattern()); for (Node key = n.getFirstChild(); key != null; key = key.getNext()) { Node value = key.getFirstChild(); if (value != null && (value.isObjectLit() || value.isArrayLit() || value.isDestructuringPattern())) { ...
python
def write(self, bucket, rows, keyed=False, as_generator=False, update_keys=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Check update keys if update_keys is not None and len(update_keys) == 0: message = 'Argument "update_keys" cannot be an em...
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataMaxCardinalityImpl instance) throws SerializationException { serialize(streamWriter, instance); }
python
def _Helmholtz(self, rho, T): """Calculated properties from helmholtz free energy and derivatives Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] Returns ------- prop : dict Dictionary wit...
python
def get_polygon_pattern_rules(declarations, dirs): """ Given a list of declarations, return a list of output.Rule objects. Optionally provide an output directory for local copies of image files. """ property_map = {'polygon-pattern-file': 'file', 'polygon-pattern-width': 'width', ...
python
def addIdentifier(self, identifier=None, seed=None, signer=None, alias=None, didMethodName=None): """ Adds signer to the wallet. Requires complete signer, identifier or seed. :p...
python
def _x_open(self): """Open a channel for use This method opens a virtual connection (a channel). RULE: This method MUST NOT be called when the channel is already open. PARAMETERS: out_of_band: shortstr (DEPRECATED) out-of-band sett...
java
@Override public <T> T findOne(LdapQuery query, Class<T> clazz) { List<T> result = find(query, clazz); if (result.size() == 0) { throw new EmptyResultDataAccessException(1); } else if (result.size() != 1) { throw new IncorrectResultSizeDataAccessException(1, ...
java
@XmlElementDecl(namespace = "http://www.w3.org/ns/prov#", name = "wasEndedBy") public JAXBElement<WasEndedBy> createWasEndedBy(WasEndedBy value) { return new JAXBElement<WasEndedBy>(_WasEndedBy_QNAME, WasEndedBy.class, null, value); }
python
def _get_ami_dict(json_url): """Get ami from a web url. Args: region (str): AWS Region to find AMI ID. Returns: dict: Contents in dictionary format. """ LOG.info("Getting AMI from %s", json_url) response = requests.get(json_url) assert response.ok, "Error getting ami info ...
python
def _daemonize(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: ...
java
public Long getPrimarySsId(String address, boolean sync) throws IOException, KeeperException, InterruptedException, ClassNotFoundException { Stat stat = new Stat(); String node = getSsIdNode(address); byte[] data = getNodeData(node, stat, false, sync); if (data == null) { return null; } ...
python
def _simple_clause_to_query(clause): """ Convert a clause from the Sacred Web API format to the MongoDB format. :param clause: A clause to be converted. It must have "field", "operator" and "value" fields. :return: A MongoDB clause. """ # It's a regular clause ...
java
@Deprecated public static int getLevenshteinDistance(CharSequence s, CharSequence t, final int threshold) { if (s == null || t == null) { throw new IllegalArgumentException("Strings must not be null"); } if (threshold < 0) { throw new IllegalArgumentException("Thresho...
java
public @Nonnull EnvVars buildEnvironment(@Nonnull TaskListener listener) throws IOException, InterruptedException { EnvVars env = new EnvVars(); Node node = getNode(); if (node==null) return env; // bail out for (NodeProperty nodeProperty: Jenkins.getInstance().getGlobalNodePropert...
java
public AlertPolicyChannelService delete(long policyId, long channelId) { QueryParameterList queryParams = new QueryParameterList(); queryParams.add("policy_id", policyId); queryParams.add("channel_id", channelId); HTTP.DELETE("/v2/alerts_policy_channels.json", null, queryParams); ...
java
public List<MessageHandler> getHandlers(IPredicate<MessageHandler> filter) { List<MessageHandler> matching = new ArrayList<MessageHandler>(); for (MessageHandler handler : handlers) { if (filter.apply(handler)) { matching.add(handler); } } return m...
python
def getRealInterfaceNumber(self, interface): """ Returns the host-visible interface number, or None if there is no such interface. """ try: return self._ioctl(INTERFACE_REVMAP, interface) except IOError as exc: if exc.errno == errno.EDOM: ...
java
private CmsAcceptDeclineCancelDialog getLeaveDialog() { StringBuffer message = new StringBuffer(); message.append("<p>" + Messages.get().key(Messages.GUI_DIALOG_LEAVE_NOT_SAVED_0) + "</p>"); message.append("<p>" + Messages.get().key(Messages.GUI_DIALOG_SAVE_QUESTION_0) + "</p>"); CmsAc...
python
def genesis(chain_class: BaseChain, db: BaseAtomicDB=None, params: Dict[str, HeaderParams]=None, state: GeneralState=None) -> BaseChain: """ Initialize the given chain class with the given genesis header parameters and chain state. """ if state is None: ge...
java
public GroupOptions addSort(@Nullable Sort sort) { if (sort == null) { return this; } if (this.sort == null) { this.sort = sort; } else { this.sort = this.sort.and(sort); } return this; }
java
@SuppressWarnings("unchecked") public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) { try { return (ObjectInstantiator<T>) constructor.newInstance(type); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new ObjenesisException(e...
java
public static void generate(OutputStream dest, AceDataset set, boolean closeStream) throws IOException { JsonGenerator g = JsonFactoryImpl.INSTANCE.getGenerator(dest); g.writeStartObject(); g.writeArrayFieldStart("weathers"); g.flush(); Iterator<IAceBaseComponent> i; List<IAceBaseComponent...
java
@Override public Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages); if (beanDefinitions.isEmpty()) { logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check ...
python
def to_dict(self): '''Save this configuration set into a dictionary.''' d = {'id': self.id} data = [] for c in self._config_data: data.append(c.to_dict()) if data: d['configurationData'] = data return d
java
public static double pbarVariance(double pbar, int sampleN, int populationN) { if(populationN<=0 || sampleN<=0 || sampleN>populationN) { throw new IllegalArgumentException("All the parameters must be positive and sampleN smaller than populationN."); } double f = (double)sampleN/popul...
python
def __encodeMultipart(self, fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ ...
python
def PriceHourly(self): """Returns the total hourly price for the server. Sums unit prices with unit volumes. >>> clc.v2.Server("NY1BTDIPHYP0101").PriceHourly() 0.02857 """ units = self.PriceUnits() return(units['cpu']*self.cpu+units['memory']*self.memory+units['storage']*self.storage+units['managed_o...
java
@Override protected void initializeImpl() { //create properties from configuration (all javax mail properties will be defined in the fax4j properties) this.mailConnectionProperties=new Properties(); Map<String,String> configuration=this.factoryConfigurationHolder.getConfiguration(); ...
java
void applyAttachment() { if (body == null || staticLight) return; restorePosition.setToTranslation(bodyPosition); rotateAroundZero.setToRotationRad(bodyAngle + bodyAngleOffset); for (int i = 0; i < rayNum; i++) { tmpVec.set(startX[i], startY[i]).mul(rotateAroundZero).mul(restorePosition); startX[i] = t...
java
public Object postRequest(String restUrl, Map<String, String> params) throws IOException, WebServiceException { return this.postRequest(HttpMethod.POST, restUrl, params); }
python
def register(self, numerics_alert): """Register an alerting numeric event. Args: numerics_alert: An instance of `NumericsAlert`. """ key = (numerics_alert.device_name, numerics_alert.tensor_name) if key in self._data: self._data[key].add(numerics_alert) else: if len(self._data...
python
def area_exists(self, area_uuid): """ Check if an Upload Area exists :param str area_uuid: A RFC4122-compliant ID for the upload area :return: True or False :rtype: bool """ response = requests.head(self._url(path="/area/{id}".format(id=area_uuid))) retur...
python
def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
java
public char getReturnKey() { String value = Optional.fromNullable(getParameter(SignalParameters.RETURN_KEY.symbol())).or(""); return value.isEmpty() ? ' ' : value.charAt(0); }
python
def publish(self, load): ''' Publish "load" to minions ''' payload = {'enc': 'aes'} crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value) payload['load'] = crypticle.dumps(load) if self.opts['sign_pub_messages']: ...
python
def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +N...