language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def mementoweb_api_tags(url): """ Parse list of :class:`TimeResource` objects based on the mementoweb.org. Args: url (str): Any url. Returns: list: :class:`TimeResource` objects. """ memento_url = "http://labs.mementoweb.org/timemap/json/" r = requests.get(memento_url + ur...
python
def get(self, value): """Returns the VRF configuration as a resource dict. Args: value (string): The vrf name to retrieve from the running configuration. Returns: A Python dict object containing the VRF attributes as key/value pairs. ...
python
def get_attr_text(self): """Get html attr text to render in template""" return ' '.join([ '{}="{}"'.format(key, value) for key, value in self.attr.items() ])
java
public Observable<ServiceResponse<VaultAccessPolicyParametersInner>> updateAccessPolicyWithServiceResponseAsync(String resourceGroupName, String vaultName, AccessPolicyUpdateKind operationKind, VaultAccessPolicyProperties properties) { if (resourceGroupName == null) { throw new IllegalArgumentExcept...
python
def get_info(line, bit_thresh): """ get info from either ssu-cmsearch or cmsearch output """ if len(line) >= 18: # output is from cmsearch id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16] sstart, send, strand = int(line[7]), int(line[8]), line[9] mstar...
python
def create_auth_header(username, key=None, key_file="~/.ssh/id_rsa", key_password=None): """ Create an HTTP Authorization header using a private key file. Either a key or a key_file must be provided. :param username: The username to authenticate as on the remote system. :param key: Optional. A pri...
python
def remove_diagonal(S): """Remove the diagonal of the matrix S. Parameters ---------- S : csr_matrix Square matrix Returns ------- S : csr_matrix Strength matrix with the diagonal removed Notes ----- This is needed by all the splitting routines which operate on...
python
def confd_state_netconf_listen_ssh_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") netconf = ET.SubElement(confd_state, "netconf") listen = ET....
java
public final void assignmentOperator() throws RecognitionException { int assignmentOperator_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 109) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1123:5: ( '=' | '+=' | '-=' | '*=' | '...
java
@Override public String process(String query, Map<String, Object> params) { return applySchema(schema, query); }
python
def change_last_focused_widget(self, old, now): """To keep track of to the last focused widget""" if (now is None and QApplication.activeWindow() is not None): QApplication.activeWindow().setFocus() self.last_focused_widget = QApplication.focusWidget() elif now is no...
python
def get_resource_siblings(raml_resource): """ Get siblings of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """ path = raml_resource.path return [res for res in raml_resource.root.resources if res.path == path]
python
def wnunid(a, b): """ Place the union of two double precision windows into a third window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnunid_c.html :param a: Input window A. :type a: spiceypy.utils.support_types.SpiceCell :param b: Input window B. :type b: spiceypy.utils.sup...
java
@Nonnull public static ImageInfoSpecificQCow2Encryption aes(@Nonnull QCryptoBlockInfoQCow aes) { ImageInfoSpecificQCow2Encryption self = new ImageInfoSpecificQCow2Encryption(); self.format = BlockdevQcow2EncryptionFormat.aes; self.aes = aes; return self; }
java
public LocalTime plusMinutes(long minutesToAdd) { if (minutesToAdd == 0) { return this; } int mofd = hour * MINUTES_PER_HOUR + minute; int newMofd = ((int) (minutesToAdd % MINUTES_PER_DAY) + mofd + MINUTES_PER_DAY) % MINUTES_PER_DAY; if (mofd == newMofd) { ...
java
@Override public URI rewriteURI(RequestContext rc) throws URISyntaxException { Request request = rc.request(); BalancerMember member = selectBalancerMember(rc); logger.debug("Selected {}", member.getName()); String path = request.path(); if (!path.startsWith(prefix)) { ...
java
protected String getCurrentProjectVersion() throws MojoFailureException { final Model model = readModel(mavenSession.getCurrentProject()); if (model.getVersion() == null) { throw new MojoFailureException( "Cannot get current project version. This plugin should be executed...
java
@Override public DescribeLifecycleHooksResult describeLifecycleHooks(DescribeLifecycleHooksRequest request) { request = beforeClientExecution(request); return executeDescribeLifecycleHooks(request); }
python
def init_from_adversarial_batches_write_to_datastore(self, submissions, adv_batches): """Populates data from adversarial batches and writes to datastore. Args: submissions: instance of CompetitionSubmissions adv_batches: instance of AversarialB...
python
def update(self, process_list): """Update the AMP""" # Get the systemctl status logger.debug('{}: Update stats using systemctl {}'.format(self.NAME, self.get('systemctl_cmd'))) try: res = check_output(self.get('systemctl_cmd').split()) except (OSError, CalledProcessEr...
java
public static GVRMesh createQuad(GVRContext ctx, String vertexDesc, float width, float height) { GVRMesh mesh = new GVRMesh(ctx, vertexDesc); mesh.createQuad(width, height); return mesh; }
java
@CanIgnoreReturnValue public Ordered containsAtLeast(@NullableDecl Object k0, @NullableDecl Object v0, Object... rest) { return containsAtLeastEntriesIn(accumulateMultimap(k0, v0, rest)); }
java
public void marshall(GetCurrentMetricDataRequest getCurrentMetricDataRequest, ProtocolMarshaller protocolMarshaller) { if (getCurrentMetricDataRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
java
@Override public int lookupIndex(String str) { int ret = data.get(str); if (ret ==-1 && !frozen) { ret = index.size(); data.put(str, ret); index.put(ret, str); } return ret; }
python
def make_sinks_api(client): """Create an instance of the Sinks API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_SinksAPI` :returns: A metrics API instance with the proper credentials. """ ge...
java
public static ByteBuffer decode(ByteBuffer input) throws IOException { byte[] out = new byte[input.remaining()]; int pos = 0; int endingSpaces = 0; int endingSpacesSkipped = 0; while (input.hasRemaining()) { byte b = input.get(); if ((b >= 33 && b <= 60) || (b >= 62 && b <= 126)) { out[pos++...
java
public static Path getLocalCache(URI cache, Configuration conf, Path baseDir, boolean isArchive, long confFileStamp, Path currentWorkDir, MRAsyncDiskService asyncDiskService) throws IOException { return getLoc...
java
private void readCode(final MethodVisitor mv, final Context context, int u) { // reads the header byte[] b = this.b; char[] c = context.buffer; int maxStack = readUnsignedShort(u); int maxLocals = readUnsignedShort(u + 2); int codeLength = readInt(u + 4); u += 8; ...
java
public ListJobExecutionsForJobResult withExecutionSummaries(JobExecutionSummaryForJob... executionSummaries) { if (this.executionSummaries == null) { setExecutionSummaries(new java.util.ArrayList<JobExecutionSummaryForJob>(executionSummaries.length)); } for (JobExecutionSummaryForJob...
java
@Override public DescribeAttachmentResult describeAttachment(DescribeAttachmentRequest request) { request = beforeClientExecution(request); return executeDescribeAttachment(request); }
java
public void analyze() { final Resources resources = new ProjectAnalyzer(analysis.classPaths) .analyze(analysis.projectClassPaths, analysis.projectSourcePaths, analysis.ignoredResources); if (resources.isEmpty()) { LogProvider.info("Empty JAX-RS analysis result, omitting outp...
java
private void remove(PollController conn) { if (conn == null) { return; } if (_lifecycle.isDestroyed()) { return; } _activeCount.incrementAndGet(); if (_activeCount.decrementAndGet() == 0 && _lifecycle.isDestroyed()) { destroy(); } }
python
def on_setexceptionbreakpoints_request(self, py_db, request): ''' :param SetExceptionBreakpointsRequest request: ''' # : :type arguments: SetExceptionBreakpointsArguments arguments = request.arguments filters = arguments.filters exception_options = arguments.excep...
python
def isVideo(self): """ Is the stream labelled as a video stream. """ val=False if self.__dict__['codec_type']: if self.codec_type == 'video': val=True return val
python
def IntegerAddition(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Adds one vertex to another :param left: a vertex to add :param right: a vertex to add """ return Integer(context.jvm_view().IntegerAdditionVertex, label...
java
@Override public List<String> getAudiences() { if (audience != null) { List<String> audiences = new ArrayList<String>(); for (String aud : audience) { audiences.add(aud); } return audiences; } else { return null; } ...
python
def get(self, url): """ To make a GET request to Falkonry API server :param url: string """ response = requests.get( self.host + url, headers={ 'Authorization': 'Bearer ' + self.token, 'x-falkonry-source':self.sourceHeader ...
python
def _make_builder_configs(): """Make built-in Librispeech BuilderConfigs. Uses 4 text encodings (plain text, bytes, subwords with 8k vocab, subwords with 32k vocab) crossed with the data subsets (clean100, clean360, all). Returns: `list<tfds.audio.LibrispeechConfig>` """ text_encoder_configs = [ ...
python
def rlgt(self, time=None, times=1, disallow_sibling_lgts=False): """ Uses class LGT to perform random lateral gene transfer on ultrametric tree """ lgt = LGT(self.copy()) for _ in range(times): lgt.rlgt(time, disallow_sibling_lgts) return lgt.tree
python
def GetDefinitionByName(self, name): """Retrieves a specific data type definition by name. Args: name (str): name of the data type definition. Returns: DataTypeDefinition: data type definition or None if not available. """ lookup_name = name.lower() if lookup_name not in self._defi...
java
public static StringBuilder chompChomp(StringBuilder builder) { return builder.delete(builder.length() - 2, builder.length()); }
java
public Accordion setIcons(UiIcon header, UiIcon headerSelected) { setIcons(new AccordionIcon(header, headerSelected)); return this; }
python
def create(self, width=0, depth=0, path=None, flags=0, seed=0): """Create new sketch Params: <int> width <str> path <int> flags <int> seed """ return self.create_method(self, width, depth, path, flags, seed)
python
def add_peer_to_bgp_speaker(self, speaker_id, body=None): """Adds a peer to BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/add_bgp_peer", body=body)
java
private void addGroupsForUser(final RestletUtilUser user, final Set<Group> userGroups, final Group currentGroup, final Set<Group> stack, final boolean inheritOnly) { if((currentGroup != null) && !stack.contains(currentGroup)) { stack.add(currentGroup); ...
python
def add_answer(self, inp, record): """Adds an answer""" if not record.suppressed_by(inp): self.add_answer_at_time(record, 0)
java
public void init() throws Exception { Iterator<UIProvider> providers = ServiceLoader.load(UIProvider.class).iterator(); uiProvider = providers.hasNext() ? providers.next() : new DefaultUIProvider(); }
java
@Override @SuppressWarnings("unchecked") public PlainTime apply(PlainTime entity) { ChronoOperator<PlainTime> operator = (ChronoOperator<PlainTime>) this.opDelegate; return operator.apply(entity); }
java
public synchronized String uninstallAddOns(List<String> addons) { StringBuilder errorMessages = new StringBuilder(); AddOnCollection aoc = this.getLocalVersionInfo(); if (aoc == null) { String error = Constant.messages.getString("cfu.cmdline.nocfu"); errorMessages.append(...
python
def get_language_from_json(language, key): """Finds the given language in a json file.""" file_name = os.path.join( os.path.dirname(__file__), 'languages', '{0}.json').format(key.lower()) if os.path.exists(file_name): try: with open(file_name, 'r', encoding='utf...
python
def get_datastreams(self): """ To get list of Datastream """ datastreams = [] response = self.http.get('/Datastream') for datastream in response: datastreams.append(Schemas.Datastream(datastream=datastream)) return datastreams
java
public ServiceFuture<PrivateZoneInner> updateAsync(String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, final ServiceCallback<PrivateZoneInner> serviceCallback) { return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, privateZoneName, parame...
python
def get_rows(self): """Get the rows from a broadcast ratings chart""" table = self.soup.find_all('tr')[1:-3] return [row for row in table if row.contents[3].string]
java
public void destroy() { if (isStarted()) throw new IllegalStateException("Started"); if (_components!=null && _eventListeners!=null) { for (int c=0;c<LazyList.size(_components);c++) { Object o=LazyList.get(_components,c); i...
java
@Deprecated public static BigtableTableAdminClient create( @Nonnull com.google.bigtable.admin.v2.InstanceName instanceName) throws IOException { return create(instanceName.getProject(), instanceName.getInstance()); }
python
def fill_layer_combo(self): """Fill layer combobox.""" project = QgsProject.instance() # MapLayers returns a QMap<QString id, QgsMapLayer layer> layers = list(project.mapLayers().values()) extensions = tuple(extension_siblings.keys()) for layer in layers: if ...
python
def publish_json(self, channel, obj): """Post a JSON-encoded message to channel.""" return self.publish(channel, json.dumps(obj))
python
def _gpdfit(x): """Estimate the parameters for the Generalized Pareto Distribution (GPD). Empirical Bayes estimate for the parameters of the generalized Pareto distribution given the data. Parameters ---------- x : array sorted 1D data array Returns ------- k : float ...
java
Object resolveThisFieldReference( CallStack callstack, NameSpace thisNameSpace, Interpreter interpreter, String varName, boolean specialFieldsVisible ) throws UtilEvalError { if ( varName.equals("this") ) { /* Somewhat of a hack. If the special fi...
python
def retry_timeout(api, retries=3): """Retry API call when a timeout occurs.""" @wraps(api) def retry_api(*args, **kwargs): """Retrying API.""" for i in range(1, retries + 1): try: return api(*args, **kwargs) except RequestTimeout: if i ...
python
def popen(args, **kwargs): """Wrapper for `subprocess.Popen`. Avoids python bug described here: https://bugs.python.org/issue3905. This can arise when apps (maya) install a non-standard stdin handler. In newer version of maya and katana, the sys.stdin object can also become replaced by an object w...
python
def truncate(self, rev: int) -> None: """Delete everything after the given revision.""" self.seek(rev) self._keys.difference_update(map(get0, self._future)) self._future = [] if not self._past: self._beginning = None
java
public static int getLevenshteinDistance(String firstString, String secondString) { final String s0 = firstString == null ? "" : firstString; //$NON-NLS-1$ final String s1 = secondString == null ? "" : secondString; //$NON-NLS-1$ final int len0 = s0.length() + 1; final int len1 = s1.length() + 1; // the arr...
java
public boolean isBlank() { return (null == getInclude() || getInclude().isBlank()) && (null == getExclude() || getExclude().isBlank()) && null==getSingleNodeName(); }
python
def median(numbers): """ Return the median of the list of numbers. see: http://mail.python.org/pipermail/python-list/2004-December/294990.html """ # Sort the list and take the middle element. n = len(numbers) copy = sorted(numbers) if n & 1: # There is an odd number of elements ...
java
private Expression coerceTypeForSwitchComparison(ExprRootNode expr) { Expression switchOn = translateExpr(expr); SoyType type = expr.getType(); // If the type is possibly a sanitized content type then we need to toString it. if (SoyTypes.makeNullable(StringType.getInstance()).isAssignableFrom(type) ...
java
public static Iterator<MutableIntTuple> clampingIterator( IntTuple min, IntTuple max, Iterator<? extends MutableIntTuple> delegate) { Utils.checkForEqualSize(min, max); IntTuple localMin = IntTuples.copy(min); IntTuple localMax = IntTuples.copy(max); return cl...
java
private void initWorkspace(WorkspaceEntry wsConfig) throws RepositoryException { WorkspaceContainer workspaceContainer = getWorkspaceContainer(wsConfig.getName()); // touch independent components workspaceContainer.getComponentInstanceOfType(IdGenerator.class); // Init Root and jcr:system ...
java
public void forEach(Consumer<? super T> action) { connections.values().forEach(sync -> sync.doWithConnection(action)); }
python
def date_range(data): """Returns the minimum activity start time and the maximum activity end time from the active entities response. These dates are modified in the following way. The hours (and minutes and so on) are removed from the start and end times and a *day* is added to the end time. These are ...
java
public static void validate (@Nonnull final Schema aSchema, @Nonnull final Source aXML, @Nonnull final ErrorList aErrorList) { validate (aSchema, aXML, aErrorList, (Locale) null); }
java
private String replaceTags(String orig, String relPath) { String result = orig.replaceAll("(?m)^\\s*\\*", ""); // todo precompile regex // {@link processing hack} result = replaceAllTags(result, "", "", LINK_REGEX, relPath); // {@code processing hack} result = replaceAllTags(re...
java
public PublishLayerVersionResult withCompatibleRuntimes(String... compatibleRuntimes) { if (this.compatibleRuntimes == null) { setCompatibleRuntimes(new com.amazonaws.internal.SdkInternalList<String>(compatibleRuntimes.length)); } for (String ele : compatibleRuntimes) { t...
python
def import_descriptor_loader(definition_name, importer=__import__): """Find objects by importing modules as needed. A definition loader is a function that resolves a definition name to a descriptor. The import finder resolves definitions to their names by importing modules when necessary. Arg...
java
public String getSessionid(boolean create) { String sessionid = getCookie(SESSIONID_NAME, null); if (create && (sessionid == null || sessionid.isEmpty())) { sessionid = context.createSessionid(); this.newsessionid = sessionid; } return sessionid; }
python
def get_item_concept_mapping(self, lang): """ Get mapping of items_ids to concepts containing these items Args: lang (str): language of concepts Returns: dict: item (int) -> set of concepts (int) """ concepts = self.filter(active=True, lang=lang) ...
java
public STTYModeSwitcher setSTTYMode(STTYMode mode) { try { return new STTYModeSwitcher(mode, runtime); } catch (IOException e) { throw new UncheckedIOException(e); } }
python
def get_connections_by_dest(self, dest): '''Search for all connections between this and another port.''' with self._mutex: res = [] for c in self.connections: if c.has_port(self) and c.has_port(dest): res.append(c) return res
python
def get_method_analysis_by_name(self, class_name, method_name, method_descriptor): """ Returns the crossreferencing object for a given method. This function is similar to :meth:`~get_method_analysis`, with the difference that you can look up the Method by name :param class_name...
java
protected boolean hasNoInvalidScope(Attributes a) { String scope = a.getValue(SCOPE); if ((scope != null) && !scope.equals(PAGE_SCOPE) && !scope.equals(REQUEST_SCOPE) && !scope.equals(SESSION_SCOPE) && !scope.equals(APPLICATION_SCOPE)) { return false; ...
python
def handle_json_GET_triprows(self, params): """Return a list of rows from the feed file that are related to this trip.""" schedule = self.server.schedule try: trip = schedule.GetTrip(params.get('trip', None)) except KeyError: # if a non-existent trip is searched for, the return nothing ...
python
def setup(self): """ Banana banana """ info('Setting up %s' % self.project_name, 'project') for extension in list(self.extensions.values()): info('Setting up %s' % extension.extension_name) extension.setup() sitemap = SitemapParser().parse(self.s...
java
@Override public void Invoke(final String method, JSONArray args, HubInvokeCallback callback) { if (method == null) { throw new IllegalArgumentException("method"); } if (args == null) { throw new IllegalArgumentException("args"); } final S...
python
def dump(obj, fp, imports=None, binary=True, sequence_as_stream=False, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=Fals...
java
public Javalin put(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) { return addHandler(HandlerType.PUT, path, handler, permittedRoles); }
python
def _restore_file_attributes(self): # type: (Descriptor) -> None """Restore file attributes for file :param Descriptor self: this """ if (not self._restore_file_properties.attributes or self._ase.file_attributes is None): return # set file uid/...
python
def photparse(tab): """ Parse through a photometry table to group by source_id Parameters ---------- tab: list SQL query dictionary list from running query_dict.execute() Returns ------- newtab: list Dictionary list after parsing to group together sources """ # Ch...
python
def from_files(cls, files_to_sort, reader=None, **kwargs): """Create multiple Scene objects from multiple files. This uses the :func:`satpy.readers.group_files` function to group files. See this function for more details on possible keyword arguments. .. versionadded:: 0.12 ...
java
protected void addJsFiles(JavaScriptObject files) { JsArray<CmsFileInfo> cmsFiles = files.cast(); List<CmsFileInfo> fileObjects = new ArrayList<CmsFileInfo>(); for (int i = 0; i < cmsFiles.length(); ++i) { fileObjects.add(cmsFiles.get(i)); } addFiles(fileObjects); ...
python
def align(fastq_file, pair_file, ref_file, names, align_dir, data, extra_args=None): """Do standard or paired end alignment with bowtie. """ num_hits = 1 if data["analysis"].lower().startswith("smallrna-seq"): num_hits = 1000 config = data['config'] out_file = os.path.join(alig...
python
def measurement_time_typical(self): """Typical time in milliseconds required to complete a measurement in normal mode""" meas_time_ms = 1.0 if self.overscan_temperature != OVERSCAN_DISABLE: meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_temperature)) if self.oversca...
python
def datashape_type_to_numpy(type_): """ Given a datashape type, return the associated numpy type. Maps datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the numpy datetime returned by datashape isn't supported by pipeline. Parameters ---------- type_: datashape.coretypes.Ty...
java
@Override public FileNode mkfile() throws MkfileException { try { Files.createFile(path); } catch (IOException e) { throw new MkfileException(this, e); } return this; }
python
def scan(self): """Scan for bluetooth devices.""" try: res = subprocess.check_output(["hcitool", "scan", "--flush"], stderr=subprocess.STDOUT) except subprocess.CalledProcessError: raise BackendError("'hcitool scan' returned erro...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.RESOURCE_SECTION_NUMBER__RES_SNUM: setResSNum(RES_SNUM_EDEFAULT); return; } super.eUnset(featureID); }
python
def combine_futures(*futures): """ Combines set of Futures. :param futures: (Futures), Futures to be combined. :return: Result of the combination. """ expected = len(futures) results = [] completed = AtomicInteger() combined = Future() def done(f): if not combined.done(...
java
public void setBudgetedAndActualAmountsList(java.util.Collection<BudgetedAndActualAmounts> budgetedAndActualAmountsList) { if (budgetedAndActualAmountsList == null) { this.budgetedAndActualAmountsList = null; return; } this.budgetedAndActualAmountsList = new java.util.Ar...
java
public static String trimQuotes(String val) { if ((val.charAt(0) == '"') && (val.charAt(val.length() - 1) == '"')) { return val.substring(1, val.length() - 1); } return val; }
python
def add_prefix(self, auth, attr, args=None): """ Add a prefix and return its ID. * `auth` [BaseAuth] AAA options. * `attr` [prefix_attr] Prefix attributes. * `args` [add_prefix_args] Arguments explaining how the prefix should b...
java
protected static IJavaClassField findField( IJavaClassInfo cls, String name ) { IJavaClassField[] allFields = cls.getFields(); for (IJavaClassField f : allFields) { if (f.getName().equals(name)) { return f; } } IJavaClassField match = findDeclaredField( cls, name ); if ( match ...