language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static void callMethod(final Object obj, final String methodName, final boolean includePrivateMehtods, final Object... args) throws InvocationTargetException { final Class[] intArgsClass = initParamsClasses(args); try { Class<?> current = obj.getClass(); Method method = null; while (current...
java
public void setHUniformIncrement(Integer newHUniformIncrement) { Integer oldHUniformIncrement = hUniformIncrement; hUniformIncrement = newHUniformIncrement; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.METRIC_ADJUSTMENT__HUNIFORM_INCREMENT, oldHUniformIncreme...
java
public static boolean isAlive(String pid) { ShellCommandExecutor shexec = null; try { String[] args = { "kill", "-0", pid }; shexec = new ShellCommandExecutor(args); shexec.execute(); } catch (ExitCodeException ee) { return false; } catch (IOException ioe) { LOG.warn("Error...
python
def stream(command, stdin=None, env=os.environ, timeout=None): """ Yields a generator of a command's output. For line oriented commands only. Args: command (str or list): a command without pipes. If it's not a list, ``shlex.split`` is applied. stdin (file like object): stream to...
python
def parse_command_line(): """ Parses the command line and returns a ``Namespace`` object containing options and their values. :return: A ``Namespace`` object containing options and their values. """ import argparse parser = argparse.ArgumentParser(description=__doc__.split("\n")[0...
java
public static String[] splitWithCommaOrSemicolon(String src) { if (isEmpty(src)) { return StringUtils.EMPTY_STRING_ARRAY; } String[] ss = split(src.replace(',', ';'), ";"); List<String> list = new ArrayList<String>(); for (String s : ss) { if (!isBlank(s))...
python
def send_rpc_response(self, rpc_tag, result, response): """Send a response to an RPC. Args: rpc_tag (str): The exact string given in a previous call to send_rpc_command result (str): The result of the operation. The possible values of response are: service_not_f...
java
@Override public DisableAWSServiceAccessResult disableAWSServiceAccess(DisableAWSServiceAccessRequest request) { request = beforeClientExecution(request); return executeDisableAWSServiceAccess(request); }
java
public static String getCompiledJavaMajorVersionFromJavaClassFileAsString( InputStream classByteStream) throws Exception { int majorVersion = getCompiledJavaVersionFromJavaClassFile(classByteStream, true); switch (majorVersion) { case 50: return "Java 6"; ...
python
def get_current_user(): """Get user information from the id_token or oauth token in the request. This should only be called from within an Endpoints request handler, decorated with an @endpoints.method decorator. The decorator should include the https://www.googleapis.com/auth/userinfo.email scope. If `end...
java
public DomainInfos withDomainInfos(DomainInfo... domainInfos) { if (this.domainInfos == null) { setDomainInfos(new java.util.ArrayList<DomainInfo>(domainInfos.length)); } for (DomainInfo ele : domainInfos) { this.domainInfos.add(ele); } return this; }
java
public void start() throws IOException { log.trace("start()"); if (stopped) { throw new IOException("Unable to start connector as already stopped."); } // If this ConnectorServer has already started just return. if (started) { return; } l...
python
def get_driver_status(driver): # noqa: E501 """Retrieve the status of a loaded driver Retrieve the status of a loaded driver # noqa: E501 :param driver: The driver to use for the request. ie. github :type driver: str :rtype: Response """ response = errorIfUnauthorized(role='admin') ...
python
def update(self, iterable): """Add all the headers from the iterable to the set. :param iterable: updates the set with the items from the iterable. """ inserted_any = False for header in iterable: key = header.lower() if key not in self._set: ...
java
public MPApiResponse executeRequest(HttpMethod httpMethod, String uri, PayloadType payloadType, JsonObject payload, Collection<Header> colHeaders, int retries, int connectionTimeout, int socketTimeout) throws MPRestException { HttpClient httpClient = null; try { httpClient = getC...
java
public void setupProcedureResume(List<Integer> deps) { setupProcedureResume(com.google_voltpatches.common.primitives.Ints.toArray(deps)); }
java
protected static List<CmsSelectWidgetOption> getFormatterOptionsStatic( CmsObject cms, CmsADEConfigData config, String rootPath, boolean allRemoved) { Map<CmsUUID, I_CmsFormatterBean> inactiveFormatters = config.getInactiveFormatters(); List<CmsSelectWidgetOption> result...
python
def fold_string(input_string, max_width): """ Fold a string within a maximum width. Parameters: input_string: The string of data to go into the cell max_width: Maximum width of cell. Data is folded into multiple lines to fit into this width. Return: ...
python
def create_project(self, name=None, project_id=None, path=None): """ Create a project and keep a references to it in project manager. See documentation of Project for arguments """ if project_id is not None and project_id in self._projects: return self._projects[pro...
java
@SuppressWarnings("unchecked") public void distributedProcess(ResponseBuilder rb, ComponentFields mtasFields) throws IOException { // System.out.println("collection: " + System.nanoTime() + " - " // + Thread.currentThread().getId() + " - " // + rb.req.getParams().getBool("isShard", false) + " DISTRI...
java
public static ZonedDateTime ofInstant(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) { Objects.requireNonNull(localDateTime, "localDateTime"); Objects.requireNonNull(offset, "offset"); Objects.requireNonNull(zone, "zone"); if (zone.getRules().isValidOffset(localDateTime, of...
python
def add_query(self, query, join_with=AND): """Join a new query to existing queries on the stack. Args: query (tuple or list or DomainCondition): The condition for the query. If a ``DomainCondition`` object is not provided, the input should conform to the inte...
java
public static JsonPatch fromJson(final JsonNode node) throws IOException { requireNonNull(node, "node"); try { return Jackson.treeToValue(node, JsonPatch.class); } catch (JsonMappingException e) { throw new JsonPatchException("invalid JSON patch", e); } }
java
public void setSampledRequests(java.util.Collection<SampledHTTPRequest> sampledRequests) { if (sampledRequests == null) { this.sampledRequests = null; return; } this.sampledRequests = new java.util.ArrayList<SampledHTTPRequest>(sampledRequests); }
java
@Override public void echo(SystemLogHolder holder, LogRecord logRecord) { TraceWriter detailLog = traceLog; // Tee to messages.log (always) String message = formatter.messageLogFormat(logRecord, logRecord.getMessage()); messagesLog.writeRecord(message); invokeMessageRouters...
python
def layer(command=None, *args): 'hints the start of a new layer' if not command: return eval([['hint', 'layer']]) # fall back to buildin layer macro else: lst = [['layer']] for arg in args: lst.append([command, arg]) lst.append(['layer']) return eval(...
python
def _Parse(self): """Extracts attributes and extents from the volume.""" fsapfs_volume = self._file_entry.GetAPFSVolume() volume_attribute = volume_system.VolumeAttribute( 'identifier', fsapfs_volume.identifier) self._AddAttribute(volume_attribute) volume_attribute = volume_system.VolumeAt...
python
def unregister_file(self, file): """ Unregisters given file in the **file_system_events_manager**. :param file: File. :type file: unicode :return: Method success. :rtype: bool """ self.__engine.file_system_events_manager.is_path_registered(file) and \ ...
python
def posttrans_hook(conduit): """ Hook after the package installation transaction. :param conduit: :return: """ # Integrate Yum with Salt if 'SALT_RUNNING' not in os.environ: with open(CK_PATH, 'w') as ck_fh: ck_fh.write('{chksum} {mtime}\n'.format(chksum=_get_checksum(),...
python
def get_subdomains_count(db_path=None, zonefiles_dir=None): """ Static method for getting count of all subdomains Return number of subdomains on success """ opts = get_blockstack_opts() if not is_subdomains_enabled(opts): log.warn("Subdomain support is disabled") return None ...
python
def build_stats(counts): """Return stats information from counts structure.""" stats = { 'status': 0, 'reportnum': counts['reportnum'], 'title': counts['title'], 'author': counts['auth_group'], 'url': counts['url'], 'doi': counts['doi'], 'misc': counts['mi...
python
def generate(self): """ Generates a new random string from the start symbol Args: None Returns: str: The generated string """ result = self._gen(self.optimized, self.splitstring) if self.splitstring and result is not None: resu...
python
def unauthorized(self, response): '''Override to change the WWW-Authenticate challenge''' realm = current_app.config.get('HTTP_OAUTH_REALM', 'uData') challenge = 'Bearer realm="{0}"'.format(realm) response.headers['WWW-Authenticate'] = challenge return response
python
def on_lstCanvasExpLayers_itemSelectionChanged(self): """Update layer description label .. note:: This is an automatic Qt slot executed when the category selection changes. """ self.parent.exposure_layer = self.selected_canvas_explayer() lblText = self.parent.get_laye...
python
def resource_get(self, resource_name): """ Return resource info :param resource_name: Resource name as returned by resource_get_list() :type resource_name: str :return: Resource information (empty if not found) name: Resource name hash: Resource hash ...
python
def _make_node(self, singular, plural, variables, plural_expr): """Generates a useful node from the data provided.""" # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], ...
python
def get_item(self, key): """ Returns the value associated with the key. """ keys = list(self.keys()) # make sure it exists if not key in keys: self.print_message("ERROR: '"+str(key)+"' not found.") return None try: x = eval(se...
python
def get_ticket_results(mgr, ticket_id, update_count=1): """Get output about a ticket. :param integer id: the ticket ID :param integer update_count: number of entries to retrieve from ticket :returns: a KeyValue table containing the details of the ticket """ ticket = mgr.get_ticket(ticket_id) ...
java
protected void layoutLabel () { Graphics2D gfx = _mgr.createGraphics(); if (gfx == null) { return; } try { gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, (_antiAliased) ? RenderingHints.V...
java
public void removeFromNavigation(CmsUUID entryId) { CmsClientSitemapEntry entry = getEntryById(entryId); CmsClientSitemapEntry parent = getEntry(CmsResource.getParentFolder(entry.getSitePath())); CmsSitemapChange change = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.remov...
java
void put(final AbstractBatchEntry batchEntry) { try { this.queue.put(batchEntry); } catch (InterruptedException e) { throw new RuntimeException(e); } if (this.queue.size() >= this.actions) { this.scheduler.submit(new Runnable() { @Override public void run() { ...
java
private static List<Character[]> getLeetSub(final String password, final String unleet_password) { List<Character[]> leet_subs = new ArrayList<>(); for (int i = 0; i < unleet_password.length(); i++) { if (password.charAt(i) != unleet_password.charAt(i)) { ...
java
public void beginRevokeAccess(String resourceGroupName, String snapshotName) { beginRevokeAccessWithServiceResponseAsync(resourceGroupName, snapshotName).toBlocking().single().body(); }
python
def script_dir_plus_file(filename, pyobject, follow_symlinks=True): """Get current script's directory and then append a filename Args: filename (str): Filename to append to directory path pyobject (Any): Any Python object in the script follow_symlinks (Optional[bool]): Follow symlinks o...
java
public static void unescapeUriQueryParam(final char[] text, final int offset, final int len, final Writer writer) throws IOException { unescapeUriQueryParam(text, offset, len, writer, DEFAULT_ENCODING); }
java
public void setSoapActionOnApiVersion(String apiVersion) { log.trace("API Version detected: " + apiVersion); if ("4.0".equals(apiVersion)) { soapAction = SoapAction.SOAP_ACTION_V40.toString(); } else if ("4.1".equals(apiVersion)) { soapAction = SoapAction.SOAP_ACT...
java
public String encode() throws IOException { FastStringWriter fsw = new FastStringWriter(); try { fsw.write("{"); ChartUtils.writeDataValue(fsw, "display", this.display, false); ChartUtils.writeDataValue(fsw, "color", this.color, true); ChartUtils.writeDa...
java
private void showBreadCrumb(@Nullable final CharSequence breadCrumbTitle) { CharSequence formattedBreadCrumbTitle = formatBreadCrumbTitle(breadCrumbTitle); if (isSplitScreen()) { breadCrumbToolbar.setTitle(formattedBreadCrumbTitle); } else if (!TextUtils.isEmpty(formattedBreadCrumbT...
java
protected <T, C> T processExecuteGroup(String name, C criteria, T result, Connection conn) throws CpoException { CallableStatement cstmt = null; CpoClass criteriaClass; T returnObject = null; Logger localLogger = criteria == null ? logger : LoggerFactory.getLogger(criteria.getClass()); JdbcCallable...
java
public static <T> C.List<T> toList(Iterable<? extends T> iterable) { if (iterable instanceof Collection) { return toList((Collection<T>) iterable); } ListBuilder<T> lb = new ListBuilder<T>(10); for (T t : iterable) { lb.add(t); } return lb.toList()...
java
public Signature prependArg(String name, Class<?> type) { String[] newArgNames = new String[argNames.length + 1]; System.arraycopy(argNames, 0, newArgNames, 1, argNames.length); newArgNames[0] = name; MethodType newMethodType = methodType.insertParameterTypes(0, type); return new...
python
def parse(readDataInstance): """ Returns a new L{FileHeader} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{FileHeader} object. @rtype: L{FileHeader} @return: A new L{ReadData} obje...
java
public static RealtimeTuningConfig makeDefaultTuningConfig(final @Nullable File basePersistDirectory) { return new RealtimeTuningConfig( defaultMaxRowsInMemory, 0L, defaultIntermediatePersistPeriod, defaultWindowPeriod, basePersistDirectory == null ? createNewBasePersistDir...
python
def get(self, url, auth_map=None): """Envia uma requisição GET para a URL informada. Se auth_map é diferente de None, então deverá conter as chaves NETWORKAPI_PASSWORD e NETWORKAPI_USERNAME para realizar a autenticação na networkAPI. As chaves e os seus valores são enviados no h...
python
def update(cls, card_id, card_generated_cvc2_id, type_=None, custom_headers=None): """ :type user_id: int :type card_id: int :type card_generated_cvc2_id: int :param type_: The type of generated cvc2. Can be STATIC or GENERATED. :type type_: str :ty...
python
def prior_prediction(self): """get a dict of prior prediction variances Returns ------- prior_prediction : dict dictionary of prediction name, prior variance pairs """ if self.__prior_prediction is not None: return self.__prior_prediction ...
java
public List<ICalendar> all() throws IOException { StreamReader reader = constructReader(); if (index != null) { reader.setScribeIndex(index); } try { List<ICalendar> icals = new ArrayList<ICalendar>(); ICalendar ical; while ((ical = reader.readNext()) != null) { if (warnings != null) { war...
java
private void updateRequiredOptions(Option option) throws AlreadySelectedException { if (option.isRequired()) { expectedOpts.remove(option.getKey()); } // if the option is in an OptionGroup make that option the selected option of the group if (options.getOptionGro...
python
def member(self, phlo_id, node_id, member_id, action, node_type='conference_bridge'): """ :param phlo_id: :param node_id: :param member_id: :param action: :param node_type: default value `conference_bridge` :return: """ ...
java
protected String[] getLibEntries(String dir) { String[] entries = new String[0]; File libdir = new File(dir); if (libdir.exists() && libdir.isDirectory()) { entries = libdir.list(); } return entries; }
java
protected ChannelsModel toChannelsModel(Channel[] channelAnnotations, KnowledgeNamespace knowledgeNamespace, ComponentModel componentModel, SwitchYardNamespace switchyardNamespace) { if (channelAnnotations == null || channelAnnotations.length == 0) { retur...
java
public void printFullFeatureMatrix(PrintWriter pw) { String sep = "\t"; for (int i = 0; i < featureIndex.size(); i++) { pw.print(sep + featureIndex.get(i)); } pw.println(); for (int i = 0; i < labels.length; i++) { pw.print(labelIndex.get(i)); Set<Integer> feats = new HashS...
python
def _compile_random_variable_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optiona...
java
private String string(JsonObject node, String key, String default_) { JsonElement value = node.get(key); if (value != null && value.isJsonPrimitive()) { return value.getAsString(); } return default_; }
java
@SuppressWarnings("unchecked") public <T> T get(PropertyKey<T> property) { return (T) properties.get(property.getName()); }
java
@Override public void writeFile(String arg0, Map result) { // Initial variables HashMap wthFile; // Data holder for whole weather data ArrayList wthRecords; // Daily data array HashMap wthRecord; // Data holder for daily data ...
java
@Override public long getLong(TemporalField field) { if (field instanceof ChronoField) { if (field == NANO_OF_DAY) { return toNanoOfDay(); } if (field == MICRO_OF_DAY) { return toNanoOfDay() / 1000; } return get0(fie...
python
def intensities(self): """ :returns: peak intensities :rtype: list of floats """ buf = ffi.new("double[]", self.size) ims.spectrum_intensities(self.ptr, buf) return list(buf)
java
public void readFields(ITuple tuple, Deserializer[] customDeserializers) throws IOException { readFields(tuple, readSchema, customDeserializers); }
python
def insert(self, context): """ Create connection pool. :param resort.engine.execution.Context context: Current execution context. """ status_code, msg = self.__endpoint.post( "/resources/jdbc-connection-pool", data={ "id": self.__name, "resType": self.__res_type, "datasourceClas...
java
@Nonnull public static LCharIntPredicate charIntPredicateFrom(Consumer<LCharIntPredicateBuilder> buildingFunction) { LCharIntPredicateBuilder builder = new LCharIntPredicateBuilder(); buildingFunction.accept(builder); return builder.build(); }
java
@VisibleForTesting static boolean isPghp(String line) { if (line == null) return false; else // return Pattern.matches("^(\\\\.*\\\\)?\\$PGHP.*$", line); return pghpPattern.matcher(line).matches(); }
python
def end_headers(self): """ Ends the headers part """ # Send them all at once for name, value in self._headers.items(): self._handler.send_header(name, value) self._handler.end_headers()
java
@Override public DescribeSigningJobResult describeSigningJob(DescribeSigningJobRequest request) { request = beforeClientExecution(request); return executeDescribeSigningJob(request); }
java
public void addScriptProperties(Content head) { HtmlTree javascript = HtmlTree.SCRIPT(pathToRoot.resolve(DocPaths.JAVASCRIPT).getPath()); head.addContent(javascript); if (configuration.createindex) { if (pathToRoot != null && script != null) { String ptrPath = pathToR...
java
public static JSONArray nodesToJSON(Collection<Node> s) { JSONArray a = new JSONArray(); for (Element e : s) { a.add(e.id()); } return a; }
python
def by_name(self, country, language="en"): """ Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string....
python
def _init_metadata(self): """stub""" QuestionTextsFormRecord._init_metadata(self) QuestionFilesFormRecord._init_metadata(self) super(QuestionTextsAndFilesMixin, self)._init_metadata()
java
public void marshall(GetRegionsRequest getRegionsRequest, ProtocolMarshaller protocolMarshaller) { if (getRegionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getRegionsRequest.getInclude...
java
public void addNewGrants(List<ResourceGrant> grants) { int numGranted = 0; int numAvailable = 0; synchronized(lockObject) { for (ResourceGrant grant: grants) { Integer requestId = grant.getId(); if (!requestedResources.containsKey(requestId) || !requestMap.containsKey(reque...
java
public static void runAndWait(final Runnable r) { try { if (r != null) { final Thread thread = new Thread(r); thread.start(); thread.join(); } } catch (final Exception ex) { LOG.debug("Thread has been interrupted and can...
java
public MBeanOperationInfo[] getOperationsInfo(ObjectName name) throws JMException { checkClientConnected(); try { return mbeanConn.getMBeanInfo(name).getOperations(); } catch (Exception e) { throw createJmException("Problems getting bean information from " + name, e); } }
python
def centroid(X): """ Calculate the centroid from a matrix X """ C = np.sum(X, axis=0) / len(X) return C
python
def announce(self, discovery): """ With the passed in Discovery class, attempt to announce to the host agent. """ try: url = self.__discovery_url() logger.debug("making announce request to %s" % (url)) response = None response = self.client...
python
def make_fileitem_stringlist_string(file_string, condition='contains', negate=False, preserve_case=False): """ Create a node for FileItem/StringList/string :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/StringList/string' content_typ...
java
public void usage(PrintStream out, Help.ColorScheme colorScheme) { out.print(usage(new StringBuilder(), getHelpFactory().create(getCommandSpec(), colorScheme))); out.flush(); }
java
@Override public DescribeResourceResult describeResource(DescribeResourceRequest request) { request = beforeClientExecution(request); return executeDescribeResource(request); }
python
def get_question_ids_for_assessment_part(self, assessment_part_id): """convenience method returns unique question ids associated with an assessment_part_id""" question_ids = [] for question_map in self._my_map['questions']: if question_map['assessmentPartId'] == str(assessment_part_i...
python
def removeText(self, text): ''' removeText - Removes the first occurace of given text in a text node (i.e. not part of a tag) @param text <str> - text to remove @return text <str/None> - The text in that block (text node) after remove, or None if not found NOTE...
java
public void doLoad(final Card card) { if (mAsyncLoader == null) { return; } if (!card.loading && !card.loaded) { card.loading = true; mAsyncLoader.loadData(card, new AsyncLoader.LoadedCallback() { @Override public void finish() ...
java
private static void locateForMemcacheBucket(final BinaryRequest request, final List<Node> nodes, final MemcachedBucketConfig config, CoreEnvironment env, RingBuffer<ResponseEvent> responseBuffer) { if (!keyIsValid(request)) { return; } NetworkAddress hostname = config.nodeF...
java
private void removeINodeFromDatanodeDescriptors(DatanodeDescriptor[] targets) { if (targets != null) { for (DatanodeDescriptor node : targets) { node.removeINode(this); } } }
python
def addPixmap(self, pixmap): """ Adds a pixmap to this graphics item. :param pixmap | <QtGui.QPixmap> """ # add the item to the group item = QtGui.QGraphicsPixmapItem(pixmap) self.addToGroup(item) return item
python
def total_digits(n: Literal) -> Optional[int]: """ 5.4.5 XML Schema Numberic Facet Constraints totaldigits and fractiondigits constraints on values not derived from xsd:decimal fail. """ return len(str(abs(int(n.value)))) + fraction_digits(n) if is_numeric(n) and n.value is not None else None
python
def _oncofuse_tissue_arg_from_config(data): """Retrieve oncofuse arguments supplied through input configuration. tissue_type is the library argument, which tells Oncofuse to use its own pre-built gene expression libraries. There are four pre-built libraries, corresponding to the four supported tissue t...
python
def dimensionNames(self): """ Returns a list with the dimension names of the underlying NCDF variable """ mainArrayDims = ['Dim{}'.format(dimNr) for dimNr in range(self._array.ndim)] nSubDims = len(self._subArrayShape) subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(n...
python
def connect(url, prefix=None, **kwargs): """ connect and return a connection instance from url arguments: - url (str): xbahn connection url """ return connection(url, prefix=get_prefix(prefix), **kwargs)
python
def _execute_command(self, command, sql): """ :raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified. """ if not self._sock: raise err.InterfaceError("(0, '')") # If the last query was unbuffered, make sure it fini...
java
@Override public void sawOpcode(int seen) { if (seenReturn && seenTransferOfControl && seenStateChange) { return; } if (DEBUG) { System.out.println(stack); System.out.println(getPC() + " : " + Const.getOpcodeName(seen)); } if ((seen == Co...
python
def getbyuuid(self, uuid): """Get a schema by given uuid. :param str uuid: schema uuid to retrieve. :rtype: Schema :raises: KeyError if uuid is not registered already. """ if uuid not in self._schbyuuid: raise KeyError('uuid {0} not registered'.format(uuid)) ...