language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def certs(self): """ List of the certificates contained in the structure """ certstack = libcrypto.CMS_get1_certs(self.ptr) if certstack is None: raise CMSError("getting certs") return StackOfX509(ptr=certstack, disposable=True)
python
def activity_show(self, activity_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/activity_stream#show-activity" api_path = "/api/v2/activities/{activity_id}.json" api_path = api_path.format(activity_id=activity_id) return self.call(api_path, **kwargs)
python
def _get_parallel_regions(data): """Retrieve regions to run in parallel, putting longest intervals first. """ callable_regions = tz.get_in(["config", "algorithm", "callable_regions"], data) if not callable_regions: raise ValueError("Did not find any callable regions for sample: %s\n" ...
java
public Object parse(Type dataType, boolean close) throws IOException { return parse(dataType, close, null); }
python
def pack(R, L, pf=None, n=None, rng=None, periodic=False, beta_max=1e4, dL_max=0.02, dr_max=0.02): """Pack a number of non-intersecting spheres into a periodic system. Can specify packing by number of spheres or packing fraction. This implementation uses the Metropolis-Hastings algorithm for an ...
python
def build_permuted_index( self, lshash, buckets, num_permutation, beam_size, num_neighbour): """ Build a permutedIndex and store it into the dict self.permutedIndexs. lshash: the binary lshash object (nearpy.hashes.lshash). ...
python
def get_route_name(resource_uri): """ Get route name from RAML resource URI. :param resource_uri: String representing RAML resource URI. :returns string: String with route name, which is :resource_uri: stripped of non-word characters. """ resource_uri = resource_uri.strip('/') resource_...
python
def get_current_config_value(self, config_key, use_preliminary=True, default=None): """Returns the current config value for the given config key :param str config_key: Config key who's value is requested :param bool use_preliminary: Whether the preliminary config should be queried first ...
java
public static Map<String, List<TraceEvent>> filterCCMPoolEvents(List<TraceEvent> data) throws Exception { Map<String, List<TraceEvent>> result = new TreeMap<String, List<TraceEvent>>(); for (TraceEvent te : data) { if (te.getType() == TraceEvent.REGISTER_CCM_CONNECTION || te....
python
def tp_graph(dataframe, image_name, dir='./'): """Throughput graph :param pandas.DataFrame dataframe: dataframe containing all data :param str dir: the output directory :return: None """ fig = pygal.TimeLine(x_title='Elapsed Time In Test (secs)', x_label_rotation=25, ...
java
@Override public String next() { if (hasNext()) { if (enumerationSize == NULL_LOCALE_ENUMERATION_SIZE) { cursor++; return templateName; } final String language = matcher.group(1); final String country = matcher.group(2); ...
python
def set_state(self, state): """ Activate and put this conversation into the given state. The relation name will be interpolated in the state name, and it is recommended that it be included to avoid conflicts with states from other relations. For example:: conversat...
java
@Override public void addClassesSummary(SortedSet<TypeElement> classes, String label, String tableSummary, List<String> tableHeader, Content summaryContentTree) { if(!classes.isEmpty()) { Content caption = getTableCaption(new RawHtml(label)); Content table = (configuratio...
java
public void init(BaseField field, GridScreenParent gridScreen, Record recGrid, boolean bCreateSortOrder) { m_recGrid = recGrid; m_bCreateSortOrder = bCreateSortOrder; super.init(field, gridScreen, null); m_iKeyAreaArray = new String[MAX_ARRAY_SIZE]; for (int i = 0; i < MAX_AR...
python
def on_key(self, event): """Sets abort if pasting and if escape is pressed""" # If paste is running and Esc is pressed then we need to abort if event.GetKeyCode() == wx.WXK_ESCAPE and \ self.pasting or self.grid.actions.saving: self.need_abort = True event.Skip(...
java
private EnabledEndpoint getPartialEnabledEndpointFromResultset(ResultSet result) throws Exception { EnabledEndpoint endpoint = new EnabledEndpoint(); endpoint.setId(result.getInt(Constants.GENERIC_ID)); endpoint.setPathId(result.getInt(Constants.ENABLED_OVERRIDES_PATH_ID)); endpoint.setO...
python
def d2logpdf_dlink2(self, link_f, y, Y_metadata=None): """ Hessian at y, given link(f), w.r.t link(f) i.e. second derivative logpdf at y given link(f_i) and link(f_j) w.r.t link(f_i) and link(f_j) The hessian will be 0 unless i == j .. math:: :param link_f: latent var...
java
@SuppressWarnings("unchecked") public static Class<? extends IHEAuditor> getAuditorClassForClassName(String className) { try { Class<?> clazz = Class.forName(className); return (Class<? extends IHEAuditor>)clazz; } catch (ClassCastException e) { LOGGER.error("The requested class "+ className +" is not a ...
java
public ExpansionProfileContactComponent addContact() { //3 ExpansionProfileContactComponent t = new ExpansionProfileContactComponent(); if (this.contact == null) this.contact = new ArrayList<ExpansionProfileContactComponent>(); this.contact.add(t); return t; }
python
def _select_next_server(self): """ Looks up in the server pool for an available server and attempts to connect. """ # Continue trying to connect until there is an available server # or bail in case there are no more available servers. while True: if l...
java
private StorageObject getObject(StorageResourceId resourceId) throws IOException { logger.atFine().log("getObject(%s)", resourceId); Preconditions.checkArgument( resourceId.isStorageObject(), "Expected full StorageObject id, got %s", resourceId); String bucketName = resourceId.getBucketName();...
python
def unicode_compact(func): """ Make sure the first parameter of the decorated method to be a unicode object. """ @wraps(func) def wrapped(self, text, *a, **kw): if not isinstance(text, six.text_type): text = text.decode('utf-8') return func(self, text, *a, **kw) ...
java
@Override public Object invoke(ELContext context, Object[] paramValues) throws ELException { return node.invoke(bindings, context, type, types, paramValues); }
java
public synchronized void init(ProcessingEnvironment processingEnv) { if (initialized) throw new IllegalStateException("Cannot call init more than once."); Objects.requireNonNull(processingEnv, "Tool provided null ProcessingEnvironment"); this.processingEnv = processingEnv; i...
python
def dict_to_ddb(item): # type: (Dict[str, Any]) -> Dict[str, Any] # TODO: narrow these types down """Converts a native Python dictionary to a raw DynamoDB item. :param dict item: Native item :returns: DynamoDB item :rtype: dict """ serializer = TypeSerializer() return {key: serializ...
java
private void obtainValidateOnFocusLost(@NonNull final TypedArray typedArray) { validateOnFocusLost(typedArray .getBoolean(R.styleable.AbstractValidateableView_validateOnFocusLost, DEFAULT_VALIDATE_ON_FOCUS_LOST)); }
java
private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo, List<String> statements, boolean logDetails) { List<String> statementsBefore = new ArrayList<String>(); List<String> statementsAfter = new ArrayList<String>(); for (FieldType fieldType : tableInfo.getField...
python
def apply_groupby(records, fn, skip_none=False): """ Given a list of objects, group them into a dictionary by applying fn to each one and using returned values as a dictionary key. Parameters ---------- records : list fn : function skip_none : bool If False, then None can ...
java
private static Reader createFreeOnCloseReader(final Clob clob, final Reader reader) { return new Reader() { @Override public void close() throws IOException { try { reader.close(); } finally { try { ...
java
public static CommercePriceList[] findByG_S_PrevAndNext( long commercePriceListId, long groupId, int status, OrderByComparator<CommercePriceList> orderByComparator) throws com.liferay.commerce.price.list.exception.NoSuchPriceListException { return getPersistence() .findByG_S_PrevAndNext(commercePriceList...
java
public static String getCanonicalCountry(String tzid) { String country = getRegion(tzid); if (country != null && country.equals(kWorld)) { country = null; } return country; }
java
public ImportExportOperationResultInner export(String resourceGroupName, String serverName, String databaseName, ImportExportDatabaseDefinition parameters) { return exportWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).toBlocking().last().body(); }
python
def _parse_invited_member(self, values): """ Parses the column texts of an invited row into a invited dictionary. Parameters ---------- values: tuple[:class:`str`] A list of row contents. """ name, date = values if date != "Invitation Date": ...
python
def fromimportupdate(cls, bundle, import_reg): # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the update of an ImportRegistration """ exc = import_reg.get_exception() if exc: return Rem...
java
private void createOEXDirectory(String wuid) throws IOException { File oexDirectory = new File(directory, wuid); if (!oexDirectory.exists() && !oexDirectory.mkdirs()) { throw new WebDriverException("Unable to create directory path: " + directory.getPath()); } File prefsDatPath = new File(oexDirect...
python
def url2fs(url): """ encode a URL to be safe as a filename """ uri, extension = posixpath.splitext(url) return safe64.dir(uri) + extension
java
protected void setURI() { // set _uri StringBuffer buf = new StringBuffer(); // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? if (_scheme != null) { buf.append(_scheme); buf.append(':'); } if (_is_net_path) { buf.append("//"...
python
def inflate_plugins(self, plugins_definition, inflate_method): """ Inflate multiple plugins based on a list/dict definition. Args: plugins_definition (list/dict): the plugins definitions. inflate_method (method): the method to indlate each plugin. Returns: ...
java
public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { startUpdate(columnIndex); preparedStatement.setParameter(columnIndex, x); }
python
def flatten(rho, pval, sortby="cor"): """Flatten correlation and p-value matrix Parameters: ----------- rho : ndarray Correlation Matrix pval : ndarray Matrix with p-values sortby : str sort the output table by - "cor" the highest absolute correlation coeffici...
java
public static int readUnsignedInt(byte[] bytes, int offset) { byte b = bytes[offset++]; int i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = bytes[offset++]; i |= (b & 0x7FL) << shift; } return i; }
python
def get_resource_metadata(self, resource=None): """ Get resource metadata :param resource: The name of the resource to get metadata for :return: list """ result = self._make_metadata_request(meta_id=0, metadata_type='METADATA-RESOURCE') if resource: re...
java
public void process(JCas jcas) { try { tagger.process(jcas); } catch(AnalysisEngineProcessException e) { e.printStackTrace(); } }
python
def _loop(self, barrier): """Actual thread""" if sys.platform != "win32": self.loop = asyncio.new_event_loop() else: self.loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(self.loop) barrier.wait() try: self.loop.run_forever() ...
java
static INode[] getINodeArray(INode inode) throws IOException { // calculate the depth of this inode from root int depth = getPathDepth(inode); INode[] inodes = new INode[depth]; // fill up the inodes in the path from this inode to root for (int i = 0; i < depth; i++) { inodes[depth-i-1] = ino...
java
public void error(SourceLocator srcLctr, Node styleNode, Node sourceNode, String msg) throws TransformerException { error(srcLctr, styleNode, sourceNode, msg, null); }
java
@Override public Boolean getPropertyBoolean(Class<?> aClass, String key, boolean aBool) { return getPropertyBoolean(new StringBuilder(aClass.getName()).append(".").append(key).toString(), aBool); }
java
@Override public long size() { try { if (emulateIsAbsent) lock.readLock().lock(); return compressedEntries.size(); } finally { if (emulateIsAbsent) lock.readLock().unlock(); } }
java
@SuppressWarnings("resource") public static List<Logger> getAllLoggers() { LoggerContext context = (LoggerContext)(LogManager.getContext(false)); Map<String, Logger> loggersByName = new TreeMap<String, Logger>(); for (Logger logger : context.getLoggers()) { String loggerName = l...
java
@NonNull public JsonProcessor lookup() { JsonProcessor registeredJsonProcessor = this.registeredJsonProcessor; if (registeredJsonProcessor != null) { return registeredJsonProcessor; } if (!init) { synchronized (this) { if (!init) { ...
python
def estimate_assignment_probs(q, trials, cxn, p0=None): """ Estimate the readout assignment probabilities for a given qubit ``q``. The returned matrix is of the form:: [[p00 p01] [p10 p11]] :param int q: The index of the qubit. :param int trials: The number of samples for ...
java
public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone) { return cache.getTimeInstance(style, timeZone, null); }
java
public boolean accept(File f) { if (f.isDirectory()) { return false; } String name = f.getName().toLowerCase(); return name.endsWith(".pdf"); }
python
def _updateWidgets(self): """ Updates the combo and spin boxes given the new rti or axes. Emits the sigContentsChanged signal. """ row = 0 model = self.tree.model() # Create path label nodePath = '' if self.rti is None else self.rti.nodePath pathItem ...
python
def create_layer(StackId=None, Type=None, Name=None, Shortname=None, Attributes=None, CloudWatchLogsConfiguration=None, CustomInstanceProfileArn=None, CustomJson=None, CustomSecurityGroupIds=None, Packages=None, VolumeConfigurations=None, EnableAutoHealing=None, AutoAssignElasticIps=None, AutoAssignPublicIps=None, Cust...
python
def flatten_model(model): """Flatten a model to a list of models. This is used to flatten a ``Binder``'ish model down to a list of contained models. """ yield model if isinstance(model, (TranslucentBinder, Binder,)): for m in model: # yield from flatten_model(m) f...
python
def get_data_port(self, state_id, port_id): """Searches for a data port The data port specified by the state id and data port id is searched in the state itself and in its children. :param str state_id: The id of the state the port is in :param int port_id: The id of the port ...
java
protected void configureJdbcAuthenticationProvider(final AuthenticationManagerBuilder auth, final MonitorProperties.Endpoints.JdbcSecurity jdbc) throws Exception { val cfg = auth.jdbcAuthentication(); cfg.usersByUsernameQuery(jdbc.getQuery()); cfg.rolePrefix(jdbc.getRolePrefix()); cfg.da...
python
def dropdb(self, name): ''' Deletes an **entire database** (i.e. a table), losing all data. ''' if self.readonly: raise s_exc.IsReadOnly() while True: try: if not self.dbexists(name): return db = self.in...
python
def _wrap(self, line: str) -> str: """ Returns an import wrapped to the specified line-length, if possible. """ wrap_mode = self.config['multi_line_output'] if len(line) > self.config['line_length'] and wrap_mode != WrapModes.NOQA: line_without_comment = line ...
python
def loadRecord(self, domain, rtype, callback=None, errback=None): """ Load a high level Record object from a domain within this Zone. :param str domain: The name of the record to load :param str rtype: The DNS record type :rtype: ns1.records.Record :return: new Record ...
python
def set_room_topic(self, room_id, topic, timestamp=None): """Perform PUT /rooms/$room_id/state/m.room.topic Args: room_id (str): The room ID topic (str): The new room topic timestamp (int): Set origin_server_ts (For application services only) """ body ...
python
def im(mn, op, params, **kwparams): """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.InvokeMethod`. Invoke a method on a target instance or on a target class. The methods that can be invoked are static and non-static methods defined in a class (also known as *extrinsic* methods...
java
@SuppressWarnings("unchecked") public void addWriter(RecordWriter<SerializationDelegate<T>> writer) { // avoid using the array-list here to reduce one level of object indirection if (this.writers == null) { this.writers = new RecordWriter[] {writer}; } else { RecordWriter<SerializationDelegate<T>>[] ws ...
java
@JsonAnySetter public void setUnknownField(final String name, final Object value) { this.unknownFields.put(name, value); }
python
def _format_episode_name(names): """Takes a list of episode names, formats them into a string. If two names are supplied, such as "Pilot (1)" and "Pilot (2)", the returned string will be "Pilot (1-2)". Note that the first number is not required, for example passing "Pilot" and "Pilot (2)" will also...
python
def make_proxy_method(cls, name): """Creates a proxy function that can be used by Flasks routing. The proxy instantiates the FlaskView subclass and calls the appropriate method. :param name: the name of the method to create a proxy for """ i = cls() view = getatt...
python
def density(self): """ Ratio of non-sparse points to total (dense) data points represented in the frame """ tot_nonsparse = sum(ser.sp_index.npoints for _, ser in self.items()) tot = len(self.index) * len(self.columns) return tot_nonspa...
python
def approxUniform(N,bot=0.0,top=1.0): ''' Makes a discrete approximation to a uniform distribution, given its bottom and top limits and number of points. Parameters ---------- N : int The number of points in the discrete approximation bot : float The bottom of the uniform di...
python
def ms_contrast(self, viewer, event, data_x, data_y, msg=True): """Shift the colormap by dragging the cursor left or right. Stretch the colormap by dragging the cursor up or down. """ if not self.cancmap: return True msg = self.settings.get('msg_contrast', msg) ...
java
private void processSecurityRoles(WebAnnotations webAnnotations, Set<String> classesWithSecurityRoles, Class<? extends Annotation> securityAnnotation, boolean annotationForClass) throws UnableToAdaptException { for (String classWithSecurityRole : classesWithSecurityRoles) {...
java
@Deprecated public void cliOffline(String cause) throws ExecutionException, InterruptedException { checkPermission(DISCONNECT); setTemporarilyOffline(true, new ByCLI(cause)); }
python
def create_namespace(self, name, ignore_errors=False): """creates a namespace if it does not exist args: name: the name of the namespace ignore_errors(bool): Will ignore if a namespace already exists or there is an error creating the namespace ...
python
def parse_add_loopback(): """ Validate params when adding a loopback adapter """ class Add(argparse.Action): def __call__(self, parser, args, values, option_string=None): try: ipaddress.IPv4Interface("{}/{}".format(values[1], values[2])) except ipaddress...
java
public String executePostRequestAndRetrieveURL(BlackDuckPath path, Request.Builder requestBuilder) throws IntegrationException { String uri = pieceTogetherUri(blackDuckHttpClient.getBaseUrl(), path.getPath()); requestBuilder.uri(uri); return executePostRequestAndRetrieveURL(requestBuilder.build(...
python
def get_policies(self): """Returns all the Policies under the Identity namespace. Returns: (list): A list containing all the Policies under the Identity namespace. """ prefix = _IDENTITY_NS + _POLICY_NS policylist_list = [ _create_from_by...
java
@Nonnull public static List<TtlRunnable> gets(@Nullable Collection<? extends Runnable> tasks, boolean releaseTtlValueReferenceAfterRun, boolean idempotent) { if (null == tasks) return Collections.emptyList(); List<TtlRunnable> copy = new ArrayList<TtlRunnable>(); for (Runnable task : tasks)...
python
def create_tree(profile, tree): """Create a new tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. tree A l...
python
def extract_github_repo_and_revision_from_source_url(url): """Given an URL, return the repo name and who owns it. Args: url (str): The URL to the GitHub repository Raises: ValueError: on url that aren't from github or when the revision cannot be extracted Returns: str, str: th...
java
private String forceAscii(StringBuilder source) { int length = source.length(); StringBuilder res = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = source.charAt(i); if ((c >= SAFE_ASCII_LOWER && c <= SAFE_ASCII_UPPER) || Character.isSpaceChar(c)) { res.append(c); } else { ...
python
def allow(ctx, foreign_account, permission, weight, threshold, account): """ Add a key/account to an account's permission """ if not foreign_account: from peerplaysbase.account import PasswordKey pwd = click.prompt( "Password for Key Derivation", hide_input=True, confirmation_pr...
java
public TokenMetadata cloneAfterAllSettled() { lock.readLock().lock(); try { TokenMetadata metadata = cloneOnlyTokenMap(); for (InetAddress endpoint : leavingEndpoints) metadata.removeEndpoint(endpoint); for (Pair<Token, InetAddress> pai...
java
@Override public boolean nextKey() throws IOException { // first element (or empty) if (this.current == null) { if (this.done) { this.valuesIterator = null; return false; } this.current = this.reuse; if ((this.current = this.iterator.next(this.current)) != null) { this.comparator.setRefere...
python
def get(self, key, defaultvalue = None): """ Support dict-like get (return a default value if not found) """ (t, k) = self._getsubitem(key, False) if t is None: return defaultvalue else: return t.__dict__.get(k, defaultvalue)
python
def sharey(axes): """ Shared axes limits without shared locators, ticks, etc. By Joe Kington """ linker = Linker(axes) for ax in axes: ax._linker = linker
java
final public long getByteCount() throws InterruptedException, IOException { try { return getByteCount(0L); } catch (AsyncTimeoutException e) { // Should only happen if the future itself is marked with an AsyncTimeoutException if ((this.exception != null) ...
python
def tab_rowstack(ListOfTabArrays, mode='nulls'): """ "Vertical stacking" of tabarrays, e.g. adding rows. Wrapper for :func:`tabular.spreadsheet.rowstack` that deals with the coloring and returns the result as a tabarray. Method calls:: data = tabular.spreadsheet.rowstack(ListOfTabArrays,...
java
private Rational doubleSum(int n) { Rational resul = Rational.ZERO; for (int k = 0; k <= n; k++) { Rational jsum = Rational.ZERO; BigInteger bin = BigInteger.ONE; for (int j = 0; j <= k; j++) { BigInteger jpown = BigInteger.valueOf(j).pow(n); ...
java
public String buildSelectTemplates(String attributes) { List options = new ArrayList(); List values = new ArrayList(); TreeMap templates = null; int selectedIndex = -1; try { // get all available templates templates = CmsNewResourceXmlPage.getTemplates(ge...
python
def format_grib_name(self, selected_variable): """ Assigns name to grib2 message number with name 'unknown'. Names based on NOAA grib2 abbreviations. Args: selected_variable(str): name of selected variable for loading Names: 3: LCDC: Low Cloud Cover 4:...
python
def get(self, key, timeout=None): """Given a key, returns an element from the redis table""" key = self.pre_identifier + key # Check to see if we have this key unpickled_entry = self.client.get(key) if not unpickled_entry: # No hit, return nothing return N...
java
public static final void rotate(Structure structure, Matrix m){ AtomIterator iter = new AtomIterator(structure) ; while (iter.hasNext()) { Atom atom = iter.next() ; rotate(atom,m); } }
java
public Identity refreshIdentity() { Identity oldOid = getIdentity(); this.oid = getBroker().serviceIdentity().buildIdentity(myObj); return oldOid; }
python
def get_column_value(manager, table, record, column): """ Example : To get datapath_id from Bridge table get_column_value('Bridge', <bridge name>, 'datapath_id').strip('"') """ row = row_by_name(manager, record, table) value = getattr(row, column, "") if isinstance(value, list) and len(valu...
java
@Nonnull public static SSLContext getSslContext(@Nullable String keyStore, @Nullable String keyStorePassword, @Nullable String trustStore, @Nullable String trustStorePassword) { try { KeyManager[] keyManagers; if (keyStore == null) { keyManagers = null; } ...
python
def from_xml(xml): """ Convert :class:`.MARCXMLRecord` object to :class:`.EPublication` namedtuple. Args: xml (str/MARCXMLRecord): MARC XML which will be converted to EPublication. In case of str, ``<record>`` tag is required. Returns: st...
java
@Override public Blob loadForID(String id) throws SQLException { Connection c = dataSource.getConnection(); PreparedStatement preparedStatement = c.prepareStatement(loadStatement()); preparedStatement.setString(1, id); ResultSet r = preparedStatement.executeQuery(); if (r.was...
java
public static void parseReverseLookupDomain(PtrDnsAnswer.Builder dnsAnswerBuilder, String hostname) { dnsAnswerBuilder.fullDomain(hostname); final InternetDomainName internetDomainName = InternetDomainName.from(hostname); if (internetDomainName.hasPublicSuffix()) { // Use Guava to...
java
public static void iterate(InputStream is, String[] entryNames, ZipEntryCallback action) { iterate(is, entryNames, action, null); }
java
static <T, ID> Dao<T, ID> createDao(ConnectionSource connectionSource, Class<T> clazz) throws SQLException { return new BaseDaoImpl<T, ID>(connectionSource, clazz) { }; }