language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def end(self): """Finish up the context.""" TftpContext.end(self, not self.filelike_fileobj) self.metrics.end_time = time.time() log.debug("Set metrics.end_time to %s" % self.metrics.end_time) self.metrics.compute()
python
def gtom(adj, nr_steps): ''' The m-th step generalized topological overlap measure (GTOM) quantifies the extent to which a pair of nodes have similar m-th step neighbors. Mth-step neighbors are nodes that are reachable by a path of at most length m. This function computes the the M x M generali...
python
def min_row_dist_sum_idx(dists): """Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row wit...
java
public I_CmsResourceType getResourceType(String typeName) throws CmsLoaderException { I_CmsResourceType result = m_configuration.getResourceTypeByName(typeName); if (result != null) { return result; } throw new CmsLoaderException(Messages.get().container(Messages.ERR_UNKNOWN...
python
def get_grp2code2nt(self): """Return ordered dict for group to namedtuple""" grp2code2nt = cx.OrderedDict([(g, []) for g in self.grps]) for code, ntd in self.code2nt.items(): grp2code2nt[ntd.group].append((code, ntd)) for grp, nts in grp2code2nt.items(): grp2code2...
python
def ReadUsers(self, database_link, options=None): """Reads all users in a database. :params str database_link: The link to the database. :params dict options: The request options for the request. :return: Query iterable of Users. :rtype: ...
python
def xmlGenPrecursorList(precursorList): """ #TODO: docstring :params precursorList: #TODO: docstring :returns: #TODO: docstring """ numEntries = len(precursorList) xmlPrecursorList = ETREE.Element('precursorList', {'count': str(numEntries)} ...
python
def read_from_file(cls, filename): """Construct a MolecularDistortion object from a file""" with open(filename) as f: lines = list(line for line in f if line[0] != '#') r = [] t = [] for line in lines[:3]: values = list(float(word) for word in line.split()...
java
public String getDateStringOrSuppliedString(String emptyDateString) { LocalDate date = getDate(); return (date == null) ? emptyDateString : date.toString(); }
python
def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The li...
java
public float process(float testX) { if (doHunt) { hunt(testX); } else { bisectionSearch(testX, 0, size - 1); } return compute(testX); }
python
def filter_service_by_regex_host_name(regex): """Filter for service Filter on regex host_name :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for service. Accept if regex ma...
java
public void createCQLTable(String storeName, boolean bBinaryValues) { String tableName = CQLService.storeToCQLName(storeName); m_logger.info("Creating CQL table {}", tableName); StringBuffer cql = new StringBuffer(); cql.append("CREATE TABLE "); cql.append(qualifiedTable...
python
def linkify(self, modules): """Link modules and Satellite links :param modules: Module object list :type modules: alignak.objects.module.Modules :return: None """ logger.debug("Linkify %s with %s", self, modules) self.linkify_s_by_module(modules)
python
def get_account_details(self, account): """ Get the account details """ result = self.get_user(account.username) if result is None: result = {} return result
python
def disable(self): """ Disable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Clien...
python
def _create_map(self): """Initialize Brzozowski Algebraic Method""" # at state i is represented by the regex self.B[i] for state_a in self.mma.states: self.A[state_a.stateid] = {} # Create a map state to state, with the transition symbols for arc in state_a.a...
java
@BetaApi public final Operation addInstanceTargetPool( ProjectRegionTargetPoolName targetPool, TargetPoolsAddInstanceRequest targetPoolsAddInstanceRequestResource) { AddInstanceTargetPoolHttpRequest request = AddInstanceTargetPoolHttpRequest.newBuilder() .setTargetPool(targetPool ...
python
def install_toolset(self, toolset): ''' Installs specific toolset on CI system. ''' info = toolset_info[toolset] if sys.platform.startswith('linux'): os.chdir(self.work_dir) if 'ppa' in info: for ppa in info['ppa']: util...
python
def mkdir(self, name=None, parents=False, mode=0o777): """Creates that directory, or a directory under this one. ``path.mkdir(name)`` is a shortcut for ``(path/name).mkdir()``. :param name: Path component to append to this path before creating the directory. :param parents...
python
def to_comm(self, light_request=False): ''' Convert `self` to :class:`.Archive`. Returns: obj: :class:`.Archive` instance. ''' data = None if not light_request: tmp_fn = path_to_zip(self.dir_pointer) data = read_as_base64(tmp_fn) ...
java
@Nullable @ReturnsMutableCopy public static float [] getCopy (@Nullable final float [] aArray, @Nonnegative final int nStartIndex, @Nonnegative final int nLength) { if (aArray == null) return null; final float [] ret = new float [nL...
python
def set_position_fast(self, val): """Set the devive OPEN LEVEL.""" if val == 0: self.close_fast() else: setlevel = 255 if val < 1: setlevel = val * 100 elif val <= 0xff: setlevel = val set_command = Stand...
java
public static boolean isRange(String value) { if (value == null) { return false; } try { Set<Integer> values = parseRange(value); return values.size() > 0; } catch (Exception e) { return false; } }
java
public void unblockRooms(DomainBareJid mucLightService, List<Jid> roomsJids) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { HashMap<Jid, Boolean> rooms = new HashMap<>(); for (Jid jid : roomsJids) { rooms.put(jid, true); } ...
python
def check_removable(dev, opts): ''' Removable drives can be identified under /sys. ''' try: # get parent device from sys filesystem, look from right. :-/ parent = os.readlink(f'/sys/class/block/{dev}').rsplit("/", 2)[1] with open(f'/sys/block/{parent}/removable') as f: return f.rea...
java
public static String getVersion(String variant) { Object data = getCalendarSystem(variant); if (data instanceof AstronomicalHijriData) { return AstronomicalHijriData.class.cast(data).getVersion(); } return ""; }
java
public CommitInfo getCommitInfo(String path) throws Exception { Iterator<RevCommit> revCommits = git.log().addPath(path).setMaxCount(1).call().iterator(); if (revCommits.hasNext()) { RevCommit revCommit = revCommits.next(); CommitInfo commitInfo = new CommitInfo(revCommit.getId()...
java
public GetSubscriptionDefinitionResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
python
def to_dict(self): """ Return entity data as a dictionary """ return {field_name: getattr(self, field_name, None) for field_name in self.meta_.declared_fields}
java
public Primitive castToType( Class<?> toType, int operation ) throws UtilEvalError { return castPrimitive( toType, getType()/*fromType*/, this/*fromValue*/, false/*checkOnly*/, operation ); }
java
@Override public String convert(SIFInteraction inter) { String s = inter.toString(); for (OutputColumn column : columns) { s += "\t" + column.getColumnValue(inter); } return s; }
python
def groupby_with_null(data, *args, **kwargs): """ Groupby on columns with NaN/None/Null values Pandas currently does have proper support for groupby on columns with null values. The nulls are discarded and so not grouped on. """ by = kwargs.get('by', args[0]) altered_columns = {} i...
java
private static ImmutableList<String> getClassNames(String qualifiedName) { ImmutableList.Builder<String> classNames = ImmutableList.builder(); List<String> parts = DOT_SPLITTER.splitToList(qualifiedName); for (int i = 0; i < parts.size(); i++) { String part = parts.get(i); if (isClassOrConstantN...
python
def _get_forums_for_user(self, user, perm_codenames, use_tree_hierarchy=False): """ Returns all the forums that satisfy the given list of permission codenames. User and group forum permissions are used. If the ``use_tree_hierarchy`` keyword argument is set the granted forums will be filtered s...
java
public static void copyFile(File src, File dest, StreamMonitor monitor) throws IOException, FileNotFoundException { FileInputStream fis = null; FileOutputStream fos = null; int length = (int) src.length(); try { fis = new FileInputStream(src); fos = new FileOutput...
python
def changes(self): """ Return a tuple with the removed and added facts since last run. """ try: return self.added, self.removed finally: self.added = list() self.removed = list()
java
BeanHelper createHelper(final JClassType pjtype, final TreeLogger plogger, final GeneratorContext pcontext) throws UnableToCompleteException { final JClassType erasedType = pjtype.getErasedType(); try { final Class<?> clazz = Class.forName(erasedType.getQualifiedBinaryName()); return doCreateH...
python
def highlight(self, *fields, **kwargs): """ Request highlighting of some fields. All keyword arguments passed in will be used as parameters for all the fields in the ``fields`` parameter. Example:: Search().highlight('title', 'body', fragment_size=50) will produce the equiv...
java
@Reference(cardinality=ReferenceCardinality.MULTIPLE, policy=ReferencePolicy.DYNAMIC) public void addFactory(TaskSystemFactory factory) { logger.finer("Adding factory: " + factory); filters.add(factory); }
java
@Override public String resolveLocaleCode(final HttpServletRequest request) { String localCode = null; if (request.getLocale() != Locale.getDefault()) { localCode = request.getLocale().toString(); } return localCode; }
java
private void addPostParams(final Request request) { if (phoneNumber != null) { request.addPostParam("PhoneNumber", phoneNumber.toString()); } if (apiVersion != null) { request.addPostParam("ApiVersion", apiVersion); } if (friendlyName != null) { ...
java
@Override public void valiate4Update(final Attribute _attribute, final Instance _instance, final Object[] _value) throws EFapsException { super.valiate4Update(_attribute, _instance, _value); validate(_attribute, _instance, _va...
java
public static <T> boolean xMatch(final Stream<T> stream, final int num, final Predicate<? super T> c) { return stream.filter(t -> c.test(t)) .collect(java.util.stream.Collectors.counting()) == num; }
java
public static int compare(Version v1, Version v2) { // throw NPE to comply with Comparable specification if (v1 == null) { throw new NullPointerException("v1 is null"); } else if (v2 == null) { throw new NullPointerException("v2 is null"); } return compare...
python
def rm_raw(ctx, dataset, kwargs): "removes the raw unprocessed data" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm_raw(**kwargs)
java
@Override public Object[] scanRowKeys(final Table hTable, final Filter filter, final String columnFamilyName, final String columnName, final Class rowKeyClazz) throws IOException { List<Object> rowKeys = new ArrayList<Object>(); if (scanner == null) { Sca...
java
public final void openHeaderRow(TrTag.State state, AbstractRenderAppender appender) { if(state == null) state = TR_STATE; appender.append(LINE_BREAK); _trRenderer.doStartTag(appender, state); }
java
private void addExecutionGoals(MavenPluginExecutionDescriptor executionDescriptor, PluginExecution pluginExecution, Store store) { List<String> goals = pluginExecution.getGoals(); for (String goal : goals) { MavenExecutionGoalDescriptor goalDescriptor = store.create(MavenExecutionGoalDescrip...
java
static void maybeAddTempsForCallArguments( AbstractCompiler compiler, Node fnNode, ImmutableMap<String, Node> argMap, Set<String> namesNeedingTemps, CodingConvention convention) { if (argMap.isEmpty()) { // No arguments to check, we are done. return; } checkArgumen...
java
public boolean appendUnitSeparator(TimeUnit unit, boolean longSep, boolean afterFirst, boolean beforeLast, StringBuffer sb) { // long seps // false, false "...b', '...d" // false, true "...', and 'c" // true, false - "a', '...c...
python
def add_values(self, values): '''add some data to the graph''' if self.child.is_alive(): self.parent_pipe.send(values)
java
void decreaseKBy1() { if (k_ <= 1) { throw new SketchesStateException("Cannot decrease k below 1 in union"); } if ((h_ == 0) && (r_ == 0)) { // exact mode, but no data yet; this reduction is somewhat gratuitous --k_; } else if ((h_ > 0) && (r_ == 0)) { // exact mode, but we have...
python
def _execute(self, native, command, data=None, returning=True, mapper=dict): """ Executes the inputted command into the current \ connection cursor. :param command | <str> da...
java
public static Object parseWithException(Reader in) throws IOException, ParseException { JSONParser parser=new JSONParser(); return parser.parse(in); }
python
def find(self, name, resolved=True): """ Get the definition object for the schema object by name. @param name: The name of a schema object. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolve...
python
def tryDynLocal(name): ''' Dynamically import a module and return a module local or raise an exception. ''' if name.find('.') == -1: raise s_exc.NoSuchDyn(name=name) modname, objname = name.rsplit('.', 1) mod = tryDynMod(modname) item = getattr(mod, objname, s_common.novalu) if ...
java
public static int getTwoTermFreq(Term fromTerm, Term toTerm) { Nature from = fromTerm.natrue(); Nature to = toTerm.natrue(); if (from.index < 0 || to.index < 0) { return 0; } return NATURETABLE[from.index][to.index]; }
java
public void completeRestore(String locationName, UUID operationId, String lastBackupName) { completeRestoreWithServiceResponseAsync(locationName, operationId, lastBackupName).toBlocking().last().body(); }
java
public static <T extends Annotation> AnnotationValueBuilder<T> builder(Class<T> annotation) { return new AnnotationValueBuilder<>(annotation); }
python
def tagref(self, index): """Get the tag and reference number of a vgroup member, given the index number of that member. Args:: index member index (0 based) Returns:: 2-element tuple: - member tag - member reference number C libra...
java
public Observable<EventSubscriptionInner> createOrUpdateAsync(String scope, String eventSubscriptionName, EventSubscriptionInner eventSubscriptionInfo) { return createOrUpdateWithServiceResponseAsync(scope, eventSubscriptionName, eventSubscriptionInfo).map(new Func1<ServiceResponse<EventSubscriptionInner>, Even...
python
def __reset_weights(self, target_phis, res_idxs, obs_idxs): """private method to reset weights based on target phi values for each group. This method should not be called directly Parameters ---------- target_phis : dict target phi contribution for groups to reweigh...
java
@Override public DescribeGlobalTableSettingsResult describeGlobalTableSettings(DescribeGlobalTableSettingsRequest request) { request = beforeClientExecution(request); return executeDescribeGlobalTableSettings(request); }
java
public void marshall(SigningPlatform signingPlatform, ProtocolMarshaller protocolMarshaller) { if (signingPlatform == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(signingPlatform.getPlatformId(), P...
java
public static String getFormattedThreadList( final String prefix, final String threadPrefix, final String stackElementPrefix) { // Sort by thread name final TreeMap<String, StackTraceElement[]> threadNames = new TreeMap<>(); for (final Map.Entry<Thread, StackTraceElement[]> entry : Thread.getAllStack...
java
@Override public RelationIndexStatusReport call() throws InterruptedException { Preconditions.checkNotNull(g, "Graph instance must not be null"); Preconditions.checkNotNull(relationIndexName, "Index name must not be null"); Preconditions.checkNotNull(status, "Target status must not be null")...
java
public final hqlParser.negatedExpression_return negatedExpression() throws RecognitionException { hqlParser.negatedExpression_return retval = new hqlParser.negatedExpression_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token NOT161=null; ParserRuleReturnScope x =null; ParserRuleReturnSc...
python
def toXml(self, xparent=None): """ Converts this object to XML. :param xparent | <xml.etree.ElementTree.Element> || None :return <xml.etree.ElementTree.Element> """ if xparent is None: xml = ElementTree.Element('object') else: xm...
python
def _set_symbols(self, file_name, configure): """ Load the symbols with configuration. :param file_name: The file path of symbol configuration. :type file_name: str :param configure: The configuration of HaTeMiLe. :type configure: hatemile.util.configure.Configure ...
python
def _render_name(self): """Render data name. The rendering is based on name template (`process.data_name`) and input context. """ if not self.process.data_name or self.named_by_user: # pylint: disable=no-member return inputs = copy.deepcopy(self.input) ...
java
@Pure @SuppressWarnings("checkstyle:magicnumber") public double getRotation() { final double[] tmpScale = new double[3]; final double[] tmpRot = new double[9]; getScaleRotate2x2(tmpScale, tmpRot); if (Math.signum(tmpRot[0]) != Math.signum(tmpRot[4])) { // Sinuses are on the top-left to bottom-right diagona...
python
def get_download_link(cookie, tokens, path): '''在下载之前, 要先获取最终的下载链接. path - 一个文件的绝对路径. @return red_url, red_url 是重定向后的URL, 如果获取失败, 就返回原来的dlink; ''' metas = get_metas(cookie, tokens, path) if (not metas or metas.get('errno', -1) != 0 or 'info' not in metas or len(metas['i...
python
def plot_pair(df, feature_name_1, feature_name_2, kind='scatter', alpha=0.01, **kwargs): """ Plot a scatterplot of two features against one another, and calculate Pearson correlation coefficient. Examples: `plot_pair(X, 'emb_mean_euclidean', 'emb_mean_cosine')` Args: df: fe...
java
private static boolean isDelimiter(final char ch, final char[] delimiters) { if (delimiters == null) { return CharUtils.isWhitespace(ch); } for (final char delimiter : delimiters) { if (ch == delimiter) { return true; } } return...
python
def _netstat_sunos(): ''' Return netstat information for SunOS flavors ''' log.warning('User and program not (yet) supported on SunOS') ret = [] for addr_family in ('inet', 'inet6'): # Lookup TCP connections cmd = 'netstat -f {0} -P tcp -an | tail +5'.format(addr_family) ...
java
private void mergeCategories(Installation entity, Set<Category> categoriesToMerge) { if (entity.getCategories() != null) { final List<String> categoryNames = convertToNames(categoriesToMerge); final List<Category> existingCategoriesFromDB = categoryDao.findByNames(categoryNames); ...
python
def map_files(self, base_dir, all_components_list): """Apply `assert_single_path_by_glob()` to all elements of `all_components_list`. Each element of `all_components_list` should be a tuple of path components, including wildcards. The elements of each tuple are joined, and interpreted as a glob expression ...
java
private Either<FEELEvent, Object> actualInputsMatchInputValues(EvaluationContext ctx, Object[] params) { // check that all the parameters match the input list values if they are defined for( int i = 0; i < params.length; i++ ) { final DTInputClause input = inputs.get( i ); // if ...
python
def schedule(self): """Gets the schedule for the given zone""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), headers=self.client._headers() # pylint: d...
java
public double falseNegativeRate(Integer classLabel, double edgeCase) { double fnCount = falseNegatives(classLabel); double tpCount = truePositives(classLabel); return EvaluationUtils.falseNegativeRate((long) fnCount, (long) tpCount, edgeCase); }
python
def run_simulation( t, y0=None, volume=1.0, model=None, solver='ode', is_netfree=False, species_list=None, without_reset=False, return_type='matplotlib', opt_args=(), opt_kwargs=None, structures=None, observers=(), progressbar=0, rndseed=None, factory=None, ## deprecated ...
python
def publishFeatureCollections(self, configs): """Publishes feature collections to a feature service. Args: configs (list): A list of JSON configuration feature service details to publish. Returns: dict: A dictionary of results objects. """ if sel...
java
public static <T> Level0ArrayOperator<Calendar[],Calendar> onArrayFor(final Calendar... elements) { return onArrayOf(Types.CALENDAR, VarArgsUtil.asRequiredObjectArray(elements)); }
python
def _many_to_many(self): """Perform many-to-many files conversion. :return: None :rtype: :py:obj:`None` """ if not self.file_generator.to_path_compression: self._to_dir(self.file_generator) elif self.file_generator.to_path_compression == "zip": sel...
java
Stream<SegmentWithState> getSegmentWithStates(Collection<String> sequenceNames) { synchronized (segments) { return sequenceNames .stream() .map(segments::get) .filter(Objects::nonNull) .flatMap(segmentsForSequence -> segmentsForSequence.intervalToSegmentStates.values(...
java
public void setProxy(Proxy proxy) { if(proxy != null) { java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort())); client.setProxy(p); } else client.setProxy(java.ne...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.MPORG__RG_LENGTH: return RG_LENGTH_EDEFAULT == null ? rgLength != null : !RG_LENGTH_EDEFAULT.equals(rgLength); case AfplibPackage.MPORG__TRIPLETS: return triplets != null && !triplets.isEmpty(); } return super....
java
@Override public ReadModifyWriteRowResponse readModifyWriteRow(ReadModifyWriteRowRequest request) { if (shouldOverrideAppProfile(request.getAppProfileId())) { request = request.toBuilder().setAppProfileId(clientDefaultAppProfileId).build(); } return createUnaryListener(request, readWriteModifyRpc, ...
java
private JScrollPane getDefaultPane() { if (defaultPane == null) { defaultPane = new JScrollPane(); defaultPane.setViewportView(getDefaultOutput()); defaultPane.setName("defaultPane"); defaultPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); } return defaultP...
java
public Observable<SharedAccessAuthorizationRuleListResultInner> listKeysAsync(String resourceGroupName, String namespaceName, String authorizationRuleName) { return listKeysWithServiceResponseAsync(resourceGroupName, namespaceName, authorizationRuleName).map(new Func1<ServiceResponse<SharedAccessAuthorizationRu...
python
def predicate_with_side_args(side_arguments: List[str]) -> Callable: # pylint: disable=invalid-name """ Like :func:`predicate`, but used when some of the arguments to the function are meant to be provided by the decoder or other state, instead of from the language. For example, you might want to have ...
java
public void encodeData(AsnOutputStream asnOs) throws MAPException { if (this.sendSubscriberData != null) { asnOs.writeNullData(); } else { asnOs.writeOctetStringData(this.subscriberDataStored); } }
python
def append(self, element): ''' Append a PileupElement to this Pileup. If an identical PileupElement is already part of this Pileup, do nothing. ''' assert element.locus == self.locus, ( "Element locus (%s) != Pileup locus (%s)" % (element.locus, self.locus...
python
def query_variable(ncfile, name) -> netcdf4.Variable: """Return the variable with the given name from the given NetCDF file. Essentially, |query_variable| just performs a key assess via the used NetCDF library, but adds information to possible error messages: >>> from hydpy.core.netcdftools import que...
java
public Object invoke(MethodInvocation mi) throws Exception { Method method = mi.getMethod(); return simulatorAdapter.service(method.getDeclaringClass().getCanonicalName(), method.getName(), mi.getArguments(), rootPath, useRootRelativePath); }
java
public static LocaleFacet createFor(final String localeString, final Log log) throws MojoExecutionException { // Check sanity Validate.notNull(log, "log"); Validate.notEmpty(localeString, "localeString"); final StringTokenizer tok = new StringTokenizer(localeString, ",", false); ...
python
def revoke_authorization(self): """Revokes Oauth authorization.""" self.request_handler.post( endpoint='oauth/token/revoke', omit_api_version=True, data={ 'client_id': self.auth.client_id, 'client_secret': self.auth.client_secret, ...
python
def transform(self, context, handler, result): """Transform the value returned by the controller endpoint. This extension transforms returned values if the endpoint has a return type annotation. """ handler = handler.__func__ if hasattr(handler, '__func__') else handler annotation = getattr(handler, '__ann...
java
@Override public Resource getResource(String path) { int index = path.indexOf("://"); if (index != -1) { String scheme = path.substring(0, index).toLowerCase().trim(); String subPath = path.substring(index + 3); for (int i = 0; i < resources.length; i++) { if (scheme.equalsIgnoreCase(resources[i]...