language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def read_namespaced_persistent_volume_claim_status(self, name, namespace, **kwargs): """ read status of the specified PersistentVolumeClaim This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.r...
python
def ensure_image(self): """ Ensure that config.image_url has been downloaded and unpacked. """ image_folder = self.get_image_folder() if os.path.exists(image_folder): print( 'OS image directory {} exists...not overwriting' .format( ...
java
public static CompletionStage<Void> copy(final ServiceBundler services, final Session session, final Resource resource, final IRI destination, final String baseUrl) { final Metadata.Builder builder = Metadata.builder(destination) .interactionModel(resource.getInteractionModel()); ...
java
private void forceDecreaseKeyToMinimum(Node<K, V> n) { Node<K, V> y = n.parent; if (y != null) { cut(n, y); root.mark = false; cascadingRankChange(y); root = link(root, n); } }
python
def get_functions_reading_from_variable(self, variable): ''' Return the functions reading the variable ''' return [f for f in self.functions if f.is_reading(variable)]
python
def render_impl(self, template, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ Render given template file and return the result. :param template: Template file path :param context: A dict or dict-like object to instantiate given ...
java
public void changeState(Class<? extends State> next) { Check.notNull(next); final State from = current; if (current != null) { last = current.getClass(); current.exit(); } if (!states.containsKey(next)) { final ...
java
public boolean validate(Signer signerToUse) throws CoseException { for (Signer r : signerList) { if (r == signerToUse) { return r.validate(rgbProtected, rgbContent); } } throw new CoseException("Signer not found"); }
python
def bfgs_method(f, x, line_search=1.0, maxiter=1000, tol=1e-15, num_store=None, hessinv_estimate=None, callback=None): r"""Quasi-Newton BFGS method to minimize a differentiable function. Can use either the regular BFGS method, or the limited memory BFGS method. Notes ----- This is ...
python
def calc_prediction(registered_map, preregistration_mesh, native_mesh, model): ''' calc_registration_prediction is a pimms calculator that creates the both the prediction and the registration_prediction, both of which are pimms itables including the fields 'polar_angle', 'eccentricity', and 'visual_area...
java
@Override public RemoveRoleFromDBClusterResult removeRoleFromDBCluster(RemoveRoleFromDBClusterRequest request) { request = beforeClientExecution(request); return executeRemoveRoleFromDBCluster(request); }
python
def eth_getBlockHeaderByNumber(self, number): """Get block header by block number. :param number: :return: """ block_hash = self.reader._get_block_hash(number) block_number = _format_block_number(number) return self.reader._get_block_header(block_hash, block_numb...
java
public List<ResourceHandle> getChildrenByType(final String type) { final ArrayList<ResourceHandle> children = new ArrayList<>(); if (this.isValid()) { for (final Resource child : this.resource.getChildren()) { ResourceHandle handle = ResourceHandle.use(child); ...
java
public <A extends Annotation> boolean hasAnnotation(final Field field, final Class<A> annClass) { return getAnnotation(field, annClass) != null; }
java
@Override protected LocalTime parse(final String string, final DateTimeFormatter formatter) { return LocalTime.parse(string, formatter); }
python
def link(self, link, title, text): """Rendering a given link with content and title. :param link: href link for ``<a>`` tag. :param title: title content for `title` attribute. :param text: text content for description. """ if self.anonymous_references: unders...
python
def add_metaclass(metaclass): """ Class decorator for creating a class with a metaclass. Adapted from the six project: https://pythonhosted.org/six/ """ vars_to_skip = ('__dict__', '__weakref__') def wrapper(cls): copied_dict = { key: value for key, value i...
python
def std_dev(self, value): """The std_dev property. Args: value (float). the property value. """ if value == self._defaults['stdDev'] and 'stdDev' in self._values: del self._values['stdDev'] else: self._values['stdDev'] = value
python
def toLily(self): ''' Method which converts the object instance, its attributes and children to a string of lilypond code :return: str of lilypond code ''' lilystring = "" children = self.GetChildrenIndexes() total = self.note_total counter = 0 f...
java
public <T extends CommandOutput<?, ?, ?>> void register(Class<T> commandOutputClass, CommandOutputFactory commandOutputFactory) { LettuceAssert.notNull(commandOutputClass, "CommandOutput class must not be null"); LettuceAssert.notNull(commandOutputFactory, "CommandOutputFactory must not be ...
java
public void setExecutableUsers(java.util.Collection<String> executableUsers) { if (executableUsers == null) { this.executableUsers = null; return; } this.executableUsers = new com.amazonaws.internal.SdkInternalList<String>(executableUsers); }
java
private static float calcLearningRate(float initLearningRate, int epochs, long totalProcessed, long vocabWordCount) { float rate = initLearningRate * (1 - totalProcessed / (float) (epochs * vocabWordCount + 1)); if (rate < initLearningRate * LEARNING_RATE_MIN_FACTOR) rate = initLearningRate * LEARNING_RATE_MIN_...
python
def gamma(ranks_list1,ranks_list2): ''' Goodman and Kruskal's gamma correlation coefficient :param ranks_list1: a list of ranks (integers) :param ranks_list2: a second list of ranks (integers) of equal length with corresponding entries :return: Gamma correlation coefficient (rank correlation ignorin...
python
def shutdown(self, container, instances=None, map_name=None, **kwargs): """ Shut down container instances from a container configuration. Typically this means stopping and removing containers. Note that not all policy classes necessarily implement this method. :param container: Containe...
java
public static String getDateString(Date self) { return DateFormat.getDateInstance(DateFormat.SHORT).format(self); }
python
def _set_port(self, v, load=False): """ Setter method for port, mapped from YANG variable /qos/cpu/slot/port_group/port (container) If this variable is read-only (config: false) in the source YANG file, then _set_port is considered as a private method. Backends looking to populate this variable shou...
python
def covariance(left, right, where=None, how='sample'): """ Compute covariance of two numeric array Parameters ---------- how : {'sample', 'pop'}, default 'sample' Returns ------- cov : double scalar """ expr = ops.Covariance(left, right, how, where).to_expr() return expr
python
def get_queryset(self, request): """Limit Pages to those that belong to the request's user.""" qs = super(VISADeviceAdmin, self).get_queryset(request) return qs.filter(protocol_id=PROTOCOL_ID)
java
private static Optional<ImmutableQueryModifiers> convertModifiers(MutableQueryModifiers queryModifiers) { if (queryModifiers.hasModifiers()) { ImmutableQueryModifiers immutableQueryModifiers = new ImmutableQueryModifiersImpl(queryModifiers); return Optional.of(immutableQueryModifiers); ...
java
public void serialize(StringBuilder buf) { for (CSSClass clss : store.values()) { clss.appendCSSDefinition(buf); } }
python
def start(self, name): ''' End the current behaviour and run a named behaviour. :param name: the name of the behaviour to run :type name: str ''' d = self.boatd.post({'active': name}, endpoint='/behaviours') current = d.get('active') if current is not Non...
java
public ReportDefinition withAdditionalSchemaElements(SchemaElement... additionalSchemaElements) { java.util.ArrayList<String> additionalSchemaElementsCopy = new java.util.ArrayList<String>(additionalSchemaElements.length); for (SchemaElement value : additionalSchemaElements) { additionalSche...
python
def flatten(*args): '''Generator that recursively flattens embedded lists, tuples, etc.''' for arg in args: if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)): yield from flatten(*arg) else: yield arg
python
def reset(self, data={}): """JsonQuery object cen be reset to new data according to given data or previously given raw Json data :@param data: {} :@type data: json/dict :@return self """ if data and (isinstance(data, dict) or isinstance(data, list)): ...
java
public static String abbreviate(String str, int max) { return StringUtils.isBlank(str) ? "" : StringUtils.abbreviate(str, max); }
java
private boolean tryAddModule( IAggregator aggregator, List<String> list, String bundleRoot, IResource bundleRootRes, String locale, String resource, Collection<String> availableLocales) throws IOException { if (availableLocales != null && !availableLocales.contains(locale)) { re...
python
def median(lst): """ Calcuates the median value in a @lst """ #: http://stackoverflow.com/a/24101534 sortedLst = sorted(lst) lstLen = len(lst) index = (lstLen - 1) // 2 if (lstLen % 2): return sortedLst[index] else: return (sortedLst[index] + sortedLst[index + 1])/2.0
java
private void repairBrokenLatticeBefore(ViterbiLattice lattice, int index) { ViterbiNode[][] nodeStartIndices = lattice.getStartIndexArr(); for (int startIndex = index; startIndex > 0; startIndex--) { if (nodeStartIndices[startIndex] != null) { ViterbiNode glueBase = findGlue...
python
def __parse_namespace(self): """ Parse the namespace from various sources """ if self.manifest.has_option('config', 'namespace'): return self.manifest.get('config', 'namespace') elif self.manifest.has_option('config', 'source'): return NAMESPACE_REGEX.sear...
java
public void marshall(DescribeDomainControllersRequest describeDomainControllersRequest, ProtocolMarshaller protocolMarshaller) { if (describeDomainControllersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
java
public ParseSetup readSetup(FileVec f, String[] columnNames, byte[] columnTypes) { try { Reader orcFileReader = getReader(f); StructObjectInspector insp = (StructObjectInspector) orcFileReader.getObjectInspector(); OrcParser.OrcParseSetup stp = OrcParser.deriveParseSetup(orcFileReader, insp); ...
python
def property_cache_once_per_frame(f): """ This decorator caches the return value for one game loop, then clears it if it is accessed in a different game loop Only works on properties of the bot object because it requires access to self.state.game_loop """ f.frame = -1 f.cache = None @wraps(f) d...
python
def convert_convolution(node, **kwargs): """Map MXNet's convolution operator attributes to onnx's Conv operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) kernel_dims = list(parse_helper(attrs, "kernel")) stride_dims = list(parse_helper(attrs, "stride",...
python
def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint ...
java
public SDVariable normal(String name, double mean, double stddev, SDVariable shape) { validateInteger("normal (Gaussian) random", shape); SDVariable ret = f().randomNormal(mean, stddev, shape); return updateVariableNameAndReference(ret, name); }
java
public static DoubleBinding hypot(final ObservableDoubleValue x, final ObservableDoubleValue y) { return createDoubleBinding(() -> Math.hypot(x.get(), y.get()), x, y); }
python
def communicate_path(self, path): """Communicates `path` to this peer if it qualifies. Checks if `path` should be shared/communicated with this peer according to various conditions: like bgp state, transmit side loop, local and remote AS path, community attribute, etc. """ ...
python
def get(self, sid): """ Constructs a TaskContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.task.TaskContext :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext """ return TaskContext(self._version, workspace_sid=self._solution['w...
java
protected boolean isIncludeStackTrace(ServerRequest request, MediaType produces) { ErrorProperties.IncludeStacktrace include = this.errorProperties .getIncludeStacktrace(); if (include == ErrorProperties.IncludeStacktrace.ALWAYS) { return true; } if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_...
java
public Title getSectionHeading() { if (Section_Type.featOkTst && ((Section_Type)jcasType).casFeat_sectionHeading == null) jcasType.jcas.throwFeatMissing("sectionHeading", "de.julielab.jules.types.Section"); return (Title)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((Section_Type)j...
python
def __get_nfiles_to_compress(self): """ Return the number of files to compress Note: it should take about 0.1s for counting 100k files on a dual core machine """ floyd_logger.info("Get number of files to compress... (this could take a few seconds)") paths = [self.source_...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ C = self.COEFFS[imt] imean = (self._get_magnitude_term(C, rup...
java
public DataBuffer asNd4jBuffer(DataType type, int elementSize) { int length = content.length / elementSize; DataBuffer ret = Nd4j.createBuffer(ByteBuffer.allocateDirect(content.length),type,length,0); for(int i = 0; i < length; i++) { switch(type) { case DOUBLE: ...
python
def makevFunc(self,solution): ''' Construct the value function for each current state. Parameters ---------- solution : ConsumerSolution The solution to the single period consumption-saving problem. Must have a consumption function cFunc (using cubic or l...
python
def update_group_color(self, lights: list) -> None: """Update group colors based on light states. deCONZ group updates don't contain any information about the current state of the lights in the group. This method updates the color properties of the group to the current color of the ligh...
python
def unblock_signals(self): """Let the combos listen for event changes again.""" self.aggregation_layer_combo.blockSignals(False) self.exposure_layer_combo.blockSignals(False) self.hazard_layer_combo.blockSignals(False)
java
@Path("version") @GET @Produces(MediaType.APPLICATION_JSON) public Response version() { try { InputStream is = getClass().getResourceAsStream("/application.properties"); Properties props = new Properties(); props.load(is); String version = props.get("v...
java
@FFDCIgnore({ IOException.class }) private void flushAsyncBuffers() throws IOException { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Flushing Async buffers: " + this); } if (!this.isc.getResponse().isCommitted()) { if ((obs != nul...
java
public <T> T evaluateExpressionGet(FacesContext context, String expression, Class<? extends T> expectedType) throws ELException { Application application = getMyfacesApplicationInstance(context); if (application != null) { return application.evaluateExpression...
python
def get_klout_topics(tweet, topic_type='influence'): """ Warning: Klout is deprecated and is being removed from Tweet payloads May 2018. \n See https://developer.twitter.com/en/docs/tweets/enrichments/overview/klout \n Get the user's chosen Klout topics (a list of dicts), if it exists. Regardle...
java
public static <T, C extends Collection<T>> Pair<Integer, C> page(long start, long howMany, Iterable<T> iterable, C collection) { dbc.precondition(iterable != null, "cannot call page with a null iterable"); return Pagination.page(start, howMany, iterable.iterator(), collection); }
java
public void marshall(KeyValuePair keyValuePair, ProtocolMarshaller protocolMarshaller) { if (keyValuePair == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(keyValuePair.getName(), NAME_BINDING); ...
python
def wiki(searchterm): """return the top wiki search result for the term""" searchterm = quote(searchterm) url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json" url = url.format(searchterm) result = requests.get(url).json() pages = result["query"]["search...
java
static String createStatsType(Set<String> statsItems, String sortType, MtasFunctionParserFunction functionParser) { String statsType = STATS_BASIC; for (String statsItem : statsItems) { if (STATS_FULL_TYPES.contains(statsItem)) { statsType = STATS_FULL; break; } else if (STATS_...
java
public BundledSignaturesType createBundledSignatures() { final BundledSignaturesType s = new BundledSignaturesType(); s.setProject(getProject()); bundledSignatures.add(s); return s; }
java
protected void notifyInMainThread(final T value) { for (ValueChangedListener<T> listener : listeners) { listener.onChanged(value, Value.this); } }
python
def stylize(self): """Apply theme style attributes to this instance and its children. This also causes a relayout to occur so that any changes in padding or other stylistic attributes may be handled. """ # do children first in case parent needs to override their style fo...
java
@Override int getIndexOf(final V value) { Validate.notNull(value, "Value required"); Validate.validState(getSize() > 0, "No data"); // search for value in current page final List<V> data = getData(); final int currentPageSize = data.size(); final K valueKey = getKeyOf(value); for (int localIndex = 0; lo...
java
@Override protected ILaunchConfiguration findLaunchConfiguration(IType type, ILaunchConfigurationType configType) { // Find an existing or create a launch configuration (Standard way) ILaunchConfiguration iConf = super.findLaunchConfiguration(type, configType); ILaunchConfigurationWorkingC...
java
public com.amazonaws.services.simpledb.SimpleDBResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) { ResponseMetadata metadata = client.getResponseMetadataForRequest(request); if (metadata != null) return new com.amazonaws.services.simpledb.SimpleDBResponseMetadata(me...
python
def _concat_same_dtype(self, to_concat, name): """ Concatenate to_concat which has the same class. """ attribs = self._get_attributes_dict() attribs['name'] = name # do not pass tz to set because tzlocal cannot be hashed if len({str(x.dtype) for x in to_concat}) !...
java
void debugHull() { StringBuilder buf = new StringBuilder(hull.size() * 20); for(IntIntPair p : hull) { buf.append(p.first).append(" (").append(p.second).append(") "); } LOG.debugFinest(buf); }
java
private boolean fillLast() throws IOException { int count; if (lastFilled == pageSize) { throw new IllegalStateException(); } count = src.read(pages[lastNo], lastFilled, pageSize - lastFilled); if (count <= 0) { if (count == 0) { throw new...
python
def compile_file(env, src_path, dst_path, encoding='utf-8', base_dir=''): """Compiles a Jinja2 template to python code. :param env: a Jinja2 Environment instance. :param src_path: path to the source file. :param dst_path: path to the destination file. :param encoding: template encoding. :param base_dir: th...
java
public BeanDeployer addClass(String className, AnnotatedTypeLoader loader) { addIfNotNull(loader.loadAnnotatedType(className, getManager().getId())); return this; }
java
public static ns_conf_upgrade_history[] get(nitro_service client) throws Exception { ns_conf_upgrade_history resource = new ns_conf_upgrade_history(); resource.validate("get"); return (ns_conf_upgrade_history[]) resource.get_resources(client); }
java
public HttpServerBuilder contentFrom(String contextRoot, String contentResource){ URL resource = resolver.resolve(contentResource,CallStack.getCallerClass()); resources.put(contextRoot, resource); return this; }
java
protected void addSummaryType(ProgramElementDoc member, Content tdSummaryType) { MethodDoc meth = (MethodDoc)member; addModifierAndType(meth, meth.returnType(), tdSummaryType); }
java
private void initialize() { this.setLayout(new CardLayout()); this.setName(Constant.messages.getString("conn.options.title")); this.add(getPanelProxyChain(), getPanelProxyChain().getName()); }
java
public boolean checkHeartBeat() { String dataPath = executorMeta.getLocalDir(); File localstate = new File(dataPath + "/data/" + startType + "/" + startType + ".heartbeat/"); Long modefyTime = localstate.lastModified(); if (System.currentTimeMillis() - modefyTime > JOYConstants.EXECUTO...
python
def value_for_keypath(dict, keypath): """ Returns the value of a keypath in a dictionary if the keypath exists or None if the keypath does not exist. """ if len(keypath) == 0: return dict keys = keypath.split('.') value = dict for key in keys: if key in value: ...
python
def get_serializer_info(self, serializer): """ Given an instance of a serializer, return a dictionary of metadata about its fields. """ if hasattr(serializer, 'child'): # If this is a `ListSerializer` then we want to examine the # underlying child serializ...
python
def get(self, oid): """Use PySNMP to perform an SNMP GET operation on a single object. :param oid: The OID of the object to get. :raises: SNMPFailure if an SNMP request fails. :returns: The value of the requested object. """ try: results = self.cmd_gen.getCmd...
python
def get_tier_from_participants(participantsIdentities, minimum_tier=Tier.bronze, queue=Queue.RANKED_SOLO_5x5): """ Returns the tier of the lowest tier and the participantsIDs divided by tier player in the match :param participantsIdentities: the match participants :param minimum_tier: the minimum ti...
java
public static void Forward(double[][] data) { double[][] result = new double[data.length][data[0].length]; for (int m = 0; m < data.length; m++) { for (int n = 0; n < data[0].length; n++) { double sum = 0; for (int i = 0; i < result.length; i++) { ...
python
def start(self, interval_s): """Starts executing the method at the specified interval. Args: interval_s: The amount of time between executions of the method. Returns: False if the interval was already running. """ if self.running: return False self.stopped.clear() def _e...
python
def profile_args(_args): """Return args for v1, v2, or v3 structure. Args: _args (dict): The args section from the profile. Returns: dict: A collapsed version of the args dict. """ # TODO: clean this up in a way that works for both py2/3 if ( ...
python
def main(): """ Start the DQL client. """ parse = argparse.ArgumentParser(description=main.__doc__) parse.add_argument("-c", "--command", help="Run this command and exit") region = os.environ.get("AWS_REGION", "us-west-1") parse.add_argument( "-r", "--region", default=region,...
java
public History withEvents(HistoryEvent... events) { if (this.events == null) { setEvents(new java.util.ArrayList<HistoryEvent>(events.length)); } for (HistoryEvent ele : events) { this.events.add(ele); } return this; }
java
private Object[] convert(FieldConversion[] fcs, Object[] values) { Object[] convertedValues = new Object[values.length]; for (int i= 0; i < values.length; i++) { convertedValues[i] = fcs[i].sqlToJava(values[i]); } return convertedValues; }
java
public static void cursorDoubleToContentValues(Cursor cursor, String field, ContentValues values, String key) { int colIndex = cursor.getColumnIndex(field); if (!cursor.isNull(colIndex)) { values.put(key, cursor.getDouble(colIndex)); } else { values.put(key, (...
python
def stdrepr_object(self, title, elements, *, cls=None, short=False, quote_string_keys=False, delimiter=None): """ Helper function to represent objects. Arguments: title: A title string displayed above the box containing t...
java
public boolean isBlank() { boolean rslt = true; // default if (value != null) { for (String v : value) { if (StringUtils.isNotBlank(v)) { rslt = false; break; } } } return rslt; }
python
def train_epoch(self, epoch_info: EpochInfo, interactive=True): """ Train model on an epoch of a fixed number of batch updates """ epoch_info.on_epoch_begin() if interactive: iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch") ...
python
def get_lowest_numeric_score(self): """Gets the lowest number in a numeric grading system. return: (decimal) - the lowest number raise: IllegalState - ``is_based_on_grades()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if self.is_based_...
python
def _read_mode_pocsp(self, size, kind): """Read Partial Order Connection Service Profile option. Positional arguments: * size - int, length of option * kind - int, 10 (POC-Serv Profile) Returns: * dict -- extracted Partial Order Connection Service Profile (P...
python
def nextMode(self): """ Put the search-replace macro into the next stage. The first stage is the query stage to ask the user for the string to replace, the second stage is to query the string to replace it with, and the third allows to replace or skip individual matches, ...
java
public void cleanupStoredBeanManagerOnShutdown(@Observes BeforeShutdown beforeShutdown) { if (bmpSingleton == null) { // this happens if there has been a failure at startup return; } ClassLoader classLoader = getClassLoader(null); bmpSingleton.bmInfos...
python
def list_management_certificates(kwargs=None, conn=None, call=None): ''' .. versionadded:: 2015.8.0 List management certificates associated with the subscription CLI Example: .. code-block:: bash salt-cloud -f list_management_certificates my-azure name=my_management ''' if call !...
java
@Check(CheckType.NORMAL) public void checkUnusedCapacities(SarlCapacityUses uses) { if (!isIgnored(UNUSED_AGENT_CAPACITY)) { final XtendTypeDeclaration container = uses.getDeclaringType(); final JvmDeclaredType jvmContainer = (JvmDeclaredType) this.associations.getPrimaryJvmElement(container); final Map<Str...