language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public OvhNetbootOption serviceName_boot_bootId_option_option_GET(String serviceName, Long bootId, net.minidev.ovh.api.dedicated.server.OvhBootOptionEnum option) throws IOException { String qPath = "/dedicated/server/{serviceName}/boot/{bootId}/option/{option}"; StringBuilder sb = path(qPath, serviceName, bootId, o...
java
public static <T extends Comparable<T>> List<T> sorted(Iterable<T> items) { List<T> result = toList(items); Collections.sort(result); return result; }
java
public static Form form() { return Form.create() .with(defaultNameField()) .url() .with(Text.of("user").label("User").length(16).optional()) .with(Password.of("password").label("Password").length(40).optional()); }
java
@Override public final Iterable<NoteDocument> findAll( final RootDocument rootDocument) { final Iterable<NoteDocument> noteDocuments = findAll(rootDocument.getFilename()); if (noteDocuments == null) { return null; } for (final NoteDocument note...
python
def _apply_nested_privacy(self, data): """ Apply privacy to nested documents. :param data: Dict of data to which privacy is already applied. """ kw = { 'is_admin': self.is_admin, 'drop_hidden': self.drop_hidden, } for key, val in data.items(): ...
python
def criteria_extract(crit_file='criteria.txt', output_file='criteria.xls', output_dir_path='.', input_dir_path='', latex=False): """ Extracts criteria from a MagIC 3.0 format criteria.txt file. Default output format is an Excel file. typeset with latex on your own computer. Pa...
java
public void inherit(DocFinder.Input input, DocFinder.Output output) { ClassDoc exception; if (input.tagId == null) { ThrowsTag throwsTag = (ThrowsTag) input.tag; exception = throwsTag.exception(); input.tagId = exception == null ? throwsTag.exceptionNa...
java
@Override public void setListProperty(String propertyName, List<String> values) { setProperty(propertyName, values); }
java
public final EObject ruleXConstructorCall() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token otherlv_3=null; Token otherlv_5=null; Token otherlv_7=null; Token lv_explicitConstructorCall_8_0=null; Token otherlv_11=null; Tok...
java
public JarSignerRequest createVerifyRequest( File jarFile, boolean certs ) { JarSignerVerifyRequest request = new JarSignerVerifyRequest(); request.setCerts( certs ); request.setWorkingDirectory( workDirectory ); request.setMaxMemory( getMaxMemory() ); request.setVerbose( isV...
java
private static String getUserInfo(String url) { String userInfo = null; int startIndex = Integer.MIN_VALUE; int nextSlashIndex = Integer.MIN_VALUE; int endIndex = Integer.MIN_VALUE; try { // The user info start index should be the first index of "//". startIndex = url.indexOf("//"); ...
python
def segments(self): """ A list of `Segment` objects. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute. """ segments = [] for label, slc in zip(self....
java
public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { LOGGER.trace("copy(InputStream, OutputStream)"); copy(inputStream, outputStream, new byte[BUFFER_SIZE]); }
python
def setModel(self, model): """sets the model for the auto parameters :param model: The data stucture for this editor to provide access to :type model: :class:`QAutoParameterModel<sparkle.gui.stim.qauto_parameter_model.QAutoParameterModel>` """ self.paramList.setModel(model) ...
java
public MapBuilder<K, V> putAll(Map<K, V> map) { this.map.putAll(map); return this; }
java
public int getNumWeights() { if (weights == null) return 0; int numWeights = 0; for (double[] wts : weights) { numWeights += wts.length; } return numWeights; }
python
def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), ...
java
@Override public RecordReader<Key, Value> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { return new MasterTextRecordReader(); }
java
@Override public void save(INDArray save, String id) throws SQLException, IOException { doSave(save, id); }
java
private void put(Object obj, XmlParser.Node node) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { if (!(obj instanceof Map)) throw new IllegalArgumentException("Object for put is not a Map: " + obj); Map map = (Map...
java
private void createColumnFamilies(List<TableInfo> tableInfos, KsDef ksDef) throws Exception { for (TableInfo tableInfo : tableInfos) { if (isCql3Enabled(tableInfo)) { createOrUpdateUsingCQL3(tableInfo, ksDef); createIndexUsingCql(tableInfo); ...
java
protected void removeFromCache(String cacheName, String key) { try { ICache cache = getCache(cacheName); if (cache != null) { cache.delete(key); } } catch (CacheException e) { LOGGER.warn(e.getMessage(), e); } }
java
public ProcessAdapter execute(Class<?> type, String... args) { return execute(FileSystemUtils.WORKING_DIRECTORY, type, args); }
python
def obsolete_client(func): """This is a decorator which can be used to mark Client classes as obsolete. It will result in an error being emitted when the class is instantiated.""" @functools.wraps(func) def new_func(*args, **kwargs): raise ObsoleteException( "{} has been removed...
python
def group_by_day(self): """Return a dictionary of this collection's values grouped by each day of year. Key values are between 1-365. """ hourly_data_by_day = OrderedDict() for d in xrange(1, 366): hourly_data_by_day[d] = [] a_per = self.header.analysis_perio...
java
public static double computeTauAndDivideRow( final int blockLength , final DSubmatrixD1 Y , final int row , int colStart , final double max ) { final int height = Math.min(blockLength , Y.row1-Y.row0); fin...
python
def process_list_arg(arg): """ Parse a string into a list separated by commas with whitespace stripped """ if isinstance(arg, list): return arg elif isinstance(arg, basestring): args = [] for part in arg.split(","): args.append(part.strip()) return args
java
protected void buildFieldList(final String field, final List<String> fieldList) { if(Utils.isEmpty(field)) { return; } if(!fieldList.contains(field)) { fieldList.add(field); } String plainField = String.valueOf(field); ...
python
def index_open(index, allow_no_indices=True, expand_wildcards='closed', ignore_unavailable=True, hosts=None, profile=None): ''' .. versionadded:: 2017.7.0 Open specified index. index Index to be opened allow_no_indices Whether to ignore if a wildcard indices expression resolves int...
python
def code(item): """ Turn a NameID class instance into a quoted string of comma separated attribute,value pairs. The attribute names are replaced with digits. Depends on knowledge on the specific order of the attributes for the class that is used. :param item: The class instance :return: A q...
java
public Observable<Page<SyncMemberInner>> listBySyncGroupAsync(final String resourceGroupName, final String serverName, final String databaseName, final String syncGroupName) { return listBySyncGroupWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName) .map(new Func1<Se...
python
def syncItems(self, client=None, clientId=None): """ Returns an instance of :class:`plexapi.sync.SyncList` for specified client. Parameters: client (:class:`~plexapi.myplex.MyPlexDevice`): a client to query SyncItems for. clientId (str): an identifier of a client to ...
python
def __protocolize(base_url): """Internal add-protocol-to-url helper""" if not base_url.startswith("http://") and not base_url.startswith("https://"): base_url = "https://" + base_url # Some API endpoints can't handle extra /'s in path requests base_url = base_url.rstrip("/")...
python
def fetchmany(self,size=-1): """ return a sequential set of records. This is guaranteed by locking, so that no other thread can grab a few records while a set is fetched. this has the side effect that other threads may have to wait for an arbitrary long time for the completion of the curre...
java
@Override public boolean supportsNativeRotation() { return this.params.useNativeAngle && (this.params.serverType == WmsLayerParam.ServerType.MAPSERVER || this.params.serverType == WmsLayerParam.ServerType.GEOSERVER); }
python
def extractRecord(resolver, name, answers, level=10): ''' This method is copy-pasted from twisted.names.common. The difference with the original is, that it favors IPv4 responses over IPv6. This is motivated by the problem of resolving "maps.googleapis.com" name, which has both types of entries. ...
python
def stop_video(self, tick): """Stop video if tick is more than the end, only for last file. Parameters ---------- tick : int time in ms from the beginning of the file useless? """ if self.cnt_video == self.n_video: if tick >= self.end_dif...
java
public static String buildCleanedParametersURIRepresentation(org.apache.commons.httpclient.URI uri, SpiderParam.HandleParametersOption handleParameters, boolean handleODataParametersVisited) throws URIException { // If the option is set to use all the information, just use the default string representation if (h...
python
def stop_service(self, instance, service): """ Stops a single service. :param str instance: A Yamcs instance name. :param str service: The name of the service. """ req = rest_pb2.EditServiceRequest() req.state = 'stopped' url = '/services/{}/{}'.format(in...
java
public static String getRandomFilename(final String prefix) { final Random rnd = new Random(); final StringBuilder stringBuilder = new StringBuilder(prefix); for (int i = 0; i < RANDOM_FILE_NAME_LENGTH; i++) { stringBuilder.append(ALPHABET[rnd.nextInt(ALPHABET.length)]); } return stringBuilder.toString()...
java
void setMarshaledContext(ContextItems marshaledContext, boolean commit, ISurveyCallback callback) { ISurveyResponse response = new SurveyResponse(); Iterator<IManagedContext<?>> iter = managedContexts.iterator(); setMarshaledContext(marshaledContext, iter, response, __ -> { if (comm...
python
def _writable_required(self, path): # type: (Text) -> FS """Check that ``path`` is writeable. """ if self.write_fs is None: raise errors.ResourceReadOnly(path) return self.write_fs
java
@Nullable final Permutation calculatePermutation( @Nonnull final TreeLogger logger, @Nonnull final LinkerContext context, @Nonnull final ArtifactSet artifacts ) throws UnableToCompleteException { Permutation permutation = nu...
java
@Override public void set(int index, byte[] data, long scn) throws Exception { if(data == null) { set(index, data, 0, 0, scn); } else { set(index, data, 0, data.length, scn); } }
java
public synchronized void abortTransaction() throws TransactionNotInProgressException { if(isInTransaction()) { fireBrokerEvent(BEFORE_ROLLBACK_EVENT); setInTransaction(false); clearRegistrationLists(); referencesBroker.removePrefetchingListeners(); ...
java
public URL getResource(String path) throws MalformedURLException { Result<URL,MalformedURLException> result = getResourceCache.get(path, getResourceRefresher); MalformedURLException exception = result.getException(); if(exception != null) throw exception; return result.getValue(); }
python
def remove_negativescores_nodes(self): """\ if there are elements inside our top node that have a negative gravity score, let's give em the boot """ gravity_items = self.parser.css_select(self.top_node, "*[gravityScore]") for item in gravity_items: sco...
java
@Override public final boolean removeAttribute(Object key, Object value) { return attributes.removeAttribute(this, key, value); }
python
def distance(self, host): """ Checks if ``predicate(host)``, then returns :attr:`~HostDistance.IGNORED` if falsey, and defers to the child policy otherwise. """ if self.predicate(host): return self._child_policy.distance(host) else: return ...
python
def load_all_yamls(cls, directories): """Loads yaml files from all given directories. Args: directories: list of directories to search Returns: dict of {fullpath: loaded_yaml_structure} """ yaml_files = [] loaded_yamls = {} for d in direc...
java
@Override public Device get(String deviceId) { DBCursor devices = devicesCollection().find(new BasicDBObject(ImmutableMap.of("deviceId", deviceId))); if(devices.hasNext()) { return dbObjectToDevice(devices.next()); } return null; }
java
protected JmsJcaSession createJcaSession(boolean transacted) throws JMSException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "createJcaSession", transacted); JmsJcaSession jcaSess = null; // If we have a JCA connection, then make a JCA se...
java
@Api public void addButton(String layerId, ToolStripButton button, int position) { extraButtons.add(new ExtraButton(constructIdSaveLayerId(layerId), button, position)); }
python
def readinto(self, data): """Read data from the ring buffer into a user-provided buffer. This advances the read index after reading; calling :meth:`advance_read_index` is *not* necessary. :param data: The memory where the data should be stored. :type data: CData pointer or buff...
python
def create_session( self, kind: SessionKind, proxy_user: str = None, jars: List[str] = None, py_files: List[str] = None, files: List[str] = None, driver_memory: str = None, driver_cores: int = None, executor_memory: str = None, executor_cor...
python
def fetch(self, url, path): """ Downloads the given url. :param url: The url to be downloaded. :type url: String :param path: The directory path to where the image should be stored :type path: String :param filename: ...
python
def run_models(self): """ Run all models. Returns ------- model Best model dict Metrics of the models """ self.linear_regression() self.lasso_regression() self.ridge_regression() self.elastic_net_regression() ...
java
@SuppressWarnings("unchecked") public static <T> Parcelable wrap(T input) { if(input == null){ return null; } return wrap(input.getClass(), input); }
python
def connect(self, devicelist, calibration=True): """Establish a connection to one or more SK8 devices. Given a list of 1 or more :class:`ScanResult` objects, this method will attempt to create a connection to each SK8 in sequence. It will return when all connections have been attempted,...
python
async def take(self, tube, timeout=None): """ Get a task from queue for execution. Waits `timeout` seconds until a READY task appears in the queue. If `timeout` is `None` - waits forever. Returns tarantool tuple object. """ cmd = tube.cmd("take") args = ...
java
@Autowired(required = false) public void setDataExporters(Collection<IDataExporter<? extends Object>> dataExporters) { this.dataExporters = dataExporters; }
java
public CMAAsset create(String spaceId, String environmentId, CMAAsset asset) { assertNotNull(spaceId, "spaceId"); assertNotNull(environmentId, "environmentId"); assertNotNull(asset, "asset"); final String assetId = asset.getId(); final CMASystem sys = asset.getSystem(); asset.setSystem(null); ...
java
@Deprecated @Internal public <R, ACC> SingleOutputStreamOperator<R> fold( ACC initialValue, FoldFunction<T, ACC> foldFunction, ProcessWindowFunction<ACC, R, K, W> windowFunction, TypeInformation<ACC> foldResultType, TypeInformation<R> windowResultType) { if (foldFunction instanceof RichFunction) { ...
python
def remove_listener(self, event, callback, single=None, priority=None): """ Remove the event listener matching the same signature used for adding it. This will remove AT MOST one entry meeting the signature requirements. """ event_stack = self._events[event] for x in event_stack...
java
public ResponseWrapper addChatRoomMember(long roomId, String... members) throws APIConnectionException, APIRequestException { Preconditions.checkArgument(roomId > 0, "room id is invalid"); Preconditions.checkArgument(members != null && members.length > 0, "member should not be empty"); ...
java
protected void rewriteContent(CmsFile file, Collection<CmsRelation> relations) throws CmsException { LOG.info("Rewriting in-content links for " + file.getRootPath()); CmsPair<String, String> contentAndEncoding = decode(file); String content = ""; if (OpenCms.getResourceManager().getRe...
python
def next(self, day_of_week=None): """ Modify to the next occurrence of a given day of the week. If no day_of_week is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired day_of_week, ex. pendulum.MONDAY. ...
python
def parse(self, contents): """Parse the document. :param contents: The text contents of the document. :rtype: a *generator* of tokenized text. """ i = 0 for text in contents.split(self.delim): if not len(text.strip()): continue wor...
java
public void startPart(String contentType) throws IOException { if (inPart) out.write(__CRLF); out.write(__DASHDASH); out.write(boundary); out.write(__CRLF); out.write("Content-Type: "); out.write(contentType); out.write(__CRLF); out.write(__CRL...
python
def migrate_flow_collection(apps, schema_editor): """Migrate 'flow_collection' field to 'entity_type'.""" Process = apps.get_model('flow', 'Process') DescriptorSchema = apps.get_model('flow', 'DescriptorSchema') for process in Process.objects.all(): process.entity_type = process.flow_collection...
python
def _get_address_override(endpoint_type=PUBLIC): """Returns any address overrides that the user has defined based on the endpoint type. Note: this function allows for the service name to be inserted into the address if the user specifies {service_name}.somehost.org. :param endpoint_type: the type ...
java
@Deprecated @PublicEvolving public DataSink<T> sortLocalOutput(String fieldExpression, Order order) { int numFields; int[] fields; Order[] orders; // compute flat field positions for (nested) sorting fields Keys.ExpressionKeys<T> ek = new Keys.ExpressionKeys<>(fieldExpression, this.type); fields = ek.co...
java
public static void addTopologyMaster(Map stormConf, StormTopology ret) { // generate outputs HashMap<String, StreamInfo> outputs = new HashMap<>(); List<String> list = JStormUtils.mk_list(TopologyMaster.FILED_CTRL_EVENT); outputs.put(TOPOLOGY_MASTER_CONTROL_STREAM_ID, Thrift.outputField...
python
def connection(self, shareable=False): """Get a steady, persistent DB-API 2 connection. The shareable parameter exists only for compatibility with the PooledDB connection method. In reality, persistent connections are of course never shared with other threads. """ try:...
java
public CalledRemoteApiCounter increment(String facadeName) { if (facadeName == null) { throw new IllegalArgumentException("The argument 'facadeName' should not be null."); } if (facadeCountMap == null) { facadeCountMap = new LinkedHashMap<String, Integer>(); } ...
python
def port_get_tag(port): ''' Lists tags of the port. Args: port: A string - port name. Returns: List of tags (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_get_tag tap0 ''' cmd = 'o...
python
def check_available(self): """ Check for availability of a service and provide run metrics. """ success = True start_time = datetime.datetime.utcnow() message = '' LOGGER.debug('Checking service id %s' % self.id) try: title = None ...
python
def advection(scalar, wind, deltas): r"""Calculate the advection of a scalar field by the wind. The order of the dimensions of the arrays must match the order in which the wind components are given. For example, if the winds are given [u, v], then the scalar and wind arrays must be indexed as x,y (whi...
java
public static boolean startsWith(final boolean caseSensitive, final CharSequence text, final CharSequence prefix) { if (text == null) { throw new IllegalArgumentException("Text cannot be null"); } if (prefix == null) { throw new IllegalArgumentException("Prefix cannot be...
python
def main(): """ Example of self documenting (of sorts) code, via aikif. Simply call functions like below to build an overview which has metadata automatically updated. """ fldr = mod_cfg.fldrs['program_path'] p = mod_prg.Programs('AIKIF Programs', fldr) document_core_programs(p) do...
python
def read(self, filenames, encoding=None): """Read and parse a filename or a list of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify a list of potential configuration file locations (e.g. current directory, user's home directo...
java
public int update(@NotNull SqlQuery query) { return withCurrentTransaction(query, tx -> { logQuery(query); try (PreparedStatement ps = tx.getConnection().prepareStatement(query.getSql())) { prepareStatementFromQuery(ps, query); long startTime = currentTi...
java
public String getLocalizedResource(String namespace, String resourceId) throws Exception { String resourceValue = ""; Class r = Class.forName(namespace + "$string"); Field f = r.getField(resourceId); resourceValue = getCurrentActivity().getResources().getString(f.getInt(f)); re...
java
@Nullable public Map<Sha256Hash, Integer> getAppearsInHashes() { return appearsInHashes != null ? ImmutableMap.copyOf(appearsInHashes) : null; }
python
def trigger(self, identifier, force=True): """Trigger an upgrade task.""" self.debug(identifier) url = "{base}/{identifier}".format( base=self.local_base_url, identifier=identifier ) param = {} if force: param['force'] = force e...
java
@Override public Collection<Person> findBySurname(final FinderObject owner, final String surname) { final Root root = (Root) owner; final RootVisitor visitor = new RootVisitor(); root.accept(visitor); final List<Person> matches = new ArrayList<>(); for (final Pers...
java
public void writeAttribute(String attributeName, String value) throws IOException { this.attribute(null, attributeName, value); }
python
def _main(): """ CLI interface """ import sys if len(sys.argv) < 2: _usage('Expected at least one parameter!') sc = sys.argv[1] options = sys.argv[2:] if sc == 'a' or sc == 'advertise': if len(options) > 5 or len(options) < 2: _usage() stype,port = options[...
java
public static void permutationVector( DMatrixSparseCSC P , int[] vector) { if( P.numCols != P.numRows ) { throw new MatrixDimensionException("Expected a square matrix"); } else if( P.nz_length != P.numCols ) { throw new IllegalArgumentException("Expected N non-zero elements in pe...
java
public String getDisplayName(ULocale locale) { String dispName = name; try { ResourceBundle bundle = UResourceBundle.getBundleInstance("android.icu.impl.data.HolidayBundle", locale); dispName = bundle.getString(name); } catch (MissingResourceException e) { ...
python
def is_rpm_installed(): """Tests if the rpm command is present.""" try: version_result = subprocess.run(["rpm", "--usage"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) rpm_installed = not version_result.returncod...
java
public long set(long instant, int year) { FieldUtils.verifyValueBounds(this, Math.abs(year), iChronology.getMinYear(), iChronology.getMaxYear()); // // Do nothing if no real change is requested. // int thisWeekyear = get( instant ); if...
java
public void setImage(String src) { if (src == null) { throw new RuntimeException("Cannot set image to null. Call removeImage() if you wanted to remove the image"); } if (imageElem == null) { imageElem = Document.get().createImageElement(); // must be first ch...
java
protected void validateArgumentList(String[] args) { checkRequiredArguments(args); // Skip the first argument as it is the task name // Arguments and values come in pairs (expect -password). // Anything outside of that pattern is invalid. // Loop through, jumping in pairs except...
java
Rule InlineField() { return FirstOf(IfieldArea(), IfieldBook(), IfieldComposer(), IfieldDiscography(), IfieldGroup(), IfieldHistory(), IfieldLength(), IfieldMeter(), IfieldNotes(), IfieldOrigin(), IfieldPart(), IfieldTempo(), IfieldRhythm(), IfieldSource(), IfieldTitle(), IfieldVoice(), IfieldWords()...
java
private void executeRequestInterceptors(final IntuitMessage intuitMessage) throws FMSException { Iterator<Interceptor> itr = requestInterceptors.iterator(); while (itr.hasNext()) { Interceptor interceptor = itr.next(); interceptor.execute(intuitMessage); } }
java
@Override public CommerceTierPriceEntry fetchCommerceTierPriceEntryByUuidAndGroupId( String uuid, long groupId) { return commerceTierPriceEntryPersistence.fetchByUUID_G(uuid, groupId); }
python
def entry_detail(request, slug, template='djournal/entry_detail.html'): '''Returns a response of an individual entry, for the given slug.''' entry = get_object_or_404(Entry.public, slug=slug) context = { 'entry': entry, } return render_to_response( template, context, ...
java
@Pure public static double toESRI_m(double measure) { if (Double.isInfinite(measure) || Double.isNaN(measure)) { return ESRI_NAN; } return measure; }
java
private void updateComplex(String string) { if (string != null && StringUtils.getExpressionKey(string) != null && !string.equals(StringUtils.getExpressionKey(string))) { complex = true; } }