language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def save_seedhex_file(self, path: str) -> None: """ Save hexadecimal seed file from seed :param path: Authentication file path """ seedhex = convert_seed_to_seedhex(self.seed) with open(path, 'w') as fh: fh.write(seedhex)
python
def websso(request): """Logs a user in using a token from Keystone's POST.""" referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL) auth_url = utils.clean_up_auth_url(referer) token = request.POST.get('token') try: request.user = auth.authenticate(request=request, auth_...
python
def setDateReceived(self, value): """Sets the date received to this analysis request and to secondary analysis requests """ self.Schema().getField('DateReceived').set(self, value) for secondary in self.getSecondaryAnalysisRequests(): secondary.setDateReceived(value) ...
python
def add_argument(self, arg_name, arg_value): '''Add an additional argument to be passed to the fitness function via additional arguments dictionary; this argument/value is not tuned Args: arg_name (string): name/dictionary key of argument arg_value (any): dictionary valu...
java
public static HeartbeatServices fromConfiguration(Configuration configuration) { long heartbeatInterval = configuration.getLong(HeartbeatManagerOptions.HEARTBEAT_INTERVAL); long heartbeatTimeout = configuration.getLong(HeartbeatManagerOptions.HEARTBEAT_TIMEOUT); return new HeartbeatServices(heartbeatInterval, h...
java
public R setPreviousListEvents(E listEvents){ mListEvents = listEvents; this.setStreamPosition(((IStreamPosition)mListEvents).getNextStreamPosition().toString()); return (R)this; }
java
@Nonnull public <V1 extends T1, V2 extends T2> LToByteBiFunctionBuilder<T1, T2> aCase(Class<V1> argC1, Class<V2> argC2, LToByteBiFunction<V1, V2> function) { PartialCaseWithByteProduct.The pc = partialCaseFactoryMethod((a1, a2) -> (argC1 == null || argC1.isInstance(a1)) && (argC2 == null || argC2.isInstance(a2))); ...
java
public Templates newTemplates(Source source) throws TransformerConfigurationException { String baseID = source.getSystemId(); if (null != baseID) { baseID = SystemIDResolver.getAbsoluteURI(baseID); } if (source instanceof DOMSource) { DOMSource dsource = (DOMSource) sour...
java
public static IVarargDependencyInjector bean(final Object target) { return new AbstractVarargDependencyInjector() { public void with(Object... dependencies) { TypeBasedInjector injector = new TypeBasedInjector(); for (Object dependency : dependencies) { injector.validateInjectionOf(target, depend...
python
def _update_ned_query_history( self): """*Update the database helper table to give details of the ned cone searches performed* *Usage:* .. code-block:: python stream._update_ned_query_history() """ self.log.debug('starting the ``_update_ned_quer...
python
def links(self) -> _Links: """All found links on page, in as–is form. Only works for Atom feeds.""" return list(set(x.text for x in self.xpath('//link')))
python
def start(self, proxy=None, cookie_db=None, disk_cache_dir=None, disk_cache_size=None): ''' Starts chrome/chromium process. Args: proxy: http proxy 'host:port' (default None) cookie_db: raw bytes of chrome/chromium sqlite3 cookies database, ...
python
def issue(self, issue_instance_id): """Select an issue. Parameters: issue_instance_id: int id of the issue instance to select Note: We are selecting issue instances, even though the command is called issue. """ with self.db.make_session() as session: ...
python
def override(self, obj): """Overrides the plain fields of the dashboard.""" for field in obj.__class__.export_fields: setattr(self, field, getattr(obj, field))
java
private int getColorDigit( int idx, CssFormatter formatter ) { Expression expression = get( idx ); double d = expression.doubleValue( formatter ); if( expression.getDataType( formatter ) == PERCENT ) { d *= 2.55; } return colorDigit(d); }
java
public static RepeatingView createFieldList(String id, Class<?> bean, Map<String, String> values) { List<AttributeDefinition> attributes = MethodUtil.buildAttributesList(bean); return createFieldList(id, attributes, values); }
python
def p_expression_uor(self, p): 'expression : OR expression %prec UOR' p[0] = Uor(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
python
def validate(item, namespace='accounts', version=2, context=None): """Validate item against version schema. Args: item: data object namespace: backend namespace version: schema version context: schema context object """ if namespace == 'accounts': if version ...
python
def cmd(send, msg, args): """Microwaves something. Syntax: {command} <level> <target> """ nick = args['nick'] channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel'] levels = { 1: 'Whirr...', 2: 'Vrrm...', 3: 'Zzzzhhhh...', ...
python
def ebs_volume_exists(region, volume_id, access_key_id, secret_access_key): """ finds out if a ebs volume exists """ conn = connect_to_ec2(region, access_key_id, secret_access_key) for vol in conn.get_all_volumes(): if vol.id == volume_id: return True
python
def pairedBEDIterator(inputStreams, mirror=False, mirrorScore=None, ignoreStrand=False, ignoreScore=True, ignoreName=True, sortedby=ITERATOR_SORTED_END, scoreType=float, verbose=False): """ Iterate over multiple BED format files simultaneously and yi...
java
public static List<UIParameter> getValidUIParameterChildren( FacesContext facesContext, List<UIComponent> children, boolean skipNullValue, boolean skipUnrendered) { return getValidUIParameterChildren(facesContext, children, skipNullValue, skipUnrendered, true); }
python
def route_create(credential_file=None, project_id=None, name=None, dest_range=None, next_hop_instance=None, instance_zone=None, tags=None, network=None, priority=None ...
python
def get_bits(block_representation, coin_symbol='btc', api_key=None): ''' Takes a block_representation and returns the number of bits ''' return get_block_overview(block_representation=block_representation, coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits']
java
@NonNull private ScrollListener createScrollViewScrollListener() { return new ScrollListener() { @Override public void onScrolled(final boolean scrolledToTop, final boolean scrolledToBottom) { adaptDividerVisibilities(scrolledToTop, scrolledToBottom, true); ...
java
@Override public SchemaManager getSchemaManager(Map<String, Object> puProperties) { if (schemaManager == null) { initializePropertyReader(); setExternalProperties(puProperties); schemaManager = new CouchbaseSchemaManager(CouchbaseClientFactory.class.getName(),...
python
def dump(self, tempy_tree_list, filename, pretty=False): """Dumps a Tempy object to a python file""" if not filename: raise ValueError('"filename" argument should not be none.') if len(filename.split(".")) > 1 and not filename.endswith(".py"): raise ValueError( ...
java
public static <T> Mono<T> illegalState(String format, Object... args) { String message = String.format(format, args); return Mono.error(new IllegalStateException(message)); }
java
protected static void cloneInternal ( JAASAuthenticator to, JAASAuthenticator from ) { Kerb5Authenticator.cloneInternal(to, from); to.serviceName = from.serviceName; to.configuration = from.configuration; to.cachedSubject = from.cachedSubject; }
python
def expand(self): """ Builds a list of single dimensional variables representing current variable. Examples: For single dimensional variable, it is returned as is discrete of (0,2,4) -> discrete of (0,2,4) For multi dimensional variable, a list of variables is returned, ...
java
@XmlElementDecl(namespace = PROV_NS, name = "role") public JAXBElement<Role> createRole(Role value) { return new JAXBElement<Role>(_Role_QNAME, Role.class, null, value); }
python
def _ondim(self, dimension, valuestring): """Converts valuestring to int and assigns result to self.dim If there is an error (such as an empty valuestring) or if the value is < 1, the value 1 is assigned to self.dim Parameters ---------- dimension: int \tDimens...
java
private void sendMessageToSelfAndDeferRetirement(ActiveInvokeContext<EhcacheEntityResponse> context, KeyBasedServerStoreOpMessage message, Chain newChain) { try { long clientId = context.getClientSource().toLong(); entityMessenger.messageSelfAndDeferRetirement(message, new PassiveReplicationMessage.Chai...
python
def parse(cls, format): """ Parse a format string. Factory function for the Format class. :param format: The format string to parse. :returns: An instance of class Format. """ fmt = cls() # Return an empty Format if format is empty if not format: ...
java
public static void apply(Element element, int offset, Functions.Func callback) { MaterialScrollfire scrollfire = new MaterialScrollfire(); scrollfire.setElement(element); scrollfire.setCallback(callback); scrollfire.setOffset(offset); scrollfire.apply(); }
python
def get_date_from_utterance(tokenized_utterance: List[Token], year: int = 1993) -> List[datetime]: """ When the year is not explicitly mentioned in the utterance, the query assumes that it is 1993 so we do the same here. If there is no mention of the month or day then we do n...
java
public static String getName(String datatypeKey) { Datatype datatype = getDatatype(datatypeKey); return datatype.getName(); }
python
def receive_message(source, auth=None, timeout=0, debug=False): """Receive a single message from an AMQP endpoint. :param source: The AMQP source endpoint to receive from. :type source: str, bytes or ~uamqp.address.Source :param auth: The authentication credentials for the endpoint. This should be...
python
def has_missing_break(real_seg, pred_seg): """ Parameters ---------- real_seg : list of integers The segmentation as it should be. pred_seg : list of integers The predicted segmentation. Returns ------- bool : True, if strokes of two different symbols are put in ...
java
public void set(IntFloatSortedVector other) { this.used = other.used; this.indices = IntArrays.copyOf(other.indices); this.values = FloatArrays.copyOf(other.values); }
java
Object convertArgument(String arg, Type paramType) throws IllegalArgumentException { Object result = null; if (null == arg || "null".equals(arg)) { return result; } logger.debug("Try to convert {} : param = {} : {}", new Object[]{arg, paramType, paramType.getClass()}); try { // GenericArrayType, Para...
python
def evalAsync(self, amplstatements, callback, **kwargs): """ Interpret the given AMPL statement asynchronously. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. callback: Callback to be executed when the state...
python
def unique_list_dicts(dlist, key): """Return a list of dictionaries which are sorted for only unique entries. :param dlist: :param key: :return list: """ return list(dict((val[key], val) for val in dlist).values())
python
def _psi(self,m): """\psi(m) = -\int_m^\infty d m^2 \rho(m^2)""" return 2.*self.a2*(1./(1.+m/self.a)+numpy.log(m/(m+self.a)))
python
def _parse(value, strict=True): """ Preliminary duration value parser strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration value exceed allowed values """ pattern = r'(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)' match = re.match(pattern, ...
java
public Observable<List<DatabaseInner>> listByServerAsync(String resourceGroupName, String serverName) { return listByServerWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<List<DatabaseInner>>, List<DatabaseInner>>() { @Override public List<DatabaseIn...
java
public static Map orderByValue(Map unsortMap, Comparator... comparators) { // Convert Map to List List<Map.Entry> list = new LinkedList<>(unsortMap.entrySet()); // Sort list with comparator, to compare the Map values Collections.sort(list, new Comparator<Map.Entry>() { publi...
java
@Override public CreateReceiptRuleResult createReceiptRule(CreateReceiptRuleRequest request) { request = beforeClientExecution(request); return executeCreateReceiptRule(request); }
java
static MultiMap removeCookieHeaders(MultiMap headers) { // We don't want to remove the JSESSION cookie. String cookieHeader = headers.get(COOKIE); if (cookieHeader != null) { headers.remove(COOKIE); Set<Cookie> nettyCookies = ServerCookieDecoder.STRICT.decode(cookieHeader); for (Cookie coo...
java
public void marshall(AttributeDefinition attributeDefinition, ProtocolMarshaller protocolMarshaller) { if (attributeDefinition == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(attributeDefinition.ge...
java
public boolean isSubscriptionPreApprovalSupported() throws NotLoggedInException { final XMPPConnection connection = getAuthenticatedConnectionOrThrow(); return connection.hasFeature(SubscriptionPreApproval.ELEMENT, SubscriptionPreApproval.NAMESPACE); }
python
def _add_keyword(self, collection_id, name, doc, args): """Insert data into the keyword table 'args' should be a list, but since we can't store a list in an sqlite database we'll make it json we can can convert it back to a list later. """ argstring = json.dumps(args) ...
java
public void setDiffuse(float red, float green, float blue){ diffuse[0] = red; diffuse[1] = green; diffuse[2] = blue; Di = true; }
python
def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Name...
python
def get_re_experiment(case, minor=1): """ Returns an experiment that uses the Roth-Erev learning method. """ locAdj = "ac" experimentation = 0.55 recency = 0.3 tau = 100.0 decay = 0.999 nStates = 3 # stateless RE? Pd0 = get_pd_max(case, profile) Pd_min = get_pd_min(case, profile...
java
public Observable<Void> beginCreateOrUpdateSecuritySettingsAsync(String deviceName, String resourceGroupName, AsymmetricEncryptedSecret deviceAdminPassword) { return beginCreateOrUpdateSecuritySettingsWithServiceResponseAsync(deviceName, resourceGroupName, deviceAdminPassword).map(new Func1<ServiceResponse<Void...
java
public void start(BundleContext context) throws Exception { ClassServiceUtility.log(context, LogService.LOG_INFO, "Starting " + this.getClass().getName() + " Bundle"); this.context = context; this.init(); // Setup the properties String interfaceClassName = getInterfaceClassNa...
java
protected void handleConfigureResponseFailure(MemberState member, ConfigureRequest request, Throwable error) { // Log the failed attempt to contact the member. failAttempt(member, error); }
java
public static Map<String, Object> generateMap(InputStream inputStream) { logger.trace("Converting XML document [{}]"); Map<String, Object> map = asMap(inputStream); logger.trace("Generated JSON: {}", map); return map; }
python
def simulate_roi(self, name=None, randomize=True, restore=False): """Generate a simulation of the ROI using the current best-fit model and replace the data counts cube with this simulation. The simulation is created by generating an array of Poisson random numbers with expectation value...
python
def setAttributesJson(self, attributesJson): """ Sets the attributes dictionary from a JSON string. """ try: self._attributes = json.loads(attributesJson) except: raise exceptions.InvalidJsonException(attributesJson) return self
java
public static File[] listFiles(final File aDir, final FilenameFilter aFilter, final boolean aDeepListing, final String... aIgnoreList) throws FileNotFoundException { if (!aDir.exists()) { throw new FileNotFoundException(aDir.getAbsolutePath()); } if (aDir.isFile()) { ...
java
public static boolean isAnonymousDiamond(JCTree tree) { switch(tree.getTag()) { case NEWCLASS: { JCNewClass nc = (JCNewClass)tree; return nc.def != null && isDiamond(nc.clazz); } case ANNOTATED_TYPE: return isAnonymousDiamond(((JCAnnotatedType...
python
def sys_mem_limit(self): """Determine the default memory limit for the current service unit.""" if platform.machine() in ['armv7l']: _mem_limit = self.human_to_bytes('2700M') # experimentally determined else: # Limit for x86 based 32bit systems _mem_limit = s...
java
public void dumpObjectMetaData() { LOGGER.debug("dump class={}", className); LOGGER.debug("----------------------------------------"); for (FieldMetaData md : fieldList) { LOGGER.debug(md.toString()); } }
python
def tokenize(text, format=None): """ tokenize text for word segmentation :param text: raw text input :return: tokenize text """ text = Text(text) text = text.replace("\t", " ") tokens = re.findall(patterns, text) tokens = [token[0] for token in tokens] if format == "text": ...
python
def _update_secret(namespace, name, data, apiserver_url): '''Replace secrets data by a new one''' # Prepare URL url = "{0}/api/v1/namespaces/{1}/secrets/{2}".format(apiserver_url, namespace, name) # Prepare data data = [{"op": "replace", "path...
python
def items(self): """ :return: a list of name/value attribute pairs sorted by attribute name. """ sorted_keys = sorted(self.keys()) return [(k, self[k]) for k in sorted_keys]
python
def guess_interval(nums, accuracy=0): """Given a seq of number, return the median, only calculate interval >= accuracy. :: from torequests.utils import guess_interval import random seq = [random.randint(1, 100) for i in range(20)] print(guess_interval(seq, 5)) # sorted...
java
TextView generateSplit(int i) { TextView split = new TextView(getContext()); int generateViewId = PinViewUtils.generateViewId(); split.setId(generateViewId); setStylesSplit(split); pinSplitsIds[i] = generateViewId; return split; }
python
def to_edgelist(self): """ Export the current transforms as a list of edge tuples, with each tuple having the format: (node_a, node_b, {metadata}) Returns ------- edgelist: (n,) list of tuples """ # save cleaned edges export = [] #...
java
public Material addVoice(InputStream inputStream, String fileName) { return upload(MediaType.voice, inputStream, fileName); }
python
def set_change(name, change): ''' Sets the time at which the password expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the password to never expire. CLI Example: .. code-block:: bash salt '*' ...
java
public final static PipeConnectionEvent build(AbstractPipe source, EventType type, IProvider provider, Map<String, Object> paramMap) { return new PipeConnectionEvent(source, type, provider, paramMap); }
java
public static MenuItem newMenuItem(final IModel<String> labelModel) { final MenuItem menuItem = new MenuItem(labelModel); return menuItem; }
java
public static <T extends Comparable<T>> int compare(Iterable<T> collection1, Iterable<T> collection2) { return compare(collection1.iterator(), collection2.iterator()); }
java
@Deprecated @JsonProperty public List<Object> getLiteralArguments() { List<Object> result = new ArrayList<>(); for (ClientTypeSignatureParameter argument : arguments) { switch (argument.getKind()) { case NAMED_TYPE: result.add(argument.getNamed...
python
def get_instances(self): """Returns a list of the instances of all the configured nodes. """ return [c.get('instance') for c in self.runtime._nodes.values() if c.get('instance')]
java
@Override public EClass getIfcGeographicElementType() { if (ifcGeographicElementTypeEClass == null) { ifcGeographicElementTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(301); } return ifcGeographicElementTypeEClass; }
python
def location_path(cls, project, location): """Return a fully-qualified location string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}", project=project, location=location, )
java
public <T, E extends Exception> Nullable<T> mapIfNotEmpty(Try.Function<? super String, T, E> mapper) throws E { N.checkArgNotNull(mapper); return buffer == null ? Nullable.<T> empty() : Nullable.of(mapper.apply(toString())); }
python
def set_maintenance_mode(value): """ Set maintenance_mode state to state file. """ # If maintenance mode is defined in settings, it can't be changed. if settings.MAINTENANCE_MODE is not None: raise ImproperlyConfigured( 'Maintenance mode cannot be set dynamically ' '...
python
def load_stylesheet(pyside=True): """ Loads the stylesheet. Takes care of importing the rc module. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file if pyside: import qdarkstyle.pyside_styl...
java
public void write(Bean bean, OutputStream output) throws IOException { write(bean, true, output); }
java
public void marshall(InstanceHealthSummary instanceHealthSummary, ProtocolMarshaller protocolMarshaller) { if (instanceHealthSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(instanceHealthSu...
java
public List<WsByteBuffer> compress(WsByteBuffer buffer) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "compress, input=" + buffer); } List<WsByteBuffer> list = new LinkedList<WsByteBuffer>(); list = compress(list, buffer); if (Trace...
python
def _validate_datetime_from_to(cls, start, end): """ validate from-to :param start: Start Day(YYYYMMDD) :param end: End Day(YYYYMMDD) :return: None or MlbAmException """ if not start <= end: raise MlbAmBadParameter("not Start Day({start}) <= End Day({e...
java
public void setText(String strText) { if ((strText == null) || (strText.length() == 0)) { if (!m_bInFocus) { strText = m_strDescription; this.changeFont(true); } } else this.changeFont(false); sup...
java
private void computeScales() { int width = getWidth(); int height = getHeight(); width = (width-borderSize)/2; // compute the scale factor for each image scaleLeft = scaleRight = 1; if( leftImage.getWidth() > width || leftImage.getHeight() > height ) { double scaleX = (double)width/(double)leftImage.ge...
python
def randomize(self, rand_gen=None, *args, **kwargs): """ Randomize the model. Make this draw from the prior if one exists, else draw from given random generator :param rand_gen: np random number generator which takes args and kwargs :param flaot loc: loc parameter for random number generator :p...
java
public static List<ColumnMetaData> buildColumns(final String colsAsCsv) { final List<ColumnMetaData> listCol = new ArrayList<>(); buildColumns(listCol, colsAsCsv); return listCol; }
java
@Override public Place getGeoDetails(String placeId) throws TwitterException { return factory.createPlace(get(conf.getRestBaseURL() + "geo/id/" + placeId + ".json")); }
python
def _parse_processor_embedded_health(self, data): """Parse the get_host_health_data() for essential properties :param data: the output returned by get_host_health_data() :returns: processor details like cpu arch and number of cpus. """ processor = self.get_value_as_list((data['...
java
public static void setThreadInstance(Application application) { if (instance == null) { instance = new ThreadLocalApplication(); } else if (!(instance instanceof ThreadLocalApplication)) { throw new IllegalStateException(); } ((ThreadLocalApplication) instance).setCurrentApplication(application); }
java
public final void setAxisAngle(Vector3D axis, double angle) { setAxisAngle(axis.getX(), axis.getY(), axis.getZ(), angle); }
python
def get_all_resources(datasets): # type: (List['Dataset']) -> List[hdx.data.resource.Resource] """Get all resources from a list of datasets (such as returned by search) Args: datasets (List[Dataset]): list of datasets Returns: List[hdx.data.resource.Resource]: l...
java
public void setRootComponent(final MvcComponent component) { if (uiThreadRunner.isOnUiThread()) { try { graph.setRootComponent(component); } catch (Graph.IllegalRootComponentException e) { throw new MvcGraphException(e.getMessage(), e); } ...
python
def child(self, subkey): """ Retrieves a subkey for this Registry key, given its name. @type subkey: str @param subkey: Name of the subkey. @rtype: L{RegistryKey} @return: Subkey. """ path = self._path + '\\' + subkey handle = win32.RegOpenKey(...
java
public static List<InetSocketAddress> getMasterRpcAddresses(AlluxioConfiguration conf) { // First check whether rpc addresses are explicitly configured. if (conf.isSet(PropertyKey.MASTER_RPC_ADDRESSES)) { return parseInetSocketAddresses(conf.getList(PropertyKey.MASTER_RPC_ADDRESSES, ",")); } // F...
python
def def_emb_sz(classes, n, sz_dict=None): "Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`." sz_dict = ifnone(sz_dict, {}) n_cat = len(classes[n]) sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb return n_cat,sz