language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected void addToList(List<IEObjectDescription> descriptions, List<IEObjectDescription> result) { result.addAll(descriptions); }
python
def close_alert(name=None, api_key=None, reason="Conditions are met.", action_type="Close"): ''' Close an alert in OpsGenie. It's a wrapper function for create_alert. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: ...
java
@POST @Produces({"script/groovy"}) @Path("src/{repository}/{workspace}/{path:.*}") public Response getScript(@PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { ses = se...
python
def cast_callback(value): """Override `cast_callback` method. """ # Postgresql / MySQL drivers change the format on 'TIMESTAMP' columns; if 'T' in value: value = value.replace('T', ' ') return datetime.strptime(value.split('.')[0], '%Y-%m-%d %H:%M:%S')
python
def _lats(self): """Return the latitudes (in degrees) of the gridded data.""" lats = _np.linspace(90.0, -90.0 + 180.0 / self.nlat, num=self.nlat) return lats
java
@Override public String extractSignedToken(String token) { String[] chunks = token.split("-", 3); if (chunks.length != 3) { // Invalid format return null; } String signature = chunks[0]; String nonce = chunks[1]; String raw = chunks[2]; ...
java
public boolean wasKeyTyped(int keyCode) { if (this.isKeyDown(keyCode) && !this.checked.contains(keyCode)) { this.checked.add(keyCode); return true; } return false; }
java
public boolean isRegistered( String clientID , String subscriptionName ) { String key = clientID+"-"+subscriptionName; return subscriptions.containsKey(key); }
python
def _wr_txt_nts(self, fout_txt, desc2nts, objgowr, verbose): """Write grouped and sorted GO IDs to GOs.""" with open(fout_txt, 'w') as prt: self._prt_ver_n_key(prt, verbose) prt.write('\n\n') prt.write('# ---------------------------------------------------------------...
python
def urlize_twitter(text): """ Replace #hashtag and @username references in a tweet with HTML text. """ html = TwitterText(text).autolink.auto_link() return mark_safe(html.replace( 'twitter.com/search?q=', 'twitter.com/search/realtime/'))
python
def fit(arr, dist='norm'): """Fit an array to a univariate distribution along the time dimension. Parameters ---------- arr : xarray.DataArray Time series to be fitted along the time dimension. dist : str Name of the univariate distribution, such as beta, expon, genextreme, gamma, gumbe...
java
public Any execute(DeviceImpl device, Any in_any) throws DevFailed { Util.out4.println("PolledDeviceCmd.execute(): arrived "); // Call the device method and return to caller return insert(((DServer)(device)).polled_device()); }
java
public List<String> parse(String[] args) { // merge args & defaults List<String> extras = new ArrayList<>(); List<String> filteredArgs = filterMonadics(args); // detect and fill mons for (int i = 0; i < filteredArgs.size(); i++) { String key = filteredArgs.get(i); ...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.MSU__RG: return rg != null && !rg.isEmpty(); } return super.eIsSet(featureID); }
python
def hset(self, hashkey, attribute, value): """Emulate hset.""" redis_hash = self._get_hash(hashkey, 'HSET', create=True) attribute = self._encode(attribute) attribute_present = attribute in redis_hash redis_hash[attribute] = self._encode(value) return long(0) if attribut...
java
public void setPreferredMacCS(String name) throws SshException { if (name == null) return; if (macCS.contains(name)) { prefMacCS = name; setMacPreferredPositionCS(name, 0); } else { throw new SshException(name + " is not supported", SshException.UNSUPPORTED_ALGORITHM); } }
java
@Override public java.util.concurrent.Future<ListOnPremisesInstancesResult> listOnPremisesInstancesAsync( com.amazonaws.handlers.AsyncHandler<ListOnPremisesInstancesRequest, ListOnPremisesInstancesResult> asyncHandler) { return listOnPremisesInstancesAsync(new ListOnPremisesInstancesRequest(), ...
python
def get_kibiter_version(url): """ Return kibiter major number version The url must point to the Elasticsearch used by Kibiter """ config_url = '.kibana/config/_search' # Avoid having // in the URL because ES will fail if url[-1] != '/': url += "/" url += config_url ...
java
public static RenderingContext anonymous(final ApplicationInfo appInfo, final CalendarProvider provider) { final UserImpl user2 = new UserImpl(); user2.setUsername("Anonymous"); user2.setFirstname("Al"); user2.setLastname("Anonymous"); user2.clearRoles(); user...
java
public static Stream<String> getLanguageCodes() { return Stream.of( LANGUAGE_CODE_EN, LANGUAGE_CODE_NL, LANGUAGE_CODE_DE, LANGUAGE_CODE_ES, LANGUAGE_CODE_IT, LANGUAGE_CODE_PT, LANGUAGE_CODE_FR, LANGUAGE_CODE_XX); }
java
public static boolean matchBitByBitIndex(final int pVal, final int pBitIndex) { if (pBitIndex < 0 || pBitIndex > MAX_BIT_INTEGER) { throw new IllegalArgumentException( "parameter 'pBitIndex' must be between 0 and 31. pBitIndex=" + pBitIndex); } return (pVal & 1 << pBitIndex) != 0; }
java
@Override public void setData(final Object data) { if (isRichTextArea() && data instanceof String) { super.setData(sanitizeInputText((String) data)); } else { super.setData(data); } }
python
def get_target_list(self, scan_id): """ Get a scan's target list. """ target_list = [] for target, _, _ in self.scans_table[scan_id]['targets']: target_list.append(target) return target_list
java
public List<Grant> getGrantsAsList() { checkState(); if (grantList == null) { if (grantSet == null) { grantList = new LinkedList<Grant>(); } else { grantList = new LinkedList<Grant>(grantSet); grantSet = null; } ...
python
def from_dict(self, document): """Create experiment object from JSON document retrieved from database. Parameters ---------- document : JSON Json document in database Returns ------- ExperimentHandle Handle for experiment object "...
java
static HeaderEntry parse(final String elementLine) throws IOException { if (!elementLine.startsWith("element ")) { throw new IOException("not an element: '" + elementLine + "'"); } String definition = elementLine.substring("element ".length()); String[] p...
python
def devices_data(): """Returns devices data. """ response = {} for part in psutil.disk_partitions(): device = part.device response[device] = { 'device': device, 'mountpoint': part.mountpoint, 'fstype': part.fstype, 'opts': part.opts, ...
python
def detect_python2(source, pathname): """ Returns a bool indicating whether we think the code is Py2 """ RTs.setup_detect_python2() try: tree = RTs._rt_py2_detect.refactor_string(source, pathname) except ParseError as e: if e.msg != 'bad input' or e.value != '=': rais...
java
protected void generatePackageUseFile() throws DocFileIOException { HtmlTree body = getPackageUseHeader(); HtmlTree div = new HtmlTree(HtmlTag.DIV); div.addStyle(HtmlStyle.contentContainer); if (usingPackageToUsedClasses.isEmpty()) { div.addContent(contents.getContent("doclet...
python
async def workerTypeStats(self, *args, **kwargs): """ Look up the resource stats for a workerType Return an object which has a generic state description. This only contains counts of instances This method gives output: ``v1/worker-type-resources.json#`` This method is ``experi...
java
public String includeJspString(String jspPath, HttpServletRequest httpRequest, HttpServletResponse httpResponse, WaybackRequest wbRequest, CaptureSearchResults results, CaptureSearchResult result, Resource resource) throws ServletException, IOException { if (wbRequest.isAjaxRequest()) { return ""; ...
java
public static boolean hasProperty(Class<?> clazz, Language language, String... propertyComponents) { return hasProperty(clazz.getName(), language, propertyComponents); }
java
public String directory(Node leftdir, Node rightdir, Filter filter) throws IOException { List<String> paths; paths = paths(leftdir, filter); paths(rightdir, filter, paths); return directory(leftdir, rightdir, paths); }
python
def _resume_ssl_session( server_info: ServerConnectivityInfo, ssl_version_to_use: OpenSslVersionEnum, ssl_session: Optional[nassl._nassl.SSL_SESSION] = None, should_enable_tls_ticket: bool = False ) -> nassl._nassl.SSL_SESSION: """Connect to the server and ret...
java
@Override public boolean isValid(Object obj, ConstraintValidatorContext constraintContext) { // Si l'Objet est null if(obj == null) return acceptNullObject; // Si l'Objet est un tableau if(obj.getClass().isArray()) { // Taille int size = Array.getLength(obj); // On retourne l...
python
def write_case_data(self, file): """ Writes the header to file. """ case_sheet = self.book.add_sheet("Case") case_sheet.write(0, 0, "Name") case_sheet.write(0, 1, self.case.name) case_sheet.write(1, 0, "base_mva") case_sheet.write(1, 1, self.case.base_mva)
java
private static RuntimeException getCause(InvocationTargetException e) { Throwable cause = e.getCause(); if(cause instanceof RuntimeException) throw (RuntimeException) cause; else throw new IllegalArgumentException(e.getCause()); }
python
def showMetadata(dat): """ Display the metadata specified LiPD in pretty print | Example | showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict dat: Metadata :return none: """ _tmp = rm_values_fields(copy.deepcopy(dat)) print(json.dumps(_tmp, indent=2)) return
python
def __analizar_observaciones(self, ret): "Comprueba y extrae observaciones si existen en la respuesta XML" self.Observaciones = [obs["codigoDescripcion"] for obs in ret.get('arrayObservaciones', [])] self.Obs = '\n'.join(["%(codigo)s: %(descripcion)s" % obs for obs in self.Observaciones])
python
def script(): """Run the command-line script.""" parser = argparse.ArgumentParser(description="Print all textual tags of one or more audio files.") parser.add_argument("-b", "--batch", help="disable user interaction", action="store_true") parser.add_argument("file", nargs="+", help="file(s) to print tag...
java
public String computeSignature(String requestMethod, String targetUrl, Map<String, String> params) { return computeSignature(requestMethod, targetUrl, params, consumerSecret, tokenSecret); }
java
public static NiftyProcessorFactory factoryFromTProcessor(final TProcessor standardThriftProcessor) { checkProcessMethodSignature(); return new NiftyProcessorFactory() { @Override public NiftyProcessor getProcessor(TTransport transport) { ...
python
def get(self, blueprint, user=None, user_id=None): """ When you have a statement in your code that says "if <provider>.authorized:" (for example "if twitter.authorized:"), a long string of function calls result in this function being used to check the Flask server's cache and database fo...
python
def compile_when_to_only_if(expression): ''' when is a shorthand for writing only_if conditionals. It requires less quoting magic. only_if is retained for backwards compatibility. ''' # when: set $variable # when: unset $variable # when: failed $json_result # when: changed $json_resul...
python
def critic(self, real_pred, input): "Create some `fake_pred` with the generator from `input` and compare them to `real_pred` in `self.loss_funcD`." fake = self.gan_model.generator(input.requires_grad_(False)).requires_grad_(True) fake_pred = self.gan_model.critic(fake) return self.loss_f...
python
def get_eco_map(url): """ To conver the three column file to a hashmap we join primary and secondary keys, for example IEA GO_REF:0000002 ECO:0000256 IEA GO_REF:0000003 ECO:0000501 IEA Default ECO:0000501 becomes IEA-GO_REF:0000002: ECO:0000256 ...
java
public static Map<String, ValueType> rowSignatureFor(final GroupByQuery query) { final ImmutableMap.Builder<String, ValueType> types = ImmutableMap.builder(); for (DimensionSpec dimensionSpec : query.getDimensions()) { types.put(dimensionSpec.getOutputName(), dimensionSpec.getOutputType()); } ...
python
def group(self, groupId): """ gets a group based on it's ID """ url = "%s/%s" % (self.root, groupId) return Group(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port,...
java
public VertexElement addVertexElementWithEdgeIdProperty(Schema.BaseType baseType, ConceptId conceptId) { return executeLockingMethod(() -> factory().addVertexElementWithEdgeIdProperty(baseType, conceptId)); }
java
@Override public File copy() throws IORuntimeException{ final File src = this.src; final File dest = this.dest; // check Assert.notNull(src, "Source File is null !"); if (false == src.exists()) { throw new IORuntimeException("File not exist: " + src); } Assert.notNull(dest, "Destination File ...
java
public ResultList<Company> searchCompanies(String query, Integer page) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.QUERY, query); parameters.add(Param.PAGE, page); URL url = new ApiUrl(apiKey, MethodBase.SEARCH).subMethod(MethodSub.CO...
python
def get_alert_community(self, channel=None): """Get the current community string for alerts Returns the community string that will be in SNMP traps from this BMC :param channel: The channel to get configuration for, autodetect by default :returns: The co...
java
public Observable<Void> deleteManagementPoliciesAsync(String resourceGroupName, String accountName) { return deleteManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> re...
python
def unzip_file_to_dir(path_to_zip, output_directory): """ Extract a ZIP archive to a directory """ z = ZipFile(path_to_zip, 'r') z.extractall(output_directory) z.close()
java
@SuppressWarnings("unchecked") public <T> Map<String, T> find(final Class<T> valueTypeToFind) { return (Map<String, T>) this.values.entrySet().stream() .filter(input -> valueTypeToFind.isInstance(input.getValue())) .collect( Collectors.toMap(Map.Entry:...
python
def parse_z(cls, offset): """ Parse %z offset into `timedelta` """ assert len(offset) == 5, 'Invalid offset string format, must be "+HHMM"' return timedelta(hours=int(offset[:3]), minutes=int(offset[0] + offset[3:]))
python
def reloading_meta_metaclass_factory(BASE_TYPE=type): """ hack for pyqt """ class ReloadingMetaclass2(BASE_TYPE): def __init__(metaself, name, bases, dct): super(ReloadingMetaclass2, metaself).__init__(name, bases, dct) #print('Making rrr for %r' % (name,)) metaself.r...
java
@Override protected void onCreate(Bundle savedInstanceState) { final RoboInjector injector = RoboGuice.getInjector(this); eventManager = injector.getInstance(EventManager.class); preferenceListener = injector.getInstance(PreferenceListener.class); injector.injectMembersWithoutViews(t...
java
public static List<Method> getAllMethod(Class<?> clazz) { return ALL_METHOD_CACHE.compute(clazz, (key, value) -> { if (value == null) { List<Method> methods = new ArrayList<>(); Map<String, Method> methodMap = getAllMethod(key, new HashMap<>()); metho...
python
def SaveDataToFD(self, raw_data, fd): """Merge the raw data with the config file and store it.""" fd.write(yaml.Dump(raw_data).encode("utf-8"))
python
def readBatchTupleQuotes(self, symbols, start, end): ''' read batch quotes as tuple to save memory ''' if end is None: end=sys.maxint ret={} session=self.getReadSession()() try: symbolChunks=splitListEqually(symbols, 100) ...
python
def set_caller(self, caller): """ Sets the caller after instantiation. """ self.caller = caller.__name__ self.module = inspect.getmodule(caller).__name__ self.load()
java
private final void eval(TagLibTag tlt, Data data, Tag tag) throws TemplateException { if (tlt.hasTTE()) { try { tlt.getEvaluator().execute(data.config, tag, tlt, data.flibs, data); } catch (EvaluatorException e) { throw new TemplateException(data.srcCode, e.getMessage()); } data.ep.add(tlt...
python
def encode(string, encoding=None, errors=None): """Encode to specified encoding. ``encoding`` defaults to the preferred encoding. ``errors`` defaults to the preferred error handler. """ if encoding is None: encoding = getpreferredencoding() if errors is None: errors = getpreferr...
java
@Override public GetPipelineDefinitionResult getPipelineDefinition(GetPipelineDefinitionRequest request) { request = beforeClientExecution(request); return executeGetPipelineDefinition(request); }
java
public void setServerEvents(java.util.Collection<ServerEvent> serverEvents) { if (serverEvents == null) { this.serverEvents = null; return; } this.serverEvents = new java.util.ArrayList<ServerEvent>(serverEvents); }
python
def eccentricity(self, directed=None, weighted=None): '''Maximum distance from each vertex to any other vertex.''' sp = self.shortest_path(directed=directed, weighted=weighted) return sp.max(axis=0)
java
public void unsubscribe(final Subscription<T> subscription) { final T token = subscription.getToken(); LOG.log(Level.FINER, "RemoteManager: {0} token {1}", new Object[]{this.name, token}); if (token instanceof Exception) { this.transport.registerErrorHandler(null); } else if (token instanceof Tupl...
python
def login_details(self): """ Gets the login details Returns: List of login details """ if not self.__login_details: self.__login_details = LoginDetails(self.__connection) return self.__login_details
python
def refresh(self, line=None): """Refreshes progress bar.""" # Just go away if it is locked. Will update next time if not self._lock.acquire(False): return if line is None: line = self._line if sys.stdout.isatty() and line is not None: self._w...
java
private static InputStream detatchResponseHeader(BufferedInputStream pIS) throws IOException { // Store header in byte array ByteArrayOutputStream bytes = new ByteArrayOutputStream(); pIS.mark(BUF_SIZE); byte[] buffer = new byte[BUF_SIZE]; int length; int headerEnd; ...
java
public void remove (SteeringBehavior<T> behavior) { for (int i = 0; i < list.size; i++) { if(list.get(i).behavior == behavior) { list.removeIndex(i); return; } } }
python
def parse_datetime(utc_timestamp_ms, utc_offset_ms): """ Create a timezone-aware ``datetime.datetime`` from the given UTC timestamp (in milliseconds), if provided. If an offest it given, it is applied to the datetime returned. Parameters ---------- utc_timestamp_ms UTC timestamp in ...
java
@Override public void flush() throws IOException { checkState(); uncheckedWriteTillByte(false); try { out.flush(); } catch(IOException e) { error = true; throw e; } }
python
def write_last_and_beds(pf, GenePositions, ContigStarts): """ Write LAST file, query and subject BED files. """ qbedfile = pf + "tigs.bed" sbedfile = pf + "chr.bed" lastfile = "{}tigs.{}chr.last".format(pf, pf) qbedfw = open(qbedfile, "w") sbedfw = open(sbedfile, "w") lastfw = open(l...
python
def run_with_plugins(plugin_list): """ Carry out a test run with the supplied list of plugin instances. The plugins are expected to identify the object to run. Parameters: plugin_list: a list of plugin instances (objects which implement some subset of PluginInterface) Returns: exit code as ...
python
def is_response(cls, response): '''Return whether the document is likely to be CSS.''' if 'css' in response.fields.get('content-type', '').lower(): return True if response.body: # Stylesheet mistakenly served as HTML if 'html' in response.fields.get('content-...
java
public void await() throws InterruptedException, EOFException { synchronized(this) { while ( (state.get() == State.STARTED) && !hasLeadership.get() ) { wait(); } } if ( state.get() != State.STARTED ) { throw new ...
java
public DbxDelta<DbxEntry> getDelta(/*@Nullable*/String cursor, boolean includeMediaInfo) throws DbxException { return _getDelta(cursor, null, includeMediaInfo); }
python
def ConsultarCondicionesVenta(self, sep="||"): "Retorna un listado de códigos y descripciones de las condiciones de ventas" ret = self.client.consultarCondicionesVenta( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': ...
python
def get(self, entity_id: EntityId, load: bool = False) -> Entity: """Get a Wikidata entity by its :class:`~.entity.EntityId`. :param entity_id: The :attr:`~.entity.Entity.id` of the :class:`~.entity.Entity` to find. :type eneity_id: :class:`~.entity.EntityId` :...
java
public <T> T executeWithUser(final String user, final String password, final SpecificUserAction<T> userAction) { Preconditions.checkState(!transactionManager.isTransactionActive(), "User can't be changed during transaction"); Preconditions.checkState(spec...
java
private DestinationHandler createForeignDestination(DestinationForeignDefinition dfd, String busName) throws SIResourceException, SINotPossibleInCurrentConfigurationException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createForeignDestination", new Object...
java
private void endWithMessage(ServerHttpExchange http, String data) { endedWithMessage.set(true); boolean jsonp = "true".equals(params.get("cettia-transport-jsonp")); if (jsonp) { try { data = params.get("cettia-transport-callback") + "(" + mapper.writeValueAsString(data) + ");"; ...
java
private static String unescapeColors (String txt, boolean restore) { if (txt == null) return null; String prefix = restore ? "#" : "%"; return ESCAPED_PATTERN.matcher(txt).replaceAll(prefix + "$1"); }
java
public void configureCreateNewElement(CmsObject cms, String pageFolderRootPath, CmsNewResourceBuilder builder) throws CmsException { checkOffline(cms); checkInitialized(); String folderPath = getFolderPath(cms, pageFolderRootPath); CmsVfsUtil.createFolder(cms, folderPath); S...
python
def rsync_git(local_path, remote_path, exclude=None, extra_opts=None, version_file='version.txt'): """Rsync deploy a git repo. Write and compare version.txt""" with settings(hide('output', 'running'), warn_only=True): print(green('Version On Server: ' + run('cat ' + '{}/{}'.format( ...
python
def notches( self ): """ Reutrns a list of the notches that are going to be used for this ruler. If the notches have not been explicitly set (per a Custom type), then the notches will be generated based on the minimum, maximum and step values the current ruler type. ...
java
public static <T> int countObjectsFromClause(Class<T> clazz, String clause, Object... args) { return SqlClosure.sqlExecute(c -> OrmElf.countObjectsFromClause(c, clazz, clause, args)); }
java
public static String ifNotEmptyAppend(String chekString, String value) { if (hasText(chekString)) { return value+chekString; } else { return ""; } }
java
public FrenchRepublicanMonth getMonth() { if (this.fdoy > 360) { throw new ChronoException( "Complementary days (sansculottides) do not represent any month: " + this.toString()); } int m = ((this.fdoy - 1) / 30) + 1; return FrenchRepublicanMonth.valueOf(m); ...
java
private ImmutableTriple<Integer,ResultSet,SQLWarning> update(final String sql, final int autoGeneratedKeys) throws SQLException { checkClosed(); try { final UpdateResult res = this.handler.whenSQLUpdate(sql, NO_PARAMS); final SQLWarning w = res.getWarning(); final R...
java
public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case OUTPUT_FIELDS: return is_set_output_fields(); case DIRECT: return is_set_direct(); } throw new IllegalStateException(); }
python
def remove_prohibited_element(tag_name, document_element): """ To fit the Evernote DTD need, drop this tag name """ elements = document_element.getElementsByTagName(tag_name) for element in elements: p = element.parentNode p.removeChild(element)
python
def read_relation_file(filename): ''' Reads the GermaNet relation file ``gn_relations.xml`` which lists all the relations holding between lexical units and synsets. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) lex_rels = []...
java
public static AuditorModuleContext getContext() { SecurityContext securityContext = SecurityContextFactory.getSecurityContext(); if (!securityContext.isInitialized()) { securityContext.initialize(); } AbstractModuleContext moduleContext = securityContext.getModuleContext(CONTEXT_ID); if (null == module...
java
@SuppressWarnings("unchecked") @FFDCIgnore(Exception.class) public static Collection<String> parseStringCollection(String propertyKey, Object obj, Collection<String> defaultValue) { if (obj != null) { try { if (obj instanceof Collection) { return (Collecti...
python
def main(): """"This main function implements the CLI""" parser = argparse.ArgumentParser(description='Do something awesome') parser.add_argument('input_list', nargs='+', type=str, default=sys.stdin) parser.add_argument('-o', '--outfile', nargs='?', type=a...
java
public Context merge(final OutputStream outputStream) { return merge(Vars.EMPTY, new OutputStreamOut(outputStream, engine)); }
python
def docker_client(): """ Returns a docker-py client configured using environment variables according to the same logic as the official Docker client. """ cert_path = os.environ.get('DOCKER_CERT_PATH', '') if cert_path == '': cert_path = os.path.join(os.environ.get('HOME', ''), '.docker')...