language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def set_governors(self, gov, rg=None): ''' Set governors gov: str name of the governor rg: list of range of cores ''' to_change = self.__get_ranges("online") if type(rg) == int: rg= [rg] if rg: to_change= set(rg) & set(self.__get_ranges("onlin...
python
def import_action(self, request, *args, **kwargs): """ Perform a dry_run of the import to make sure the import will not result in errors. If there where no error, save the user uploaded file to a local temp file that will be used by 'process_import' for the actual import. ...
java
public static List<Long> lengths(final Iterable<Range<Long>> ranges) { checkNotNull(ranges); List<Long> lengths = new ArrayList<Long>(); for (Range<Long> range : ranges) { lengths.add(length(range)); } return lengths; }
python
def opening(image, radius=None, mask=None, footprint=None): '''Do a morphological opening image - pixel image to operate on radius - use a structuring element with the given radius. If no radius, use an 8-connected structuring element. mask - if present, only use unmasked pixels for op...
java
public ImportExportResponseInner importMethod(String resourceGroupName, String serverName, ImportRequest parameters) { return importMethodWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().last().body(); }
java
@Nullable JSModule getModuleByName(String name) { for (JSModule m : modules) { if (m.getName().equals(name)) { return m; } } return null; }
python
def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, *varBinds, **options): """Creates a generator to send one or more SNMP notifications. On each iteration, new SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4,2,6`). The iterator blocks wa...
python
def mapped_read_count(self, force=False): """ Counts total reads in a BAM file. If a file self.bam + '.scale' exists, then just read the first line of that file that doesn't start with a "#". If such a file doesn't exist, then it will be created with the number of reads as the ...
python
def importExistingServerCertificate(self, alias, certPassword, certFile): """This operation imports an existing server certificate, stored in the PKCS #12 format, into the keystore.""" url = self._url + "/sslcertificates/importExistingServerCertificate" files = {} files['certFile'] = cer...
java
@Override public AssumeRoleWithSAMLResult assumeRoleWithSAML(AssumeRoleWithSAMLRequest request) { request = beforeClientExecution(request); return executeAssumeRoleWithSAML(request); }
python
def get_top_edge_depth(self): """ Compute top edge depth of each surface element and return area-weighted average value (in km). """ areas = self._get_areas() depths = numpy.array( [surf.get_top_edge_depth() for surf in self.surfaces]) return numpy.sum...
java
@Override public RestRepositories getRepositories(Request request) { RestRepositories repositories = new RestRepositories(); for (String repositoryName : getRepositoryManager().getJcrRepositoryNames()) { addRepository(request, repositories, repositoryName); } return repos...
java
public @NonNull Optional<T> get(final @NonNull String name) { return Optional.ofNullable(this.byName.get(name)); }
java
public void writeHtmlString(String strHTML, PrintWriter out) { int iIndex; if (strHTML == null) return; while ((iIndex = strHTML.indexOf(HtmlConstants.TITLE_TAG)) != -1) { // ** FIX THIS to look for a <xxx/> and look up the token ** strHTML = strHTML.substri...
python
def _glob_to_re(self, pattern): """Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). """ pattern_re = fnmat...
python
def set_custom_ticks(self, locations=None, clockwise=False, multiple=1, axes_colors=None, tick_formats=None, **kwargs): """ Having called get_ticks_from_axis_limits, set the custom ticks on the plot. """ for k in ['b', 'l', 'r']: self.ticks(ti...
java
@Override public void onFileCreate(File file) { try { engine.addTemplate(context.getBundle(0), file.toURI().toURL()); } catch (MalformedURLException e) { LOGGER.error("Cannot compute the url of file {}", file.getAbsolutePath(), e); } }
java
public static String join( Collection col, char sep ) { if( col.isEmpty() ) { return ""; } StringBuffer buffer = new StringBuffer(); boolean first = true; for (Object o : col) { if( first ) { first = false; } else { buffer.append( sep ); } buffer.append(...
java
public boolean removeMapping(String hostName, String contextPath) { log.info("Remove mapping host: {} context: {}", hostName, contextPath); final String key = getKey(hostName, contextPath); log.debug("Remove mapping: {}", key); return (mapping.remove(key) != null); }
python
def priority(s): """Return priority for a given object.""" # REZ: Previously this value was calculated in place many times which is # expensive. Do it once early. # REZ: Changed this to output a list, so that can nicely sort "validate" # items by the sub-priority of their schema type_...
java
static Collection<Sample> samples(Collection<SampleDTO> samples) { return Collections2.transform(samples, DTO_TO_SAMPLE); }
python
def exception_info(current_filename=None, index=-1): "Analizar el traceback y armar un dict con la info amigable user-friendly" # guardo el traceback original (por si hay una excepción): info = sys.exc_info() # exc_type, exc_value, exc_traceback # importante: no usar unpacking porque puede causa...
python
def update_wsnum_in_files(self, vernum): """ With the given version number ```vernum```, update the source's version number, and replace in the file hashmap. the version number is in the CHECKSUMS file. :param vernum: :return: """ self.version_num = vernu...
java
private void insertVariableDataTyping(Term term, Function atom, int position, Map<String, List<IndexedPosition>> termOccurenceIndex) throws UnknownDatatypeException { if (term instanceof Function) { Function function = (Function) term; Predica...
java
public static Resource toPythonConfigParser(@NonNull String sectionName, @NonNull Resource output) throws IOException { try (BufferedWriter writer = new BufferedWriter(output.writer())) { writer.write("["); writer.write(sectionName); writer.write("]\n"); for (Map.Entry<String, ...
python
def score(self, features, classes, scoring_function=accuracy_score, **scoring_function_kwargs): """Estimates the accuracy of the predictions from the constructed feature Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to predict from ...
java
public int getOwnerDocument(int nodeHandle) { if (DTM.DOCUMENT_NODE == getNodeType(nodeHandle)) return DTM.NULL; return getDocumentRoot(nodeHandle); }
python
def gen_authenticated_decorator(api_tokens=[]): """ This is a helper to build an `@authenticated` decorator that knows which API tokens are allowed. Example usage which allows 2 valid API tokens: authenticated = gen_authenticated_decorator(['123', 'abc']) @authenticated def te...
python
def post(self, request, *args, **kwargs): # type: (HttpRequest, object, object) -> HttpResponse """The method that handles HTTP POST request on the view. This method is called when the view receives a HTTP POST request, which is generally the request sent from Alexa during skill...
python
def _xor_block(a, b): """ XOR two blocks of equal length. """ return ''.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
java
public LDAPUserContext getUserContext(AuthenticatedUser authenticatedUser) throws GuacamoleException { // Bind using credentials associated with AuthenticatedUser Credentials credentials = authenticatedUser.getCredentials(); LDAPConnection ldapConnection = bindAs(credentials); ...
java
void configureNotFound(Reflections reflections) { log.info("Checking for a not-found endpoint.."); NotFound notFound = getEndpoint(NotFound.class, "not-found", reflections); if (notFound == null) notFound = new DefaultNotFound(); printEndpoint(notFound, "not-found"); this.notFou...
python
def getAnalysisRequestTemplates(self): """ This functions builds a list of tuples with the object AnalysisRequestTemplates' uids and names. :returns: A list of tuples where the first value of the tuple is the AnalysisRequestTemplate name and the second one is the AnalysisRequestTemplate ...
python
def inline_map_reduce(self, map, reduce, full_response=False, **kwargs): """Perform an inline map/reduce operation on this collection. Perform the map/reduce operation on the server in RAM. A result collection is not created. The result set is returned as a list of documents. I...
python
def register(cls, attr_name, attr_cls): """ Register a custom extended property in this item class so they can be accessed just like any other attribute """ if not cls.INSERT_AFTER_FIELD: raise ValueError('Class %s is missing INSERT_AFTER_FIELD value' % cls) try: ...
java
public static byte[] queryBinary(PreparedStatement stmt, byte[] def) throws SQLException { ResultSet rs = null; try { rs = stmt.executeQuery(); return rs.next() ? rs.getBytes(1) : def; } finally { close(rs); } }
python
def get_project(self, project_id): """ Returns a Project instance. :param project_id: Project identifier :returns: Project instance """ try: UUID(project_id, version=4) except ValueError: raise aiohttp.web.HTTPBadRequest(text="Project ID...
java
public boolean existsOnBroker (String brokerId) { boolean result = false; PerBrokerInfo info; synchronized (this.brokerDetails) { info = this.brokerDetails.get(brokerId); } if ((info != null) && (info.exists)) { result = true; } return r...
java
public ImageEncodingBITORDR createImageEncodingBITORDRFromString(EDataType eDataType, String initialValue) { ImageEncodingBITORDR result = ImageEncodingBITORDR.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getN...
java
public void floodFill(int xx, int yy, Rectangle clip, int replacement) { floodFill(xx, yy, clip, (c)->c!=replacement, replacement); }
java
public static IntArray getInstance(byte[] buffer, int bitCount, ByteOrder order) { return getInstance(buffer, 0, buffer.length, bitCount, order); }
java
public void appendMsg(final String msg) { if (!EventQueue.isDispatchThread()) { try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { appendMsg(msg); } }); ...
java
public static XLinkConnectorView[] getViewsOfRegistration(XLinkConnectorRegistration registration) { List<XLinkConnectorView> viewsOfRegistration = new ArrayList<XLinkConnectorView>(); Map<ModelDescription, XLinkConnectorView[]> modelsToViews = registration.getModelsToViews(); for (XLinkConnecto...
python
def tolist(self, to): """ Make sure that our addressees are a unicoded list Arguments: - `to`: str or list Return: [u, ...] Exceptions: None """ return ', '.join(isinstance(to, list) and [u(x) for x in to] or [u(to)])
python
def based_on(self, based_on): """Sets the based_on of this TaxRate. :param based_on: The based_on of this TaxRate. :type: str """ allowed_values = ["shippingAddress", "billingAddress"] if based_on is not None and based_on not in allowed_values: raise ValueEr...
java
public Agent newAgent(QualifiedName ag, String label) { Agent res = newAgent(ag); if (label != null) res.getLabel().add(newInternationalizedString(label)); return res; }
python
def transitive_closure(self): """Compute the transitive closure of the matrix.""" data = [[1 if j else 0 for j in i] for i in self.data] for k in range(self.rows): for i in range(self.rows): for j in range(self.rows): if data[i][k] and data[k][j]: ...
java
public void setContains(T value, boolean isMember) { checkNotFrozen(); m_membershipMap.put(value, new Boolean(isMember)); }
java
public static Comparable<?> getComparable(ValueData value, int type) throws UnsupportedEncodingException, IllegalStateException, IOException, IllegalNameException, RepositoryException { switch (type) { case PropertyType.BINARY : return null; case PropertyType.BOOLEAN :...
python
def encodeEntities(self, input): """TODO: remove xmlEncodeEntities, once we are not afraid of breaking binary compatibility People must migrate their code to xmlEncodeEntitiesReentrant ! This routine will issue a warning when encountered. """ ret = libxml2mod.xmlEncodeEnt...
java
public <V> NavigableMap<T, V> toNavigableMap(Function<? super T, ? extends V> valMapper) { return toNavigableMap(Function.identity(), valMapper); }
java
public SoapClient setParam(String name, Object value) { return setParam(name, value, true); }
java
@Override public void sawOpcode(int seen) { String userValue = null; try { stack.precomputation(this); int pc = getPC(); if (branchTargets.get(pc)) { localMethodCalls.clear(); fieldMethodCalls.clear(); branchTargets.clear(pc); } if (((seen >= Const.IFEQ) && (seen <= Const.GOTO)) || ((...
java
public boolean isValidGenericTld(String gTld) { final String key = chompLeadingDot(unicodeToASCII(gTld).toLowerCase(Locale.ENGLISH)); return (arrayContains(GENERIC_TLDS, key) || arrayContains(genericTLDsPlus, key)) && !arrayContains(genericTLDsMinus, key); }
python
def remove_dirs(self, directory): """Delete a directory recursively. :param directory: $PATH to directory. :type directory: ``str`` """ LOG.info('Removing directory [ %s ]', directory) local_files = self._drectory_local_files(directory=directory) for file_name i...
java
@Override public CPDefinition fetchByC_S_First(long CProductId, int status, OrderByComparator<CPDefinition> orderByComparator) { List<CPDefinition> list = findByC_S(CProductId, status, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; }
java
private String escapeCodeText(String text) { String lowerText = text.toLowerCase(); int preStart = lowerText.indexOf("<pre>"); int preEnd = lowerText.indexOf("</pre>"); if (preStart == -1 && preEnd == -1) { return text; } if (preStart >= 0 && preEnd >= 0 && preEnd < preStart) { // Ba...
java
public OutputStream create(String src, FsPermission permission, boolean overwrite, boolean createParent, short replication, long blockSize, Progre...
java
private void notifyOnPreferenceFragmentShown( @NonNull final NavigationPreference navigationPreference, @NonNull final Fragment fragment) { for (PreferenceFragmentListener listener : preferenceFragmentListeners) { listener.onPreferenceFragmentShown(navigationPreference, fragm...
python
def get_nadir(self, channel=0) -> tuple: """Get the coordinates, in units, of the minimum in a channel. Parameters ---------- channel : int or str (optional) Channel. Default is 0. Returns ------- generator of numbers Coordinates in units...
python
def attach_process_classic(self, command_or_pid_path, background, control=False, for_legion=False): """Attaches a command/daemon to the master process optionally managed by a pidfile. This will allow the uWSGI master to control/monitor/respawn this process. .. note:: This uses old classic uWSG...
python
def process_view(self, request, view_func, view_args, view_kwargs): """ Per-request mechanics for the current page object. """ # Load the closest matching page by slug, and assign it to the # request object. If none found, skip all further processing. slug = path_to_slug...
python
def get_activation_key(self, user): """ Generate the activation key which will be emailed to the user. """ return signing.dumps( obj=getattr(user, user.USERNAME_FIELD), salt=self.key_salt )
java
private void generateDelete(SQLiteDatabaseSchema schema) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("delete").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(Integer.TYPE); methodBuilder.addParameter(Uri.class, "uri"); methodBuilder.addParameter(String.class, "selection"); ...
python
def get_uncompleted_tasks(self): """Return all of a user's uncompleted tasks. .. warning:: Requires Todoist premium. :return: A list of uncompleted tasks. :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('john.d...
python
def iter_user_repos(login, type=None, sort=None, direction=None, number=-1, etag=None): """List public repositories for the specified ``login``. .. versionadded:: 0.6 .. note:: This replaces github3.iter_repos :param str login: (required) :param str type: (optional), accepted ...
python
def setEncoder(self, encoder): """ Sets the client's encoder ``encoder`` should be an instance of a ``json.JSONEncoder`` class """ if not encoder: self._encoder = json.JSONEncoder() else: self._encoder = encoder self._encode = self._encoder...
java
@Override public void play() { final String name = media.getPath(); if (Medias.getResourcesLoader().isPresent()) { if (cache == null) { cache = extractFromJar(media); } play(cache, name); } else { ...
java
public final void transliterate(Replaceable text, Position index, int insertion) { transliterate(text, index, UTF16.valueOf(insertion)); }
python
def __process_warc_gz_file(self, path_name): """ Iterates all transactions in one WARC file and for each transaction tries to extract an article object. Afterwards, each article is checked against the filter criteria and if all are passed, the function on_valid_article_extracted is invok...
python
def del_contact_downtime(self, downtime_id): """Delete a contact downtime Format of the line that triggers function call:: DEL_CONTACT_DOWNTIME;<downtime_id> :param downtime_id: downtime id to delete :type downtime_id: int :return: None """ for item in s...
java
private CmsSearchWorkplaceBean getSearchParams() { if ((m_searchParams == null) && (getSettings().getDialogObject() instanceof Map<?, ?>)) { Map<?, ?> dialogObject = (Map<?, ?>)getSettings().getDialogObject(); if (dialogObject.get(CmsSearchDialog.class.getName()) instanceof CmsSearchWor...
python
def get_tasklogger(name="TaskLogger"): """Get a TaskLogger object Parameters ---------- logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger """ try: return logging.getLogger(name).tasklogger ex...
java
@Override public T doDeserialize( JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params ) { // Processing the parameters. We fallback to default if parameter is not present. final IdentityDeserializationInfo identityInfo = null == params.getIdentityInfo() ? defaultIde...
java
public void insertRule(final String rule, final int index) throws DOMException { try { final CSSOMParser parser = new CSSOMParser(); parser.setParentStyleSheet(this); parser.setErrorHandler(ThrowCssExceptionErrorHandler.INSTANCE); final AbstractCSSRuleImpl r = par...
java
public void init() { LOG.info("Scanning esjps for REST implementations"); try { if (!Context.isThreadActive()) { Context.begin(null, Context.Inheritance.Local); Context.getThreadContext().setRequestAttribute(CONTEXTHINT, true); } re...
python
def cls_slots(self, cls: CLASS_OR_CLASSNAME) -> List[SlotDefinition]: """ Return the list of slots directly included in the class definition. Includes slots whose domain is cls -- as declared in slot.domain or class.slots Does not include slots declared in mixins, apply_to or is_a links ...
python
def _get_journal(): ''' Return the active running journal object ''' if 'systemd.journald' in __context__: return __context__['systemd.journald'] __context__['systemd.journald'] = systemd.journal.Reader() # get to the end of the journal __context__['systemd.journald'].seek_tail() ...
python
def chat_update_message(self, channel, text, timestamp, **params): """chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default format...
java
public EClass getGSLT() { if (gsltEClass == null) { gsltEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(476); } return gsltEClass; }
python
def notChainStr (states, s): """XXX I'm not sure this is how it should be done, but I'm going to try it anyway. Note that for this case, I require only single character arcs, since I would have to basically invert all accepting states and non-accepting states of any sub-NFA's. """ assert len(s)...
java
private CompositeExpression parseWildcardRange() { if (tokens.positiveLookahead(WILDCARD)) { tokens.consume(); return gte(versionFor(0, 0, 0)); } int major = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); if (tokens.positiveLookahead(WILD...
java
public void grow(float h, float v) { setX(getX() - h); setY(getY() - v); setWidth(getWidth() + (h*2)); setHeight(getHeight() + (v*2)); }
java
@Deprecated public void setPrimaryKeys(String... primaryKeyFieldName) { setProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, Joiner.on(",").join(primaryKeyFieldName)); }
java
@Override public boolean encode(long[] current, long[] next) { boolean configured = false; for (int i = unconfigured.nextSetBit(0); i >= 0; i = unconfigured.nextSetBit(i + 1)) { if (encoders.get(i).encode(current, next)) { unconfigured.clear(i); // don't configure again...
python
def add_io_macro(self,io,filename): """ Add a variable (macro) for storing the input/output files associated with this node. @param io: macroinput or macrooutput @param filename: filename of input/output file """ io = self.__bad_macro_chars.sub( r'', io ) if io not in self.__opts: ...
java
public void update(PeerState state, long uploaded, long downloaded, long left) { if (PeerState.STARTED.equals(state) && left == 0) { state = PeerState.COMPLETED; } if (!state.equals(this.state)) { logger.trace("Peer {} {} download of {}.", new Object[]{ ...
java
public List<MwDumpFile> findAllRelevantRevisionDumps(boolean preferCurrent) { MwDumpFile mainDump; if (preferCurrent) { mainDump = findMostRecentDump(DumpContentType.CURRENT); } else { mainDump = findMostRecentDump(DumpContentType.FULL); } if (mainDump == null) { return findAllDumps(DumpContentType.D...
java
public static List<CmsResource> getDetailOnlyResources(CmsObject cms, CmsResource resource) { List<CmsResource> result = new ArrayList<CmsResource>(); Set<String> resourcePaths = new HashSet<String>(); String sitePath = cms.getSitePath(resource); for (Locale locale : OpenCms.getLocaleMa...
java
public TypeMetadata without(Entry.Kind kind) { if (this == EMPTY || contents.get(kind) == null) return this; TypeMetadata out = new TypeMetadata(this); out.contents.remove(kind); return out.contents.isEmpty() ? EMPTY : out; }
python
def _init_metadata(self): """stub""" super(PDFPreviewFormRecord, self)._init_metadata() self._preview_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'file'), ...
java
public static MozuUrl removeDestinationUrl(String checkoutId, String destinationId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/checkouts/{checkoutId}/destinations/{destinationId}"); formatter.formatUrl("checkoutId", checkoutId); formatter.formatUrl("destinationId", destinationId); return n...
java
public Observable<ServiceResponse<Void>> checkNameAvailabilityWithServiceResponseAsync(CheckNameAvailabilityParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } ...
python
def CDSReader( fh, format='gff' ): """ yield chrom, strand, cds_exons, name """ known_formats = ( 'gff', 'gtf', 'bed') if format not in known_formats: print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr) raise Exception('?') if format == 'bed': f...
python
def _create_affine_siemens_mosaic(dicom_input): """ Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4d if in mosaic format """ # read dicom series with pds dicom_header = dicom_input[0] # Create affine matrix (http://nipy.sourceforge.net/...
java
public boolean isFinishing() { final Iterator<ExecutionVertex> it = this.vertices.iterator(); while (it.hasNext()) { final ExecutionState state = it.next().getExecutionState(); if (state != ExecutionState.FINISHING && state != ExecutionState.FINISHED) { return false; } } return true; }
java
@Override public UpdateServiceSpecificCredentialResult updateServiceSpecificCredential(UpdateServiceSpecificCredentialRequest request) { request = beforeClientExecution(request); return executeUpdateServiceSpecificCredential(request); }
java
@SuppressWarnings("static-method") protected ILaunchConfiguration chooseConfiguration(List<ILaunchConfiguration> configList) { final IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation(); final ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);...
python
def _normalize_port(scheme, port): """Return port if it is not default port, else None. >>> _normalize_port('http', '80') >>> _normalize_port('http', '8080') '8080' """ if not scheme: return port if port and port != DEFAULT_PORT[scheme]: return port
python
def _from_timeseries(ts1, ts2, stride, fftlength=None, overlap=None, window=None, **kwargs): """Generate a time-frequency coherence :class:`~gwpy.spectrogram.Spectrogram` from a pair of :class:`~gwpy.timeseries.TimeSeries`. For each `stride`, a PSD :class:`~gwpy.frequencyseries.Fre...