language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _member_def(self, member): """ Return an individual member definition formatted as an RST glossary entry, wrapped to fit within 78 columns. """ member_docstring = textwrap.dedent(member.docstring).strip() member_docstring = textwrap.fill( member_docstring,...
java
public void addChildNodesCount(NodeData parent, int count) { boolean inTransaction = cache.isTransactionActive(); try { if (!inTransaction) { cache.beginTransaction(); } cache.setLocal(true); cache.putIfAbsent(new CacheNodesId(get...
java
protected String readStringImpl(int length) throws IOException { StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int ch = is.read(); if (ch < 0x80) sb.append((char) ch); else if ((ch & 0xe0) == 0xc0) { ...
java
@Override public double getQuantile(double quantile, RandomVariable probabilities) { return ((RandomVariableAAD) getRandomVariableInterface()).getRandomVariableInterface().getQuantile(quantile, probabilities); }
java
public static boolean[] longToBinary(final long src, final int srcPos, final boolean[] dst, final int dstPos, final int nBools) { if (0 == nBools) { return dst; } if (nBools - 1 + srcPos >= 64) { throw new IllegalArgumentException("nBools-1+srcPos is greater o...
java
public static DefaultFeatureCollection runRawSqlToFeatureCollection( String name, ASpatialDb db, String simpleSql, Polygon roi ) throws Exception { String[] split = simpleSql.split("\\s+"); String tableName = null; for( int i = 0; i < split.length; i++ ) { if (split[i].to...
python
def run_dumper(self, dumper): """run dumber (once pr. engine) Args: dumper: dumper to run (function or method). The dumper takes the attributes experiments, farms, and barn as input. It does not return anything. But can, if the dumper designer feels in a bad and nas...
java
public static int aton(final String ip) { try { return aton(InetAddress.getByName(ip)); } catch (UnknownHostException e) { throw new IllegalArgumentException("must pass a valid ip. Illegal input was: " + ip, e); } }
java
public static Date getFromTimestamp(Timestamp timestamp) { if (timestamp == null) { return null; } return new Date(timestamp.getTime()); }
python
def system_piped(self, cmd): """Call the given cmd in a subprocess, piping stdout/err Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. Should not be a command that expects input other than s...
java
public static ArrayList<Trajectory> splitTrackInSubTracks(Trajectory t, int windowWidth, boolean overlapping){ int increment = 1; if(overlapping==false){ increment=windowWidth; } ArrayList<Trajectory> subTrajectories = new ArrayList<Trajectory>(); boolean trackEndReached = false; for(int i = 0; i < t....
java
@Override public long dynamicQueryCount(DynamicQuery dynamicQuery, Projection projection) { return cpDefinitionOptionValueRelPersistence.countWithDynamicQuery(dynamicQuery, projection); }
java
private static Boolean stringToBoolean(String value) { final String s = blankToNull(value); return s == null ? null : Boolean.valueOf(s); }
java
private void xorPayloadToHmacPad(byte[] workBytes) { int payloadSize = workBytes.length - OVERHEAD_SIZE; int sections = (payloadSize + COUNTER_PAGESIZE - 1) / COUNTER_PAGESIZE; checkArgument(sections <= COUNTER_SECTIONS, "Payload is %s bytes, exceeds limit of %s", payloadSize, COUNTER_PAGESIZE * COU...
java
TaskStatus getTaskStatus(TaskAttemptID taskid) { TaskInProgress tip = getTip(taskid.getTaskID()); return (tip == null ? null : tip.getTaskStatus(taskid)); }
java
@Override protected void cancelFaxJobImpl(FaxJob faxJob) { //get fax job ID int faxJobIDInt=WindowsFaxClientSpiHelper.getFaxJobID(faxJob); //invoke fax action this.winCancelFaxJob(this.faxServerName,faxJobIDInt); }
java
@Override public synchronized void process(CAS tcas) { final AnnotationComboIterator comboIterator = new AnnotationComboIterator(tcas, this.sentenceType, this.tokenType); for (AnnotationIteratorPair annotationIteratorPair : comboIterator) { final List<Annotatio...
java
@PostConstruct void init(TracingRunnableInstrumenter instrumenter) { if (instrumenter != null) { Func1<Action0, Action0> existing = RxJavaHooks.getOnScheduleAction(); if (existing != null && !(existing instanceof InstrumentScheduleAction)) { RxJavaHooks.setOnScheduleA...
python
def create_archive_dir(self): """ Create the archive dir """ archive_dir = os.path.join(self.tmp_dir, self.archive_name) os.makedirs(archive_dir, 0o700) return archive_dir
java
public static void reloadPolicies(String protocol, String user, String pass) throws IOException { getServerResponse(protocol, user, pass, "/management/control?action=reloadPolicies"); }
java
public int deleteByExtension(String extensionName) throws SQLException { DeleteBuilder<Extensions, Void> db = deleteBuilder(); db.where().eq(Extensions.COLUMN_EXTENSION_NAME, extensionName); int deleted = db.delete(); return deleted; }
java
public static void assertAllAreNull(String messageIfNull, Object... objects) throws IllegalArgumentException { for (Object object : objects) { if (object != null) { throw new IllegalArgumentException(messageIfNull); } } }
python
def replace_units(self, units, copy=True): """Change the unit system of this potential. Parameters ---------- units : `~gala.units.UnitSystem` Set of non-reducable units that specify (at minimum) the length, mass, time, and angle units. copy : bool (optio...
python
def get_configuration(self, module_id, run_number=None): ''' Returns the configuration for a given module ID. The working directory is searched for a file matching the module_id with the given run number. If no run number is defined the last successfull run defines the run number. ...
python
def save_to_temp(content, file_name=None): """Save the contents into a temp file.""" #output = "results.html" temp_dir = tempfile.gettempdir() #tempfile.TemporaryDirectory() #tempfile.NamedTemporaryFile(mode='w+t') as f: out_file = os.path.join(temp_dir, file_name) #if os.path.exists(output...
java
public static void print(final PrintStream out, final String name, final Percentile p) { if(p.isReady()) { try { final StringBuilder sb = new StringBuilder(512); final float[] q = p.getQuantiles(); final float[] e = p.getEstimates(); fi...
python
def int_to_key(value, base=BASE62): """ Convert the specified integer to a key using the given base. @param value: a positive integer. @param base: a sequence of characters that is used to encode the integer value. @return: a key expressed in the specified base. """ def key_seq...
python
def _yum_pkginfo(output): ''' Parse yum/dnf output (which could contain irregular line breaks if package names are long) retrieving the name, version, etc., and return a list of pkginfo namedtuples. ''' cur = {} keys = itertools.cycle(('name', 'version', 'repoid')) values = salt.utils.it...
java
public static int checkInvariantsI( final int value, final ContractIntConditionType... conditions) throws InvariantViolationException { final Violations violations = innerCheckAllInt(value, conditions); if (violations != null) { throw new InvariantViolationException( failedMess...
python
def update_dimensions(self, dims): """ Update multiple dimension on the cube. .. code-block:: python cube.update_dimensions([ {'name' : 'ntime', 'global_size' : 10, 'lower_extent' : 2, 'upper_extent' : 7 }, {'name' : 'na', 'global_siz...
java
public void setTemplateResolver(final ITemplateResolver templateResolver) { Validate.notNull(templateResolver, "Template Resolver cannot be null"); checkNotInitialized(); this.templateResolvers.clear(); this.templateResolvers.add(templateResolver); }
java
public boolean isTriggeringEvent( final Appender appender, final LoggingEvent event, final String filename, final long fileLength) { return System.currentTimeMillis() >= nextCheck; }
java
public static SimpleResponse makeResponse(SimpleRequest request) { if (request.getResponseSize() > 0) { if (!Messages.PayloadType.COMPRESSABLE.equals(request.getResponseType())) { throw Status.INTERNAL.augmentDescription("Error creating payload.").asRuntimeException(); } ByteString body =...
java
private void parseRelations(final Object originalEntity, final Object relationEntity, final Map<String, Object> relationsMap, final PersistenceDelegator pd, final EntityMetadata metadata, boolean lazilyloaded, Map<Object, Object> relationStack) { for (Relation relation : metadata.ge...
java
public static int[] subset(final int[] set, final int k, final Random random) { final int[] sub = subset(set.length, new int[k], random); for (int i = 0; i < k; ++i) { sub[i] = set[sub[i]]; } return sub; }
python
def link(self, content, link, title=''): """ Emit a link, potentially remapped based on our embed or static rules """ link = links.resolve(link, self._search_path, self._config.get('absolute')) return '{}{}</a>'.format( utils.make_tag('a', { ...
python
def check_new_round(self, hours=24, tournament=1): """Check if a new round has started within the last `hours`. Args: hours (int, optional): timeframe to consider, defaults to 24 tournament (int): ID of the tournament (optional, defaults to 1) Returns: bool:...
java
public boolean waitForView(int id){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "waitForView("+id+")"); } return waitForView(id, 0, Timeout.getLargeTimeout(), true); }
python
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ jsn = super(InvocationTransaction, self).ToJson() jsn['script'] = self.Script.hex() jsn['gas'] = self.Gas.ToNeoJsonString() return jsn
java
static public JSONObject recreateDocumentFromDocAndReserved(JSONObject doc, JSONObject reserved) throws Exception { JSONObject result = JSONSupport.copyObject( doc ); // Re-insert attributes that start with '_' if( null != reserved ) { Iterator<?> it = reserved.keys(); while( it.hasNext() ){ Object k...
java
public static IntTuple reversed(IntTuple t) { Objects.requireNonNull(t, "The input tuple is null"); return new AbstractIntTuple() { @Override public int getSize() { return t.getSize(); } @Override ...
python
def get_logger(): """Setup logging output defaults""" # Grab the logger if not hasattr(get_logger, 'logger'): # Setup the default logging config get_logger.logger = logging.getLogger('chains') format_str = '%(asctime)s [%(levelname)s] - %(module)s: %(message)s' logging.basi...
java
public static <B extends ProcessBuilder> QueueBuilder<B> newQueueBuilder(Class<B> process_builder_class) { return new QueueBuilder<B>(ROOT_QUEUE, process_builder_class); }
java
public S getSchemaByKey(K key) throws SchemaRegistryException { try { return cachedSchemasByKeys.get(key); } catch (ExecutionException e) { throw new SchemaRegistryException(String.format("Schema with key %s cannot be retrieved", key), e); } }
python
def deactivate(): """ Deactivate a state in this thread. """ if hasattr(_mode, "current_state"): del _mode.current_state if hasattr(_mode, "schema"): del _mode.schema for k in connections: con = connections[k] if hasattr(con, 'reset_schema'): con.res...
python
def data_to_df(self, sysbase=False): """ Return a pandas.DataFrame of device parameters. :param sysbase: save per unit values in system base """ p_dict_comp = self.data_to_dict(sysbase=sysbase) self._check_pd() self.param_df = pd.DataFrame(data=p_dict_comp).set_...
python
def _addSortParam(self, field, order=''): """Adds a sort parameter, order have to be in ['ascend', 'ascending','descend', 'descending','custom']""" if order != '': validSortOrders = { 'ascend':'ascend', 'ascending':'ascend', '<':'ascend', 'descend':'descend', 'descending':'descend', '>':...
java
protected final void putInt16(int i16) { ensureCapacity(position + 2); byte[] buf = buffer; buf[position++] = (byte) (i16 & 0xff); buf[position++] = (byte) (i16 >>> 8); }
java
public void init(Converter converter, Object objTarget, boolean bTrueIfMatch) { super.init(converter, null, null); m_objTarget = objTarget; m_bTrueIfMatch = bTrueIfMatch; }
java
public static String format(final Calendar calendar, final String pattern, final Locale locale) { return format(calendar, pattern, null, locale); }
python
def optimize(self, **kwargs): """Iteratively optimize the ROI model. The optimization is performed in three sequential steps: * Free the normalization of the N largest components (as determined from NPred) that contain a fraction ``npred_frac`` of the total predicted counts...
java
private void actOnSamplesDataList(Consumer<List<List<String>>> action) { actOnList(impl.getSamplesData(), action, impl::setSamplesData); }
java
public static int completeCircularPasses(int index, int seqLength) { int count = 0; while (index > seqLength) { count++; index -= seqLength; } return count - 1; }
python
def cycle_windows(tree, direction): """ Cycle through windows of the current workspace """ wanted = { "orientation": ("vertical" if direction in ("up", "down") else "horizontal"), "direction": (1 if direction in ("down", "right") else -1), ...
java
public static void writeInt(byte[] bytes, int value, int offset) { bytes[offset] = (byte) (0xFF & (value >> 24)); bytes[offset + 1] = (byte) (0xFF & (value >> 16)); bytes[offset + 2] = (byte) (0xFF & (value >> 8)); bytes[offset + 3] = (byte) (0xFF & value); }
java
@SuppressWarnings("unchecked") private Repository<Entity> decorateRepository( Repository<Entity> repository, DecoratorConfiguration configuration) { Map<String, Map<String, Object>> parameterMap = getParameterMap(configuration); List<DecoratorParameters> decoratorParameters = configuration.getDe...
java
public static CurrencyConversion getConversion(CurrencyUnit termCurrency, String... providers){ Objects.requireNonNull(providers); Objects.requireNonNull(termCurrency); if(providers.length == 0){ return getMonetaryConversionsSpi().getConversion( ConversionQueryBui...
java
private boolean isAllowedAddress(String ipAddress) { if (allowedAddresses == null) { return false; } // IPv4 int offset = ipAddress.lastIndexOf('.'); if (offset == -1) { // IPv6 offset = ipAddress.lastIndexOf(':'); if (offset == -1...
python
def get_possible_combos_for_transition(trans, model, self_model, is_external=False): """ The function provides combos for a transition and its respective :param trans: :param model: :param self_model: :param is_external: :return: """ from_state_combo = Gt...
python
def results(self): """If successfully created, add the cleaned `CifData` and `StructureData` as output nodes to the workchain. The filter and select calculations were successful, so we return the cleaned CifData node. If the `group_cif` was defined in the inputs, the node is added to it. If the...
java
public static final DoubleMatrix2D diagonalMatrixMult(final DoubleMatrix1D diagonalU, DoubleMatrix2D A, final DoubleMatrix1D diagonalV){ int r = A.rows(); int c = A.columns(); final DoubleMatrix2D ret; if (A instanceof SparseDoubleMatrix2D) { ret = DoubleFactory2D.sparse.make(r, c); A.forEachNonZero...
python
def vcsNodeState_originator_switch_info_switchIpV6Address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcsNodeState = ET.SubElement(config, "vcsNodeState", xmlns="urn:brocade.com:mgmt:brocade-vcs") originator_switch_info = ET.SubElement(vcsNodeState, ...
python
def get(self, path, name): """ :param path: str or Path instance :param name: :type name: str :return: """ container = self.get_container(path) try: return container._values[name] except KeyError: raise KeyError()
java
private void startupDialog(String prefs, int message, final Class clazz) { final SharedPreferences preferences = getSharedPreferences(prefs, Activity.MODE_PRIVATE); final String accepted = "accepted"; if (!preferences.getBoolean(accepted, false)) { AlertDialog.Builder builder = new A...
java
public static TemplateBasedScriptBuilder fromTemplateResource(Resource scriptTemplateResource) { try { return new TemplateBasedScriptBuilder(FileUtils.readToString(scriptTemplateResource.getInputStream())); } catch (IOException e) { throw new CitrusRuntimeException("Error loading...
java
private static URL findHelpSetUrl() { return LocaleUtils.findResource( HELP_SET_FILE_NAME, HELP_SET_FILE_EXTENSION, Constant.getLocale(), r -> ExtensionFactory.getAddOnLoader().getResource(r)); }
java
@Override public List<HBaseData> LoadData(HTableInterface hTable, Object rowKey, Filter filter, String... columns) throws IOException { return LoadData(hTable, Bytes.toString(hTable.getTableName()), rowKey, filter, columns); }
java
public static Uri getUriForQualifiedResource(String packageName, int resourceId) { return new Uri.Builder() .scheme(QUALIFIED_RESOURCE_SCHEME) .authority(packageName) .path(String.valueOf(resourceId)) .build(); }
python
def add_latent_style(self, name): """ Return a newly added |_LatentStyle| object to override the inherited defaults defined in this latent styles object for the built-in style having *name*. """ lsdException = self._element.add_lsdException() lsdException.name = B...
java
protected void initCommon () { this.fitness = problem.getDefaultFitness(); this.bestConfiguration = this.activeConfiguration; this.bestFitness = this.fitness.getValue(this.activeConfiguration); // calculate fitness this.activeFitness = this.fitness.getValue(this.activeConfigura...
python
def format_string(current_size, total_length, elapsed_time): """ Consistent format to be displayed on the screen. :param current_size: Number of finished object size :param total_length: Total object size :param elapsed_time: number of seconds passed since start """ n_to_mb = current_size /...
java
public long getLastTickReceived() throws SIMPRuntimeOperationFailedException { //Returns the tick of the last message received and acknowleged if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getLastTickReceived"); try { assertValidControllable(); ...
java
public static SecretKey generateKey(final byte[] key) { return new SecretKey() { private byte[] k; { if (key.length == 16) { k = key; } else { k = new byte[16]; System.arraycopy(key, 0, k, 0, ke...
python
def logs_handle_job(job_uuid: str, job_name: str, log_lines: Optional[Union[str, Iterable[str]]], temp: bool = True) -> None: """Task handling for sidecars logs.""" handle_job_logs(job_uuid=job_uuid, job_name=job_name, ...
java
protected String getErrorDesc(int errorType, int currEvent) { // Defaults are mostly fine, except we can easily add event type desc switch (errorType) { case ERR_GETELEMTEXT_NOT_START_ELEM: return ErrorConsts.ERR_STATE_NOT_STELEM+", got "+ErrorConsts.tokenTypeDesc(currEvent); ...
java
@Override protected V mergeState(V a, V b) throws Exception { return reduceTransformation.apply(a, b); }
java
private void checkAndEnableSaveButton() { boolean enabled = true; enabled &= txt_PubCert.getDocument().getLength() > MIN_CERT_LENGTH; bt_save.setEnabled(enabled); }
java
public static DB newEmbeddedDB(int port) throws ManagedProcessException { DBConfigurationBuilder config = new DBConfigurationBuilder(); config.setPort(port); return newEmbeddedDB(config.build()); }
java
@Restricted(NoExternalUse.class) public void writeConfigDotXml(OutputStream os) throws IOException { checkPermission(EXTENDED_READ); XmlFile configFile = getConfigFile(); if (hasPermission(CONFIGURE)) { IOUtils.copy(configFile.getFile(), os); } else { String e...
python
def load_zipfile(self, path): """ import contents of a zipfile """ # try to add as zipfile zin = zipfile.ZipFile(path) for zinfo in zin.infolist(): name = zinfo.filename if name.endswith("/"): self.mkdir(name) else: ...
java
public static String getSettingsRemotePath(GlobalSettingsProvider provider, AbstractBuild<?, ?> build, TaskListener listener) { FilePath fp = getSettingsFilePath(provider, build, listener); return fp == null ? null : fp.getRemote(); }
java
public AbstractExpression replaceAVG () { if (getExpressionType() == ExpressionType.AGGREGATE_AVG) { AbstractExpression child = getLeft(); AbstractExpression left = new AggregateExpression(ExpressionType.AGGREGATE_SUM); left.setLeft(child.clone()); ...
python
def from_coarse_partition(self, partition, coarse_node=None): """ Update current partition according to coarser partition. Parameters ---------- partition : :class:`~VertexPartition.MutableVertexPartition` The coarser partition used to update the current partition. coarse_node : list of int ...
java
public QueryRequest addParameter(String key, Object value) { if (parameters.get(key) == null) { parameters.put(key, Sets.newHashSet(value)); } else { parameters.get(key).add(value); } return this; }
java
public RobotsDirectives getDirectivesFor(String ua, boolean useFallbacks) { // find matching ua for(String uaListed : namedUserAgents) { if(ua.indexOf(uaListed)>-1) { return agentsToDirectives.get(uaListed); } } if(useFallbacks==false) { ...
python
def _add_input_state(self, node, input_state): """ Add the input state to all successors of the given node. :param node: The node whose successors' input states will be touched. :param input_state: The state that will be added to successors of the node. :return: ...
java
protected void addURL(final URL url) { final URL[] newUrls = new URL[this.urls.length + 1]; System.arraycopy(url, 0, newUrls, 0, this.urls.length); newUrls[this.urls.length] = url; this.urls = newUrls; }
java
public void preprocess(IContext context) throws ContextPreprocessorException { unrecognizedWords.clear(); // construct cLabs context = buildCLabs(context); // sense filtering context = findMultiwordsInContextStructure(context); try { senseFiltering(cont...
java
public DescribeStackResourceDriftsRequest withStackResourceDriftStatusFilters(StackResourceDriftStatus... stackResourceDriftStatusFilters) { com.amazonaws.internal.SdkInternalList<String> stackResourceDriftStatusFiltersCopy = new com.amazonaws.internal.SdkInternalList<String>( stackResourceDrift...
python
def supports_ansi_escape_codes(fd): """Returns whether the output device is capable of interpreting ANSI escape codes when :func:`print_` is used. Args: fd (int): file descriptor (e.g. ``sys.stdout.fileno()``) Returns: `bool` """ if os.isatty(fd): return True if no...
java
public TaskResult addIntegerArrayList(String key, ArrayList<Integer> value) { mBundle.putIntegerArrayList(key, value); return this; }
python
def send_confirmation_email(self, confirmation_id, email_dict): """ Sends an confirmation by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param confirmation_id: the confirmation id ...
java
@Override public void downsample(final long interval, final Aggregator downsampler) { if (downsampler == Aggregators.NONE) { throw new IllegalArgumentException("cannot use the NONE " + "aggregator for downsampling"); } downsample(interval, downsampler, FillPolicy.NONE); }
java
public Document serialiseToDocument(final Object obj) { final Document document = DOMUtils.createDocumentBuilder().newDocument(); serialise(obj, document); return document; }
java
private List<JoinableResourceBundle> getBundleDependencies(ResourceBundleDefinition definition, List<JoinableResourceBundle> bundles) throws BundleDependencyException { List<JoinableResourceBundle> dependencies = new ArrayList<>(); List<String> processedBundles = new ArrayList<>(); if (definition.isGlobal() &...
java
public String readPassword(String password) { if (password == null || encryptors.size() < 1) { return password; } Matcher matcher = PASSWORD_PATTERN.matcher(password); if (matcher.find()) { return this.decryptPassword(matcher.group(1)); } return password; }
python
def synset(synset_key): """Returns synset object with the provided key. Notes ----- Uses lazy initialization - synsets will be fetched from a dictionary after the first request. Parameters ---------- synset_key : string Unique synset identifier in the form of `lemma.pos.sense_no`. ...
java
public static void SubmitDelayed( long millis, Runnable task ) { Actors.delayedCalls.schedule( new TimerTask() { @Override public void run() { task.run(); } },millis); }
java
protected void localRelease() { _name = ""; _toolbar = null; _location = null; _directories = null; _status = null; _menubar = null; _resizable = null; _scrollbars = null; _width = null; _height = null; _left = null; _to...
java
@Override public void close() throws IOException { InputStream is = getObjectContent(); if (is != null) is.close(); }