language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def download_example_datasets(self): """ Download example datasets from `openSNP <https://opensnp.org>`_. Per openSNP, "the data is donated into the public domain using `CC0 1.0 <http://creativecommons.org/publicdomain/zero/1.0/>`_." Returns ------- paths : list of str ...
python
def resolve_links(self, link_resolver): """ Banana banana """ self.type_link = None self.type_tokens = [] for child in self.get_children_symbols(): child.resolve_links(link_resolver) for tok in self.input_tokens: if isinstance(tok, Link):...
python
def _set_commands(self, v, load=False): """ Setter method for commands, mapped from YANG variable /aaa_config/aaa/accounting/commands (container) If this variable is read-only (config: false) in the source YANG file, then _set_commands is considered as a private method. Backends looking to populate ...
java
public static boolean isSeparateChecksumBlockFilename(String name) { if (isBlockFileName(name) && name.indexOf('.') < 0 && name.indexOf('_', BLOCK_FILE_PREFIX.length()) < 0) { return true; } return false; }
python
def _valid_folder(self, base, name): """Return whether a folder can be searched.""" valid = True fullpath = os.path.join(base, name) if ( not self.recursive or ( self.folder_exclude_check is not None and not self.compare_directory(...
python
def update_health_check(HealthCheckId=None, HealthCheckVersion=None, IPAddress=None, Port=None, ResourcePath=None, FullyQualifiedDomainName=None, SearchString=None, FailureThreshold=None, Inverted=None, HealthThreshold=None, ChildHealthChecks=None, EnableSNI=None, Regions=None, AlarmIdentifier=None, InsufficientDataHea...
java
public final void variable_definition() throws RecognitionException { CommonTree varname=null; CommonTree q=null; CommonTree pattern=null; try { // src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:127:5: ( ^( VT_VAR_DEF varname= LITERAL ^( VT_QUAL (q= LITERAL )? ) (pattern= VT_PATTERN )? ) ) ...
python
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # Get original mean and standard deviations mean, stddevs = sup...
java
public Optional<AlertCondition> add(Entity entity, long conditionId) { return add(entity.getId(), entity.getType(), conditionId); }
java
public static StoreFactory init() { try { StoreFactory theStoreFactory = (StoreFactory) EPackage.Registry.INSTANCE.getEFactory(StorePackage.eNS_URI); if (theStoreFactory != null) { return theStoreFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return ne...
python
def append_fields(self, new_fields): ''' Add fields to the container :param new_fields: fields to append ''' for field in new_fields: self.push(field) if isinstance(field, Container): self.pop()
python
def search(self, query, **kwargs): """ Cruddy provides a limited but useful interface to search GSI indexes in DynamoDB with the following limitations (hopefully some of these will be expanded or eliminated in the future. * The GSI must be configured with a only HASH and not a R...
python
def fix_super_reload(this_class, self): """ Fixes an error where reload causes super(X, self) to raise an exception The problem is that reloading causes X to point to the wrong version of the class. This function fixes the problem by searching and returning the correct version of the class. See ex...
python
def get_stored_hash(self, temp_ver): """ Retrieves the hash for the given template version from the store Args: temp_ver (TemplateVersion): template version to retrieve the hash for Returns: str: hash of the given template version """ ...
java
public static void animate(View imageView, int durationMillis) { if (imageView != null) { AlphaAnimation fadeImage = new AlphaAnimation(0, 1); fadeImage.setDuration(durationMillis); fadeImage.setInterpolator(new DecelerateInterpolator()); imageView.startAnimation(fadeImage); } }
java
public void marshall(LoadBalancerInfo loadBalancerInfo, ProtocolMarshaller protocolMarshaller) { if (loadBalancerInfo == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(loadBalancerInfo.getElbInfoList...
java
public EClass getESU() { if (esuEClass == null) { esuEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(328); } return esuEClass; }
python
def where(self, key, value): """ Filter items by the given key value pair. :param key: The key to filter by :type key: str :param value: The value to filter by :type value: mixed :rtype: Collection """ return self.filter(lambda item: data_get(it...
java
public BaseMessageFilter linkRemoteSession(Object remoteSession) { return new ServerSessionMessageFilter(this.getQueueName(), this.getQueueType(), null, remoteSession, m_bPrivate, true); // This is hooked to a thin filter }
python
def conjugate(self, tense = 'present'): ''' Tries to conjugate a given verb using verbix.com.''' if self.tenses.has_key(tense): return self._extract(self.tenses[tense]) elif self.tenses.has_key(tense.title()): return self._extract(self.tenses[tense.title()]) return [None]
python
def solve(self, b, x0=None, tol=1e-5, maxiter=100, cycle='V', accel=None, callback=None, residuals=None, return_residuals=False): """Execute multigrid cycling. Parameters ---------- b : array Right hand side. x0 : array Initial guess. ...
python
def list(self, filter_guid=None, filter_ids=None, detailed=None, page=None): """ This API endpoint returns a paginated list of the plugins associated with your New Relic account. Plugins can be filtered by their name or by a list of IDs. :type filter_guid: str :param fi...
python
def http_resource(self, method, url, params=None, data=None): """ Makes an HTTP request. """ url = urllib_parse.urljoin(self.url, url) url = url if url.endswith("/") else url + "/" headers = None if method.lower() in self.unsupported_methods: header...
java
private void initialize() { this.level = 0; this.next = 0; this.empty = null; this.scoreIncrement = 1; this.ignore = null; this.vars = new LNGVector<>(); this.vals = new LNGByteVector(); this.phases = new LNGByteVector(); this.decisions = new LNGDo...
python
def generate_data(shp=[16, 20, 24]): """ Generating data """ x = np.ones(shp) # inserting box x[4:-4, 6:-2, 1:-6] = -1 x_noisy = x + np.random.normal(0, 0.6, size=x.shape) return x_noisy
java
public static Reflect onClass(String clazz) throws Exception { return new Reflect(null, ReflectionUtils.getClassForName(clazz)); }
java
public int deleteCascade(SpatialReferenceSystem srs) throws SQLException { int count = 0; if (srs != null) { // Delete Contents ForeignCollection<Contents> contentsCollection = srs.getContents(); if (!contentsCollection.isEmpty()) { ContentsDao dao = getContentsDao(); dao.deleteCascade(contentsCo...
python
def args_as_tuple(self): """FIXME: en fonction de la manière dont la commande a été générée (factory ou parser), le type des arguments est différent : string quand ça vient de la factory ou type normal depuis le parser. Il faut uniformiser tout ça !! """ value = self.arg...
python
def children(self): """Retrieve tags associated to the current node""" tags = {'*'} if self.tag: network_tags = {self.tag: self.campaign.network.tags[self.tag]} else: network_tags = self.campaign.network.tags for tag, configs in network_tags.items(): ...
python
def col (loc,strg): """Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} f...
java
@GwtIncompatible("incompatible method") public static String reflectionToString(final Object object, final ToStringStyle style) { return ReflectionToStringBuilder.toString(object, style); }
java
public Map<Integer, Long> getIdMappingCategories() { Map<Integer, Long> idMapping = new HashMap<Integer, Long>(); Session session = WikiHibernateUtil.getSessionFactory(this.dbConfig).getCurrentSession(); session.beginTransaction(); Iterator results = session.createQuery("select cat.id, ...
python
def date_this_century(self, before_today=True, after_today=False): """ Gets a Date object for the current century. :param before_today: include days in current century before today :param after_today: include days in current century after today :example Date('2012-04-04') ...
python
def _text(code, quiet_zone=4): """This method returns a text based representation of the QR code. This is useful for debugging purposes. """ buf = io.StringIO() border_row = '0' * (len(code[0]) + (quiet_zone*2)) #Every QR code start with a quiet zone at the top for b in range(quiet_zone): ...
python
def insert(self, index, text): """Insert line to the document """ if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(tex...
java
public Element attributes(String attributes) { if (log.isDebugEnabled() && attributes!=null && attributes.indexOf('=')>=0) log.debug("Set attribute with old method: "+attributes+ " on " + getClass().getName()); if (attributes==null) { this.at...
java
public T withTag(String k, String v) { extraTags.add(new BasicTag(k, v)); return (T) this; }
java
private List<Cmdb> getConfigurationItemList(HpsmSoapModel hpsmSoapModel) throws HygieiaException{ List<Cmdb> configurationItemList = new ArrayList<>(); boolean getMore = true; int startValue = 0; while(getMore){ String batchLimit = hpsmSettings.getCmdbBatchLimit(); int returnLimit = Integer.parseInt(ba...
java
static void setAppVisibility(Bundle args, AppVisibility visibility) { if (visibility == null) { visibility = AppVisibility.OPEN_COMPOSER; } switch (visibility) { case OPEN_COMPOSER: args.remove(EvernoteIntent.EXTRA_QUICK_SEND); args.remove...
java
public ReportDefinition withAdditionalArtifacts(String... additionalArtifacts) { if (this.additionalArtifacts == null) { setAdditionalArtifacts(new java.util.ArrayList<String>(additionalArtifacts.length)); } for (String ele : additionalArtifacts) { this.additionalArtifact...
python
def point_segment_distance(point, segment): """ >>> a = LineSegment(Point(1,0), Point(2,0)) >>> b = LineSegment(Point(2,0), Point(0,2)) >>> point_segment_distance(Point(0,0), a) 1.0 >>> "%0.2f" % point_segment_distance(Point(0,0), b) '1.41' """ assert isinstance(point, Point), \ ...
java
private CmsSearchParameters getSearchParameters(Map<String, String> params) { CmsSearchParameters searchParams = new CmsSearchParameters(); searchParams.setQuery(params.get(PARAM_QUERY)); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(params.get(PARAM_SORT))) { searchParams.setSortNam...
java
public final UserManagedCacheBuilder<K, V, T> withEventListeners(CacheEventListenerConfiguration... cacheEventListenerConfigurations) { UserManagedCacheBuilder<K, V, T> otherBuilder = new UserManagedCacheBuilder<>(this); otherBuilder.eventListenerConfigurations.addAll(Arrays.asList(cacheEventListenerConfigurati...
python
def _is_url(url): """ Used to determine if a given string represents a URL """ regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... ...
java
@FormattableElement(format = "w") public static <T extends ChronoEntity<T> & CalendarDate> StdCalendarElement<Integer, T> weekOfYear( Chronology<T> chronology, Weekmodel model ) { ChronoElement<Integer> e = findDayElement(chronology, "DAY_OF_YEAR"); if (e == null) { ...
python
def combine_numeric_values(self, other): """ numeric_values * sp_values """ if self.values is None: ret = IdValues() else: ret = sum([IdValues( {k: int(v) * int(other.values[key]) for k, v in value.items()}) for key, value i...
java
@Override protected int writeBytesWireFormat ( byte[] dst, int dstIndex ) { int start = dstIndex; SMBUtil.writeInt2(33, dst, dstIndex); dst[ dstIndex + 2 ] = this.fileInformationClass; dst[ dstIndex + 3 ] = this.queryFlags; dstIndex += 4; SMBUtil.writeInt4(this.fileIn...
python
def batch_taxonomy(list_of_taxids): """ Convert list of taxids to Latin names """ for taxid in list_of_taxids: handle = Entrez.efetch(db='Taxonomy', id=taxid, retmode="xml") records = Entrez.read(handle) yield records[0]["ScientificName"]
java
public static ParticleSystem loadConfiguredSystem(InputStream ref, ConfigurableEmitterFactory factory, ParticleSystem system, Color mask) throws IOException { if (factory == null) { factory = new ConfigurableEmitterFactory() { public ConfigurableEmitter createEmitter(String name) { return ne...
java
public ApiResponse<TargetsResponse> getTargetsWithHttpInfo(String searchTerm, String filterName, String types, String excludeGroup, String restrictGroup, String excludeFromGroup, String restrictToGroup, String sort, BigDecimal limit, String matchType) throws ApiException { com.squareup.okhttp.Call call = getTar...
python
def configure(self, config): """ Configure Monitor, pull list of what to monitor, initialize threads """ self.config = config self.update_monitors() # initialize thread pools for profile in ('worker', 'result'): for _ in range(config['threads'][profil...
python
def hashmodel(model, library=None): '''Calculate the Hash id of metaclass ``meta``''' library = library or 'python-stdnet' meta = model._meta sha = hashlib.sha1(to_bytes('{0}({1})'.format(library, meta))) hash = sha.hexdigest()[:8] meta.hash = hash if hash in _model_dict: rai...
java
@SuppressWarnings("unchecked") protected Map<String, Object> getNestedMap(Map<String, Object> map, String key) { Object value = map.get(key); if (value == null) { return Collections.emptyMap(); } return (Map<String, Object>) value; }
python
def make_call_types(f, globals_d): # type: (Callable, Dict) -> Tuple[Dict[str, Anno], Anno] """Make a call_types dictionary that describes what arguments to pass to f Args: f: The function to inspect for argument names (without self) globals_d: A dictionary of globals to lookup annotation d...
python
def dns_rr(self, ips): """Get the domains related to input domains. Args: domains: an enumerable of strings as domains Returns: An enumerable of resource records and features """ api_name = 'opendns-dns_rr' fmt_url_path = u'dnsdb/name/a/{0}.json' ...
java
public Operation waitFor(RetryOption... waitOptions) throws InterruptedException { RetrySettings waitSettings = RetryOption.mergeToSettings(DEFAULT_OPERATION_WAIT_SETTINGS, waitOptions); try { Operation operation = RetryHelper.poll( new Callable<Operation>() { ...
java
public RelatedTags getRelated(String tag) throws JinxException { JinxUtils.validateParams(tag); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.tags.getRelated"); params.put("tag", tag); return jinx.flickrGet(params, RelatedTags.class); }
java
public static AnyValueMap fromValue(Object value) { AnyValueMap result = new AnyValueMap(); result.setAsObject(value); return result; }
python
def _get_dim_size(start, stop, step): """Given start, stop, and stop, calculate the number of elements of this slice.""" assert step != 0 if step > 0: assert start < stop dim_size = (stop - start - 1) // step + 1 else: assert stop < start dim_size = (start - stop - 1)...
python
def short_description(self): """ HGVS nomenclature for genomic variants More info: http://www.hgvs.org/mutnomen/ """ if self.is_insertion: return "chr%s g.%d_%dins%s" % ( self.contig, self.start, self.start + 1, ...
java
public void warn(String format, Object ... params) { log.warn(colored(format, COLOR_WARNING, true, params)); }
python
def wait_for_mouse_move_from(self, origin_x, origin_y): """ Wait for the mouse to move from a location. This function will block until the condition has been satisified. :param origin_x: the X position you expect the mouse to move from :param origin_y: the Y position you expect ...
java
public void init(Map<String,Object> mapParams) { m_htDBList = new Hashtable<Object,PDatabase>(); m_mapParams = mapParams; Object strMinutes = this.getProperty(TIME); int iMinutes = -1; // Default time try { if (strMinutes instanceof String) iMin...
java
private List<TreeNode> getSelected(TreeNode parent) { List<TreeNode> result = new ArrayList<>(); for (TreeNode n : parent.getChildren()) { if (n.isSelected()) { result.add(n); } result.addAll(getSelected(n)); } return result; }
python
def handle_command_line(options): """ act upon command options """ options = merge(options, constants.DEFAULT_OPTIONS) engine = plugins.ENGINES.get_engine( options[constants.LABEL_TEMPLATE_TYPE], options[constants.LABEL_TMPL_DIRS], options[constants.LABEL_CONFIG_DIR], ) ...
java
public void updateUser(User user){ ProtocolHeader header = new ProtocolHeader(); header.setType(ProtocolType.UpdateUser); UpdateUserProtocol p = new UpdateUserProtocol(user); connection.submitRequest(header, p, null); }
python
def set_default_var(**vars): """Sets context variables using the key/value provided in the options """ for k, v in vars.iteritems(): current_context.vars.setdefault(k, v)
python
def _print_image(self, line, size): """ Print formatted image """ i = 0 cont = 0 buffer = "" self._raw(S_RASTER_N) buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0) self._raw(buffer.decode('hex')) buffer = "" while i < ...
python
def get_available_currencies(): """Return a list of all available Cryptonator currencies.""" r = requests.get(API_CURRENCIES) if r.status_code != requests.codes.ok: raise CryptonatorException( ("An error occurred while getting available currencies " "({} from Cryptonator).")...
java
void freeOutput() { state.pool.free( output ); output = outputs.size() > 0 ? outputs.removeLast() : null; }
python
def value(self) -> Union[bool, None]: """Returns the concrete value of this bool if concrete, otherwise None. :return: Concrete value or None """ self.simplify() if self.is_true: return True elif self.is_false: return False else: ...
java
public com.google.api.ads.adwords.axis.v201809.mcm.AccessRole getInviteeRole() { return inviteeRole; }
java
void applyGaussian(GrayF32 input, GrayF32 output, Kernel1D kernel) { tempBlur.reshape(input.width, input.height); GConvolveImageOps.horizontalNormalized(kernel, input, tempBlur); GConvolveImageOps.verticalNormalized(kernel, tempBlur,output); }
java
public void removeComponent(Object screenField) { // DO NOT call Object or inherited if (m_vScreenField != null) if (screenField != null) m_vScreenField.removeElement(screenField); // Remove this component }
python
def set_token(self, token): """ Set the token for the v20 context Args: token: The token used to access the v20 REST api """ self.token = token self.set_header( 'Authorization', "Bearer {}".format(token) )
java
public int deleteAll() throws SQLException { int count = 0; if (isTableExists()) { DeleteBuilder<GeometryIndex, GeometryIndexKey> db = deleteBuilder(); PreparedDelete<GeometryIndex> deleteQuery = db.prepare(); count = delete(deleteQuery); } return count; }
java
public void skipEofPacket() throws SQLException, IOException { Buffer buffer = reader.getPacket(true); switch (buffer.getByteAt(0)) { case EOF: break; case ERROR: ErrorPacket ep = new ErrorPacket(buffer); throw new SQLException("Could not connect: " + ep.getMessage(), ep.get...
python
def invertible_total_flatten(unflat_list): r""" Args: unflat_list (list): Returns: tuple: (flat_list, invert_levels) CommandLine: python -m utool.util_list --exec-invertible_total_flatten --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import...
java
public void sendShortPoll() { myExec.execute(new Runnable() { @Override public void run() { Object[] req = new Object[] { "SP", lastSeenSeq }; sendCallArray(req); } }); }
java
public void marshall(NodeRangeProperty nodeRangeProperty, ProtocolMarshaller protocolMarshaller) { if (nodeRangeProperty == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(nodeRangeProperty.getTargetN...
java
public AlignedBox3f toBoundingBoxWithCtrlPoints() { AlignedBox3f bb = this.logicalBounds==null ? null : this.logicalBounds.get(); if (bb==null) { bb = new AlignedBox3f(); buildLogicalBoundingBox(bb); this.logicalBounds = new SoftReference<>(bb); } return bb; }
java
public Deserializer getDeserializer(String type) throws HessianProtocolException { if (type == null || type.equals("")) { return null; } if (!transcriptionParams.contains(TranscribableParams.MajorOnlyPackageNaming)) { // look for vMajor type =...
java
public Section addSection(Container container, String title, Format format, String content) { return add(container, title, format, content); }
python
def metadataURL(self, value): """gets/sets the public metadata url""" if value != self._metadataURL: self._metadataURL = value self._metaFS = None
java
public Cursor<DataPointFound> findDataPoints(Series series, Interval interval, Predicate predicate) { return findDataPoints(series, interval, predicate, DateTimeZone.getDefault()); }
java
protected synchronized void doStart() throws Exception { if (isStarted()) return; _contextLog = LogFactory.getLog("org.browsermob.proxy.jetty.jetty.context."+getHttpContext().getHttpContextName()); if (_contextLog==null) _contextLog=log; ...
java
@Override public List<CPOptionCategory> findAll(int start, int end) { return findAll(start, end, null); }
python
def block1(self, value): """ Set the Block1 option. :param value: the Block1 value """ option = Option() option.number = defines.OptionRegistry.BLOCK1.number num, m, size = value if size > 512: szx = 6 elif 256 < size <= 512: ...
java
public void writeToDirectory(@NotNull LanguageProfile languageProfile, @NotNull File fullPath) throws IOException { if (!fullPath.exists()) { throw new IOException("Path does not exist: "+fullPath); } if (!fullPath.canWrite()) { throw new IOException("Path not writable: "...
python
def rpc_get_account_record(self, address, token_type, **con_info): """ Get the current state of an account """ if not check_account_address(address): return {'error': 'Invalid address', 'http_status': 400} if not check_token_type(token_type): return {'err...
python
def _minimize_powell(func, x0, cl_runtime_info, lower_bounds, upper_bounds, constraints_func=None, data=None, options=None): """ Options: patience (int): Used to set the maximum number of iterations to patience*(number_of_parameters+1) reset_method (str): one of 'EXTRAPOLATE...
python
def createSummary(self, log): """ Match log lines against warningPattern. Warnings are collected into another log for this step, and the build-wide 'warnings-count' is updated.""" # If there were any warnings, make the log if lines with warnings # available if s...
java
private void initFileSystem() throws IOException { if (fs == null) { Path path = new Path(basePath); fs = createHadoopFileSystem(path, fsConfig); } }
python
def tag(self, tokens): """Run individual chemical entity mention taggers and return union of matches, with some postprocessing.""" # Combine output from individual taggers tags = [None] * len(tokens) just_tokens = [t[0] for t in tokens] for tagger in self.taggers: tag...
java
@Override public CreateLoadBalancerTlsCertificateResult createLoadBalancerTlsCertificate(CreateLoadBalancerTlsCertificateRequest request) { request = beforeClientExecution(request); return executeCreateLoadBalancerTlsCertificate(request); }
java
private static <I, O> AsyncFunction<I, O> asAsyncFunction( final Function<? super I, ? extends O> function) { return new AsyncFunction<I, O>() { @Override public ListenableFuture<O> apply(I input) { O output = function.apply(input); return immediateFuture(output); } }; }
java
public String verboseToString() { String out = resultToString(getResult()); switch (result) { case BACK: case FAIL: out = out + vertex.throwableToString(); break; case FOLLOW: case SUCCEED: out = out + vertex.moreToString(); ...
java
public static systemglobal_auditnslogpolicy_binding[] get(nitro_service service) throws Exception{ systemglobal_auditnslogpolicy_binding obj = new systemglobal_auditnslogpolicy_binding(); systemglobal_auditnslogpolicy_binding response[] = (systemglobal_auditnslogpolicy_binding[]) obj.get_resources(service); retur...
java
public FessMessages addErrorsDesignJspFileDoesNotExist(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_design_jsp_file_does_not_exist)); return this; }
python
def element_data_from_Z(Z): '''Obtain elemental data given a Z number An exception is thrown if the Z number is not found ''' # Z may be a str if isinstance(Z, str) and Z.isdecimal(): Z = int(Z) if Z not in _element_Z_map: raise KeyError('No element data for Z = {}'.format(Z))...