language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public AlgoResponse pipe(Object input) throws APIException { if (input instanceof String) { return pipeRequest((String)input,ContentType.Text); } else if (input instanceof byte[]) { return pipeBinaryRequest((byte[])input); } else { return pipeRequest(gson.toJs...
java
static String getArrayElementStringValue(Node n) { return (NodeUtil.isNullOrUndefined(n) || n.isEmpty()) ? "" : getStringValue(n); }
java
public Collection<Monitor> list(String name, String type) { return list(name, type, 0, -1); }
python
def output(self) -> None: """Pretty print travel times.""" print("%s - %s" % (self.station, self.now)) print(self.products_filter) for j in sorted(self.journeys, key=lambda k: k.real_departure)[ : self.max_journeys ]: print("-------------") pr...
java
@Override public EClass getFile() { if (fileEClass == null) { fileEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(47); } return fileEClass; }
java
public synchronized void updateMasterConf(PropertyKey key, @Nullable String value) { mMasters.forEach(master -> master.updateConf(key, value)); }
python
def change_return_type(f): """ Converts the returned value of wrapped function to the type of the first arg or to the type specified by a kwarg key return_type's value. """ @wraps(f) def wrapper(*args, **kwargs): if kwargs.has_key('return_type'): return_type = kwargs['return_...
python
def _legacy_api_registration_check(self): ''' Check registration status through API ''' logger.debug('Checking registration status...') machine_id = generate_machine_id() try: url = self.api_url + '/v1/systems/' + machine_id net_logger.info("GET %s...
python
def _cnvkit_fix(cnns, background_cnn, items, ckouts): """Normalize samples, correcting sources of bias. """ return [_cnvkit_fix_base(cnns, background_cnn, items, ckouts)]
python
def write_output(self): """Write all stored output data to storage.""" for data in self.output_data.values(): self.create_output(data.get('key'), data.get('value'), data.get('type'))
python
def to_utf8(self, data): """ Convert unicode values to strings even if they belong to lists or dicts. :param data: an object. :return: The object with all unicode values converted to string. """ # if this is a unicode string, return its string representation if is...
java
public PersistentTranId getPersistentTranId() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(this, tc, "getPersistentTranId"); SibTr.exit(this, tc, "getPersistentTranId", "return="+_ptid); } return _ptid; }
python
def load(self): """Load proxy list from configured proxy source""" self._list = self._source.load() self._list_iter = itertools.cycle(self._list)
python
def init(**kw): """ Initialize an instance of :class:`fedmsg.core.FedMsgContext`. The config is loaded with :func:`fedmsg.config.load_config` and updated by any keyword arguments. This config is used to initialize the context object. The object is stored in a thread local as :data:`fedmsg.__l...
java
@Override public void contains(JsonElement expectedJson) { assertTrue("Expected to find " + GSON.toJson(expectedJson), checkContains(expectedJson)); }
java
public void setAWSAccountIds(java.util.Collection<String> aWSAccountIds) { if (aWSAccountIds == null) { this.aWSAccountIds = null; return; } this.aWSAccountIds = new com.amazonaws.internal.SdkInternalList<String>(aWSAccountIds); }
python
def _listdir(self, root): "List directory 'root' appending the path separator to subdirs." res = [] for name in os.listdir(root): path = os.path.join(root, name) if os.path.isdir(path): name += os.sep res.append(name) return res
python
def send_request(req_cat, con, req_str, kwargs): """ Sends request to facebook graph Returns the facebook-json response converted to python object """ try: kwargs = parse.urlencode(kwargs) #python3x except: kwargs = urllib.urlencode(kwargs) #python2x ...
java
public java.util.List<String> getApprovedPatches() { if (approvedPatches == null) { approvedPatches = new com.amazonaws.internal.SdkInternalList<String>(); } return approvedPatches; }
java
public static <T> Set<T> toSet(Enumeration<T> self) { Set<T> answer = new HashSet<T>(); while (self.hasMoreElements()) { answer.add(self.nextElement()); } return answer; }
java
public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> listRemoteLoginInformationNextWithServiceResponseAsync(final String nextPageLink) { return listRemoteLoginInformationNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<RemoteLoginInformationInner>>, Observ...
java
@NonNull public static CreateTypeStart createType(@Nullable String keyspace, @NonNull String typeName) { return createType( keyspace == null ? null : CqlIdentifier.fromCql(keyspace), CqlIdentifier.fromCql(typeName)); }
python
def SetValue(self, value, raise_on_error=True): """Receives a value and fills it into a DataBlob. Args: value: value to set raise_on_error: if True, raise if we can't serialize. If False, set the key to an error string. Returns: self Raises: TypeError: if the value can...
java
@Override public synchronized void reset() throws IOException { try { this.digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { /* * Not much to do here. We know the algorithm existed when we created the initial MessageDigest in the ...
python
def _coords_conv(self, pos): """For Svg coordinate system, reflect over X axis and translate from center to top-left """ px = (self.original_size[0] / 2 + pos[0]) * self.scale_factor py = (self.original_size[1] / 2 - pos[1]) * self.scale_factor return round(px, 2), round(...
python
def _ScopesFromMetadataServer(self, scopes): """Returns instance scopes based on GCE metadata server.""" if not util.DetectGce(): raise exceptions.ResourceUnavailableError( 'GCE credentials requested outside a GCE instance') if not self.GetServiceAccount(self.__servic...
python
def sfiles_to_event(sfile_list): """ Write an event.dat file from a list of Seisan events :type sfile_list: list :param sfile_list: List of s-files to sort and put into the database :returns: List of tuples of event ID (int) and Sfile name """ event_list = [] sort_list = [(readheader(s...
java
public RecordType getOrCreateRecordType(Map<String, SoyType> fields) { return recordTypes.intern(RecordType.of(fields)); }
python
def emit(self, record): """ Override emit() method in handler parent for sending log to RESTful API """ pid = os.getpid() if pid != self.pid: self.pid = pid self.logs = [] self.timer = self._flushAndRepeatTimer() atexit.reg...
java
@Override public CPMeasurementUnit findByUuid_C_First(String uuid, long companyId, OrderByComparator<CPMeasurementUnit> orderByComparator) throws NoSuchCPMeasurementUnitException { CPMeasurementUnit cpMeasurementUnit = fetchByUuid_C_First(uuid, companyId, orderByComparator); if (cpMeasurementUnit != null)...
python
def _count_spaces_startswith(line): ''' Count the number of spaces before the first character ''' if line.split('#')[0].strip() == "": return None spaces = 0 for i in line: if i.isspace(): spaces += 1 else: return spaces
python
def get_attachments(self, ids, attachment_ids, include_fields=None, exclude_fields=None): """ Wrapper for Bug.attachments. One of ids or attachment_ids is required :param ids: Get attachments for this bug ID :param attachment_ids: Specific attachment ID to get ...
python
def set_boolean(self, option, value): """Set a boolean option. Args: option (str): name of option. value (bool): value of the option. Raises: TypeError: Value must be a boolean. """ if not isinstance(value, bool): ...
java
static final Properties getProperties(final KunderaMetadata kunderaMetadata, final String persistenceUnit) { PersistenceUnitMetadata persistenceUnitMetadatata = kunderaMetadata.getApplicationMetadata() .getPersistenceUnitMetadata(persistenceUnit); Properties props = persistenceUnitMe...
java
public static <T extends Throwable> void printHistory(final String message, T th, final Logger logger) { printHistory(new CouldNotPerformException(message, th), logger, LogLevel.ERROR); }
java
public static String getMessageLogLevel(final int level, final String defLevel) { switch (level) { case (Constants.ERR_LEVEL): return Constants.MSG_ERR; case (Constants.DEBUG_LEVEL): return Constants.MSG_DEBUG; case (Constants.INFO_LEVEL): ...
python
def parse(self, data): """ Converts a dict representing an OLSR 0.6.x topology to a NetworkX Graph object, which is then returned. Additionally checks for "config" data in order to determine version and revision. """ graph = self._init_graph() if 'topology' not in...
java
public void updateDrawableState(int state, boolean flag) { final int oldState = mCombinedState; // Update the combined state flag if (flag) mCombinedState |= state; else mCombinedState &= ~state; // Set the combined state if (oldState != mCombinedState) { set...
java
public static Connection newInstance(Connection conn) { return (Connection) java.lang.reflect.Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[]{Connection.class}, new ConnectionProxy(conn)); /* return (Connection) java.lang.reflect.Proxy.newProxyInstance(conn....
python
def one_point_crossover(parents): """Perform one point crossover on two parent chromosomes. Select a random position in the chromosome. Take genes to the left from one parent and the rest from the other parent. Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child = xxyyy """ # The po...
java
protected <T> CompletionStage<Optional<T>> doWithServiceImpl(String name, Descriptor.Call<?, ?> serviceCall, Function<URI, CompletionStage<T>> block) { return locate(name, serviceCall).thenCompose(uri -> { return uri .map(u -> block.apply(u).thenApply(Optional::of)) ...
python
def get_index(self, value): """ Return the index (or indices) of the given value (or values) in `state_values`. Parameters ---------- value Value(s) to get the index (indices) for. Returns ------- idx : int or ndarray(int) ...
java
private static void addLong(long input, int count, int startPos, byte[] dest) { if(DEBUG_LEV > 30) System.err.println("EncodedElement::addLong : Begin"); int currentByte = startPos/8; int currentOffset = startPos%8; int bitRoom;//how many bits can be placed in current byte long upMask;//to cle...
python
def plot_kde(self, ax=None, amax=None, amin=None, label=None, return_fig=False): """ Plot a KDE for the curve. Very nice summary of KDEs: https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ ...
java
public void delete_device_attribute_property(Database database, String deviceName, DbAttribute[] attribute) throws DevFailed { for (DbAttribute att : attribute) delete_device_attribute_property(database, deviceName, att.name, att.get_property_list()); } //===...
java
@Override protected int handlePrevious(int position) { if (pattern_.CELength_ == 0) { search_.matchedIndex_ = search_.matchedIndex_ == DONE ? getIndex() : search_.matchedIndex_; if (search_.matchedIndex_ == search_.beginIndex()) { setMatchNotFound(...
python
def _get_traversal_children(self, name): """ Retrieve component and subcomponent indexes from the given traversal path (e.g. PID_1_2 -> component=2, subcomponent=None) """ name = name.upper() parts = name.split('_') try: assert 3 <= len(parts) <= 4 ...
java
public Upload upload(final PutObjectRequest putObjectRequest) throws AmazonServiceException, AmazonClientException { return doUpload(putObjectRequest, null, null, null); }
python
def transform_index_to_physical_point(image, index): """ Get spatial point from index of an image. ANTsR function: `antsTransformIndexToPhysicalPoint` Arguments --------- img : ANTsImage image to get values from index : list or tuple or numpy.ndarray location in image ...
python
def clear_published_date(self): """Removes the puiblished date. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid...
java
public static String getStatusAsString(int status) { if (status == STATUS_PENDING) { return "PENDING"; } else if (status == STATUS_ACTIVE) { return "ACTIVE"; } else if (status == STATUS_DONE) { return "DONE"; } else if (status == STATUS_FAILED) { return "FAILED"; } else if (status == STATUS_SUS...
java
@Override protected <T> T parseEntity(Class<T> entityClass, HttpResponse httpResponse) throws IOException { return GSON.fromJson(new InputStreamReader(httpResponse.getEntity().getContent()), entityClass); }
java
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (CollectionUtils.isNotEmpty(annotations)) { Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Interceptor.class); try { parseInterceptors(element...
java
@Override public CreateEgressOnlyInternetGatewayResult createEgressOnlyInternetGateway(CreateEgressOnlyInternetGatewayRequest request) { request = beforeClientExecution(request); return executeCreateEgressOnlyInternetGateway(request); }
java
public static synchronized XMLEventReader createStringReader(final String paramString) throws IOException, XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); final InputStream in = new ByteArrayInpu...
java
public static TokenRegex compile(String pattern) throws ParseException { ExpressionIterator p = QueryToPredicate.PARSER.parse(pattern); Expression exp; TransitionFunction top = null; while ((exp = p.next()) != null) { if (top == null) { top = consumerize(exp); } els...
java
public List<String> asMulti() { if (values.isEmpty()) { return Collections.emptyList(); } List<String> multi = new ArrayList<String>(values.size()); for (JsonValue value : values) { if (value.isNull()) { multi.add(""); continue; } Object obj = value.getValue(); if (obj != null) { mu...
java
private JPanel getPDBFilePanel(int pos ,JTextField f, JTextField c){ JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createLineBorder(Color.black)); JLabel l01 = new JLabel("PDB code "); panel.add(l01); Box hBox11 = Box.createHorizontalBox(); JLabel l11 = new JLabel(pos + ":"); f.setMa...
java
public static synchronized void chdir(String path) { if (path != null) { rootDir = new File(getAbsolutePath(path)).getAbsolutePath(); } }
python
def on_sigint(self, sig, frame): """ We got SIGINT signal. """ if self.stop_requested or self.stop_requested_force: # signal has already been sent or we force a shutdown. # handles the keystroke 2x CTRL+C to force an exit. self.stop_requested_force = ...
java
public static void addExtendedProperty(String propName, String dataType, boolean multiValued, Object defaultValue) { if (dataType == null || "null".equalsIgnoreCase(dataType)) return; if (extendedPropertiesDataType.containsKey(propName)) { Tr.warning(tc, WIMMessageKey.DUPLICATE_...
java
public void setUserPassword(String password) { try { getSipURI().setUserPassword(password); } catch (ParseException e) { logger.error("error setting parameter ", e); throw new IllegalArgumentException("Bad arg", e ); } }
java
public static void addSuccessAndErrorConditionsAndActions(final JpaRolloutGroup group, final RolloutGroupConditions conditions) { addSuccessAndErrorConditionsAndActions(group, conditions.getSuccessCondition(), conditions.getSuccessConditionExp(), conditions.getSuccessAction(), condit...
java
protected TupleWritable createInternalValue() { Writable[] vals = new Writable[kids.length]; for (int i = 0; i < vals.length; ++i) { vals[i] = kids[i].createValue(); } return new TupleWritable(vals); }
python
def is_local(self): """Return true is the partition file is local""" from ambry.orm.exc import NotFoundError try: if self.local_datafile.exists: return True except NotFoundError: pass return False
java
public void setMaxHeaderTableSize(ByteBuf out, long maxHeaderTableSize) throws Http2Exception { if (maxHeaderTableSize < MIN_HEADER_TABLE_SIZE || maxHeaderTableSize > MAX_HEADER_TABLE_SIZE) { throw connectionError(PROTOCOL_ERROR, "Header Table Size must be >= %d and <= %d but was %d", ...
python
def variance(arg, where=None, how='sample'): """ Compute standard deviation of numeric array Parameters ---------- how : {'sample', 'pop'}, default 'sample' Returns ------- stdev : double scalar """ expr = ops.Variance(arg, how, where).to_expr() expr = expr.name('var') ...
java
public javax.sip.address.SipURI createRecordRouteURI(boolean usePublicAddress) { try { String host = getIpAddress(usePublicAddress); SipURI sipUri = SipFactoryImpl.addressFactory.createSipURI(null, host); sipUri.setPort(port); sipUri.setTransportParam(transport); // Do we want to add an ID here? ...
java
public ResourceImpl getSubResource(String name, Object parameter) { SubResourceGetterModel getter = resourceModel.getSubResourceGetter(name); if (getter == null) { throw new UnsupportedOperationException( "No sub-resource named " + name); } ...
java
public void init(Record record, int iLastModifiedToSet, boolean bStart, boolean bEnd) { super.init(record, null, null, null, null, null, null); this.setInitialKey(bStart); this.setEndKey(bEnd); m_iLastModifiedToSet = iLastModifiedToSet; }
java
public final Promise clean(String match) { ScanArgs args = new ScanArgs(); args.limit(100); boolean singleStar = match.indexOf('*') > -1; boolean doubleStar = match.contains("**"); if (doubleStar) { args.match(match.replace("**", "*")); } else if (singleStar) { if (match.length() > 1 && match....
python
def prepare_amazon_algorithm_estimator(estimator, inputs, mini_batch_size=None): """ Set up amazon algorithm estimator, adding the required `feature_dim` hyperparameter from training data. Args: estimator (sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase): An estimator for a b...
java
public T acquire() { if (closed) { throw new IllegalStateException("pool closed"); } T reference = pool.poll(); if (reference == null) { reference = factory.createReference(this); } reference.acquire(); return reference; }
java
private <T extends Property> Map<String, String> getOverriddenImplementationConfiguration( Collection<T> overridableProperties) { Map<String, String> ret = new HashMap<>(); overridableProperties.forEach(p -> { String val = getProperty(p, null); if (val != null) { ...
java
@Override public void addComments(ExecutableElement property, Content propertyDocTree) { TypeElement holder = (TypeElement)property.getEnclosingElement(); if (!utils.getFullBody(property).isEmpty()) { if (holder.equals(typeElement) || (!utils.isPublic(holder) || utils...
java
static final int coupon16(final byte[] identifier) { final long[] hash = MurmurHash3.hash(identifier, SEED); final int hllIdx = (int) (((hash[0] >>> 1) % 1024) & TEN_BIT_MASK); //hash[0] for 10-bit address final int lz = Long.numberOfLeadingZeros(hash[1]); final int value = (lz > 62 ? 62 : lz) + 1; ...
java
public void saveTxt(String file) throws Exception { FileOutputStream fos = new FileOutputStream(file); BufferedWriter bout = new BufferedWriter(new OutputStreamWriter( fos, "UTF8")); bout.write(this.toString()); bout.close(); }
python
def folderitem(self, obj, item, index): """Applies new properties to the item (Batch) that is currently being rendered as a row in the list :param obj: client to be rendered as a row in the list :param item: dict representation of the batch, suitable for the list :param index: c...
java
public void marshall(GetSubscriptionStateRequest getSubscriptionStateRequest, ProtocolMarshaller protocolMarshaller) { if (getSubscriptionStateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { } catch (Exception e) { ...
java
public static List<String> replaceNullValueWithEmptyGroup(@Nonnull final List<String> groups) { Check.notNull(groups, "groups"); final List<String> result = new ArrayList<String>(groups.size()); for (final String group : groups) { if (group == null) { result.add(EMPTY_GROUP); } else { result.add(gr...
python
def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False): """Return dict of response received from Twitter's API :param endpoint: (required) Full url or Twitter API endpoint (e.g. search/tweets) :type endpoint: string :param meth...
python
def is_ssh_available(host, port=22): """ checks if ssh port is open """ s = socket.socket() try: s.connect((host, port)) return True except: return False
java
@Override public int compareTo(Instant otherInstant) { int cmp = Long.compare(seconds, otherInstant.seconds); if (cmp != 0) { return cmp; } return nanos - otherInstant.nanos; }
python
def reset_network(message): """Resets the users network to make changes take effect""" for command in settings.RESTART_NETWORK: try: subprocess.check_call(command) except: pass print(message)
python
def which_api_version(self, api_call): """ Return QualysGuard API version for api_call specified. """ # Leverage patterns of calls to API methods. if api_call.endswith('.php'): # API v1. return 1 elif api_call.startswith('api/2.0/'): # API v2....
java
public boolean hasProperty(String category, String key) { return this.categories.containsKey(category) && this.categories.get(category).containsKey(key); }
java
public static JavaRDD<String> listPaths(JavaSparkContext sc, String path, boolean recursive) throws IOException { //NativeImageLoader.ALLOWED_FORMATS return listPaths(sc, path, recursive, (Set<String>)null); }
java
public Observable<Page<JobVersionInner>> listByJobNextAsync(final String nextPageLink) { return listByJobNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<JobVersionInner>>, Page<JobVersionInner>>() { @Override public Page<JobVersionInner>...
java
public void marshall(Type type, ProtocolMarshaller protocolMarshaller) { if (type == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(type.getName(), NAME_BINDING); protocolMarshaller.marsh...
python
def play(self, source, *, after=None): """Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stop...
java
public static byte[] getQualifier(final int level, final int order) { final byte[] suffix = (level + ":" + order).getBytes(CHARSET); final byte[] qualifier = new byte[RULE_PREFIX.length + suffix.length]; System.arraycopy(RULE_PREFIX, 0, qualifier, 0, RULE_PREFIX.length); System.arraycopy(suffix, 0, qual...
python
def strace_data_access_event(self, operation, address, data, data_mask=None, access_width=4, address_range=0): """...
python
def get_extension_classes(sort, extra_extension_paths=None): """ Banana banana """ all_classes = {} deps_map = {} for entry_point in pkg_resources.iter_entry_points( group='hotdoc.extensions', name='get_extension_classes'): if entry_point.module_name == 'hotdoc_c_extension.e...
python
def copy_files(src, ext, dst): """ Copies files with extensions "ext" from "src" to "dst" directory. """ src_path = os.path.join(os.path.dirname(__file__), src) dst_path = os.path.join(os.path.dirname(__file__), dst) file_list = os.listdir(src_path) for f in file_list: if f == '__init__.py'...
java
@Override public final synchronized List<TrialBalanceLine> retrieveTrialBalance( final Map<String, Object> pAddParam, final Date pDate) throws Exception { recalculateAllIfNeed(pAddParam, pDate); List<TrialBalanceLine> result = new ArrayList<TrialBalanceLine>(); String query = evalQueryBalance(pA...
java
private static void checkMandatoryProperties( final Analyzer analyzer, final Jar jar, final String symbolicName ) { final String importPackage = analyzer.getProperty( Analyzer.IMPORT_PACKAGE ); if( im...
java
@CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> flatMapSingleElement(final Function<? super T, ? extends SingleSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new MaybeFlatMapSingleElement<...
python
def init_config(self, app): """Initialize configuration. :param app: An instance of :class:`~flask.Flask`. """ app.config.setdefault('REQUIREJS_BASEURL', app.static_folder) app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder) app.config.setdefault('COLLECT_STO...
python
def _list_linodes(full=False): ''' Helper function to format and parse linode data ''' nodes = _query('linode', 'list')['DATA'] ips = get_ips() ret = {} for node in nodes: this_node = {} linode_id = six.text_type(node['LINODEID']) this_node['id'] = linode_id ...
python
def get_vehicle_health_report(session, vehicle_index): """Get complete vehicle health report.""" profile = get_profile(session) _validate_vehicle(vehicle_index, profile) return session.get(VHR_URL, params={ 'uuid': profile['vehicles'][vehicle_index]['uuid'] }).json()