language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def implied_timescales(sequences, lag_times, n_timescales=10, msm=None, n_jobs=1, verbose=0): """ Calculate the implied timescales for a given MSM. Parameters ---------- sequences : list of array-like List of sequences, or a single sequence. Each sequence sho...
java
@Override public Long append(final String key, final String value) { return this.d_append(key, value).getResult(); }
java
public static ByteBuffer asByteBuffer(String expression, Node node) throws XPathExpressionException { return asByteBuffer(expression, node, xpath()); }
java
@Override public void generatedFile(final String fileName, final int current, final int total) { if (log.isDebugEnabled()) { log.debug("Processing file [" + current + "/" + total + "]: " + fileName); } }
java
@NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull Point point) { coords.add(point); return coords; }
java
@Override public File findMostRecentSnapshot() throws IOException { List<File> files = findNValidSnapshots(1); if (files.size() == 0) { return null; } return files.get(0); }
java
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public static String optString(@Nullable Bundle bundle, @Nullable String key, @Nullable String fallback) { if (bundle == null) { return fallback; } return bundle.getString(key, fallback); }
java
public static void generateCylinder(TFloatList positions, TFloatList normals, TIntList indices, float radius, float height) { // 0,0,0 will be halfway up the cylinder in the middle final float halfHeight = height / 2; // The positions at the rims of the cylinders final List<Vector3f> rim...
python
def get_current_shutit_pexpect_session(self, note=None): """Returns the currently-set default pexpect child. @return: default shutit pexpect child object """ self.handle_note(note) res = self.current_shutit_pexpect_session self.handle_note_after(note) return res
java
public Interval withStart(ReadableInstant start) { long startMillis = DateTimeUtils.getInstantMillis(start); return withStartMillis(startMillis); }
java
public void onDrawFrame(float frameTime) { GVRSceneObject owner = getOwnerObject(); if (owner == null) { return; } if (mSwitchIndex < 0 || mSwitchIndex > owner.rawGetChildren().size()) { return; } int i = 0; List<GVRScen...
python
def _initialize(self, **resource_attributes): """ Initialize the collection. :param resource_attributes: API resource parameters """ super(APIResourceCollection, self)._initialize(**resource_attributes) dict_list = self.data self.data = [] for resource i...
python
def _find_from_file(full_doc, from_file_keyword): """ Finds a line in <full_doc> like <from_file_keyword> <colon> <path> and return path """ path = None for line in full_doc.splitlines(): if from_file_keyword in line: parts = line.strip().split(':') if ...
java
protected final Stringifier<Long> registerLongStringifier(String name, Stringifier<Long> longStringifier) { compositeStringifier.add(Long.class, name, longStringifier); compositeStringifier.add(Long.TYPE, name, longStringifier); return longStringifier; }
python
def backend_fields(self, fields): '''Return a two elements tuple containing a list of fields names and a list of field attribute names.''' dfields = self.dfields processed = set() names = [] atts = [] pkname = self.pkname() for name in fields: ...
python
def graph(self): """ Returns MultiDiGraph from kihs. Nodes are helices and edges are kihs. """ g = networkx.MultiDiGraph() edge_list = [(x.knob_helix, x.hole_helix, x.id, {'kih': x}) for x in self.get_monomers()] g.add_edges_from(edge_list) return g
python
def to_syllables_with_trailing_spaces(line: str, syllables: List[str]) -> List[str]: """ Given a line of syllables and spaces, and a list of syllables, produce a list of the syllables with trailing spaces attached as approriate. :param line: :param syllables: :return: >>> to_syllables_with...
python
def from_dict(cls, d): """ Reconstructs the StructureEnvironments object from a dict representation of the StructureEnvironments created using the as_dict method. :param d: dict representation of the StructureEnvironments object :return: StructureEnvironments object """ ...
java
public void displayDialog() throws Exception { Map<String, String[]> params = initAdminTool(); // explorer view dialogs if (CmsExplorerDialog.EXPLORER_TOOLS.contains(getCurrentToolPath())) { if (getAction() == CmsDialog.ACTION_CANCEL) { actionCloseDialog(); ...
java
public static Observable<? extends AVUser> logIn(String username, String password) { return logIn(username, password, internalUserClazz()); }
python
def get_table_name(self, ind): """ Return both the table_name (i.e., 'specimens') and the col_name (i.e., 'specimen') for a given index in self.ancestry. """ if ind >= len(self.ancestry): return "", "" if ind > -1: table_name = self.ancestr...
python
def cal_continue(self, list_data): """ 計算持續天數 :rtype: int :returns: 向量數值:正數向上、負數向下。 """ diff_data = [] for i in range(1, len(list_data)): if list_data[-i] > list_data[-i - 1]: diff_data.append(1) else: diff_...
python
def flatten(data): """Returns a flattened version of a list. Courtesy of https://stackoverflow.com/a/12472564 Args: data (`tuple` or `list`): Input data Returns: `list` """ if not data: return data if type(data[0]) in (list, tuple): return list(flatten(dat...
python
def _get_group_from_state(self, sid): """ Args: sid (int): The state identifier Return: int: The group identifier that the state belongs """ for index, selectgroup in enumerate(self.groups): if sid in selectgroup: return index
java
public void init(String st, int minsize, int maxsize) { super.init(buildString(st.trim(), minsize), minsize, maxsize); }
java
public VariantMetadata loadPedigree(Pedigree pedigree, String studyId) { VariantStudyMetadata variantStudyMetadata = getVariantStudyMetadata(studyId); if (variantStudyMetadata != null) { boolean found; org.opencb.biodata.models.metadata.Individual dest = null; for (Me...
python
def descendants(self, node): """ Returns a :class:`QuerySet` with all descendants for a given :class:`CTENode` `node`. :param node: the :class:`CTENode` whose descendants are required. :returns: A :class:`QuerySet` with all descendants of the given `node`. ...
java
protected void createLibraryHandlingGroup(Composite parent) { fLibraryHandlingGroup= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); fLibraryHandlingGroup.setLayout(layout); fLibraryHandlingGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | Gri...
python
def conditional_jit(function=None, **kwargs): # noqa: D202 """Use numba's jit decorator if numba is installed. Notes ----- If called without arguments then return wrapped function. @conditional_jit def my_func(): return else called with arguments @co...
python
def postActivate_(self): """Whatever you need to do after creating the shmem client """ if (self.requiredGPU_MB(self.required_mb)): self.analyzer = YoloV3TinyAnalyzer(verbose = self.verbose) else: self.warning_message = "WARNING: not enough GPU memory!" ...
python
def _to_dict(objects): ''' Potentially interprets a string as JSON for usage with mongo ''' try: if isinstance(objects, six.string_types): objects = salt.utils.json.loads(objects) except ValueError as err: log.error("Could not parse objects: %s", err) raise err ...
python
def private_config_file(self): """ Returns the private-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return path els...
java
public Observable<ManagementPolicyInner> createOrUpdateAsync(String resourceGroupName, String accountName, ManagementPolicySchema policy) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, policy).map(new Func1<ServiceResponse<ManagementPolicyInner>, ManagementPolicyInner>() { ...
python
def explained_variance(returns, values): """ Calculate how much variance in returns do the values explain """ exp_var = 1 - torch.var(returns - values) / torch.var(returns) return exp_var.item()
python
def query(self,sql): """ Execute an SQL query on the server and fetch the resulting XML file back. @return: message received (may be empty) from LDBD Server as a string """ msg = "QUERY\0" + sql + "\0" self.sfile.write(msg) ret, output = self.__response__() reply = str(output[0]) ...
python
def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" try: user_data = super().user_data(access_token, *args, **kwargs) if not user_data.get('email'): raise AuthFailed(self, _('You must have a public email configured in GitHub. ' ...
java
public String buildJson() throws ODataRenderException { LOG.debug("Start building Json service root document"); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8); jsonGenerator....
java
public GetDatabaseOperation buildGetDatabaseOperation(String databasePath, String key, String name) { return new GetDatabaseOperation(getOperationFactory(), databasePath, key, name); }
java
protected static String makeComponentPrefix(String tokenName, String className) { String simpleClassName = className; if (null != className) { int lastDotIdx = className.lastIndexOf("."); if (lastDotIdx > -1) { simpleClassName = className.substring(lastDotIdx...
python
def compute_correlation(matrix1, matrix2, return_nans=False): """compute correlation between two sets of variables Correlate the rows of matrix1 with the rows of matrix2. If matrix1 == matrix2, it is auto-correlation computation resulting in a symmetric correlation matrix. The number of columns MUS...
java
public void configConstant(Constants me) { //load properties this.loadPropertyFile(); me.setViewType(ViewType.JSP); me.setDevMode(this.getAppDevMode()); me.setEncoding(Const.DEFAULT_ENCODING); me.setError404View(PageViewKit.get404PageView()); me.setError500View(PageViewKit.get500PageView()); me.setError...
java
public void addExcludedlaceId(final String placeId) { if (null == this.countryCodes) { this.excludePlaceIds = new ArrayList<String>(); } this.excludePlaceIds.add(placeId); }
java
@Override public Document parseXML(String string) { try { return loadXML(new ByteArrayInputStream(string.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new BugError("JVM with missing support for UTF-8."); } }
python
def parse_numeric(self): """Tokenize a Fortran numerical value.""" word = '' frac = False if self.char == '-': word += self.char self.update_chars() while self.char.isdigit() or (self.char == '.' and not frac): # Only allow one decimal point ...
java
@Override public UpdateGatewayGroupResult updateGatewayGroup(UpdateGatewayGroupRequest request) { request = beforeClientExecution(request); return executeUpdateGatewayGroup(request); }
java
private String getUserDn(String callerName, String filter, SearchControls controls) { String userDn = null; String searchBase = idStoreDefinition.getCallerSearchBase(); if (searchBase == null || searchBase.isEmpty()) { userDn = idStoreDefinition.getCallerNameAttribute() + "=" + calle...
java
public static TimerJobEntity createTimerEntityForTimerEventDefinition(TimerEventDefinition timerEventDefinition, boolean isInterruptingTimer, ExecutionEntity executionEntity, String jobHandlerType, String jobHandlerConfig) { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngin...
java
public String getTypeGeneric(boolean includeBrackets) { if (isTypeGeneric() == false) { return ""; } String result = typeGenericName[0] + typeGenericExtends[0]; if (typeGenericExtends.length > 1) { result += ", " + typeGenericName[1] + typeGenericExtends[1]; ...
java
public void registerType(ModelElementType modelElementType, Class<? extends ModelElementInstance> instanceType) { QName qName = ModelUtil.getQName(modelElementType.getTypeNamespace(), modelElementType.getTypeName()); typesByName.put(qName, modelElementType); typesByClass.put(instanceType, modelElementType);...
python
def unflatten(flat_dict, separator='_'): """ Creates a hierarchical dictionary from a flattened dictionary Assumes no lists are present :param flat_dict: a dictionary with no hierarchy :param separator: a string that separates keys :return: a dictionary with hierarchy """ _unflatten_asse...
java
public GetSecurityPolicyResponse getSecurityPolicy(GetSecurityPolicyRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string."); InternalRequest internalRe...
java
static void setTheme(Context context, AttributeSet attrs) { boolean nightModeEnabled = isNightModeEnabled(context); if (shouldSetThemeFromPreferences(context)) { int prefLightTheme = retrieveThemeResIdFromPreferences(context, NavigationConstants.NAVIGATION_VIEW_LIGHT_THEME); int prefDarkTheme = ret...
java
private void handleResidueAnnotation(String seqName, String featureName, String value) { if (featureName.equals(GR_SURFACE_ACCESSIBILITY)) { stockholmStructure.addSurfaceAccessibility(seqName, value); } else if (featureName.equals(GR_TRANS_MEMBRANE)) { stockholmStructure.addTransMembrane(seqName, value); }...
python
def read(self, filename): ''' Read a file content. :param string filename: The storage root-relative filename :raises FileNotFound: If the file does not exists ''' if not self.backend.exists(filename): raise FileNotFound(filename) return self.backend....
python
def _table_arg_to_table_ref(value, default_project=None): """Helper to convert a string or Table to TableReference. This function keeps TableReference and other kinds of objects unchanged. """ if isinstance(value, six.string_types): value = TableReference.from_string(value, default_project=defa...
python
def hash(self): """(property) Returns a unique hash value for the result.""" data_str = ';'.join( [str(repr(var)) for var in [self.N, self.K, self.X, self.L, self.stat, self.cutoff, self.pval, self.pval_thresh, self.escore_pval_thresh]]) data_...
python
def post(self, ddata, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT): """Method to update some attributes on namespace.""" headers = HEADERS.copy() if referer is None: headers.pop('Referer') else: headers['Referer'] = referer # append csrftoken if 'c...
java
@GuardedBy("evictionLock") void drainWriteBuffer() { for (int i = 0; i < WRITE_BUFFER_DRAIN_THRESHOLD; i++) { final Runnable task = writeBuffer.poll(); if (task == null) { break; } task.run(); } }
java
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-") public List<ExceptionClassFilter.Include> getIncludeList() { if (includeList == null) { includeList = new ArrayList<ExceptionClassFilter.Include>(...
java
public static void putScript(String name, KotlinCompiledScript script) { getInstance().scripts.put(name, script); }
python
def ra(self,*args,**kwargs): """ NAME: ra PURPOSE: return the right ascension INPUT: t - (optional) time at which to get ra obs=[X,Y,Z] - (optional) position of observer (in kpc) (default=Object-wide default) ...
java
public void skipHttpHeader() throws IOException { if (this.httpHeaderStream != null) { // Empty the httpHeaderStream for (int available = this.httpHeaderStream.available(); this.httpHeaderStream != null && (available = this.httpHead...
java
@Override public void removeByCommercePriceListId(long commercePriceListId) { for (CommercePriceListUserSegmentEntryRel commercePriceListUserSegmentEntryRel : findByCommercePriceListId( commercePriceListId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commercePriceListUserSegmentEntryRel); } }
python
def sort_versions(self): """Sort entries by version. The order is typically descending, but package order functions can change this. """ if self.sorted: return for orderer in (self.solver.package_orderers or []): entries = orderer.reorder(self.en...
java
public EClass getRMI() { if (rmiEClass == null) { rmiEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(332); } return rmiEClass; }
java
public static String getURL(URI uri) { final StringBuilder buffer = new StringBuilder(); buffer.append(uri.getPath()); String query = uri.getQuery(); String fragment = uri.getFragment(); if (StringUtils.isNotBlank(query)) { buffer.append('?').append(query); ...
java
public int getNbWritten() throws DevFailed { manageExceptions("getNbWritten"); return attrval.w_dim.dim_x * DIM_MINI(attrval.w_dim.dim_y); }
python
def otsu(fpath): """ Returns value of otsu threshold for an image """ img = imread(fpath, as_grey=True) thresh = skimage.filter.threshold_otsu(img) return thresh
java
@Override public void endElement(String uri, String l, String q) { /* * 1. If current element is a String, update its value from the string buffer. * 2. Add the element to parent. */ XDB.Element element = Enum.valueOf(XDB.Element.class, l.toUpperCase()); s...
java
public QueueReference build(Map<String, String> params) throws IOException { return build(params, null,false); }
java
public Observable<ExpressRouteGatewayInner> createOrUpdateAsync(String resourceGroupName, String expressRouteGatewayName, ExpressRouteGatewayInner putExpressRouteGatewayParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, expressRouteGatewayName, putExpressRouteGatewayParameters).map(n...
python
def time_stops(self): """ Valid time steps for this service as a list of datetime objects. """ if not self.supports_time: return [] if self.service.calendar == 'standard': units = self.service.time_interval_units interval = self.service.time_interval ...
java
public Observable<Void> deleteAsync(String locationName, String longTermRetentionServerName, String longTermRetentionDatabaseName, String backupName) { return deleteWithServiceResponseAsync(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName).map(new Func1<ServiceResponse<Void>,...
python
def _set_group_best(self, v, load=False): """ Setter method for group_best, mapped from YANG variable /routing_system/route_map/content/match/additional_paths/advertise_set/group_best (empty) If this variable is read-only (config: false) in the source YANG file, then _set_group_best is considered as a p...
java
public void setupKeys() { KeyAreaInfo keyArea = null; keyArea = new KeyAreaInfo(this, Constants.UNIQUE, ID_KEY); keyArea.addKeyField(ID, Constants.ASCENDING); keyArea = new KeyAreaInfo(this, Constants.UNIQUE, KEY_FILENAME_KEY); keyArea.addKeyField(KEY_FILENAME, Constants.ASCE...
python
def change_time(filename, newtime): """Change the time of a process or group of processes by writing a new time to the time file.""" with open(filename, "w") as faketimetxt_handle: faketimetxt_handle.write("@" + newtime.strftime("%Y-%m-%d %H:%M:%S"))
python
def tail(self, rows: int=5): """ Returns the main dataframe's tail :param rows: number of rows to print, defaults to 5 :param rows: int, optional :return: a pandas dataframe :rtype: pd.DataFrame :example: ``ds.tail()`` """ if self.df is None: ...
python
def time_series_rdd_from_observations(dt_index, df, ts_col, key_col, val_col): """ Instantiates a TimeSeriesRDD from a DataFrame of observations. An observation is a row containing a timestamp, a string key, and float value. Parameters ---------- dt_index : DateTimeIndex The index of t...
java
protected CellFormatter createDefaultFormatter(final String name, final Locale... locales) { final String key = String.format("format.%s", name); final String defaultFormat = messageResolver.getMessage(key); if(defaultFormat == null) { return null; } ...
java
@Override public int read() throws IOException { try { int value = super.read(); eofReached = value == -1; if (!eofReached) { bytesRead++; } return value; } catch (Exception e) { return onException(e); } ...
python
def controller(self): """ Check if multiple controllers are connected. :returns: Return the controller_id of the active controller. :rtype: string """ if hasattr(self, 'controller_id'): if len(self.controller_info['controllers']) > 1: raise T...
java
public void setMailTimeout(Integer timeout) throws SecurityException { checkWriteAccess(); boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManager.TYPE_MAIL); if (!hasAccess) throw new SecurityException("no access to update mail server settings"); Element mail = _getRootElement("mail"); mail.setAttribu...
python
def start(self): """Overrides default start behaviour by raising ConnectionError instead of custom requests_mock.exceptions.NoMockAddress. """ if self._http_last_send is not None: raise RuntimeError('HttpMock has already been started') # 1) save request.Session.send ...
python
def create(backbone: ModelFactory, input_block: typing.Optional[ModelFactory]=None): """ Vel factory function """ if input_block is None: input_block = IdentityFactory() return QModelFactory(input_block=input_block, backbone=backbone)
python
def write(self, script): # type: (str) -> None """Send a script to FORM. Write the given script to the communication channel to FORM. It could be buffered and so FORM may not execute the sent script until :meth:`flush` or :meth:`read` is called. """ if self._clos...
python
def version_add(package, version, pkghash, force=False): """ Add a new version for a given package hash. Version format needs to follow PEP 440. Versions are permanent - once created, they cannot be modified or deleted. """ team, owner, pkg = parse_package(package) session = _get_session(te...
python
def from_api_response(cls, reddit_session, json_dict): """Return an instance of the appropriate class from the json dict.""" # The Multireddit response contains the Subreddits attribute as a list # of dicts of the form {'name': 'subredditname'}. # We must convert each of these into a Sub...
python
def create_detector(self, detector): """Creates a new detector. Args: detector (object): the detector model object. Will be serialized as JSON. Returns: dictionary of the response (created detector model). """ resp = self._post(self._u(sel...
java
public void setBinding(String binding) throws JspException { if (!isValueReference(binding)) { throw new IllegalArgumentException("not a valid binding: " + binding); } _binding = binding; }
python
def parseFullScan(self, i, modifications=True): """ parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml """ scanObj = PeptideObject() peptide = str(i[1]) pid=i[2] if modifications: sql = '...
python
def ParseRecord(self, parser_mediator, key, structure): """Parse each record structure and return an EventObject if applicable. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): identifier of the struc...
java
public void setLocaterInfo(SourceLocator locator) { m_publicId = locator.getPublicId(); m_systemId = locator.getSystemId(); super.setLocaterInfo(locator); }
python
def QA_save_tdx_to_mongo(file_dir, client=DATABASE): """save file Arguments: file_dir {str:direction} -- 文件的地址 Keyword Arguments: client {Mongodb:Connection} -- Mongo Connection (default: {DATABASE}) """ reader = TdxMinBarReader() __coll = client.stock_min_five for...
python
def cross_entropy_loss(logits, one_hot_labels, label_smoothing=0, weight=1.0, scope=None): """Define a Cross Entropy loss using softmax_cross_entropy_with_logits. It can scale the loss by weight factor, and smooth the labels. Args: logits: [batch_size, num_classes] logits outputs of t...
python
def position_result_list(change_list): """ Returns a template which iters through the models and appends a new position column. """ result = result_list(change_list) # Remove sortable attributes for x in range(0, len(result['result_headers'])): result['result_headers'][x]['sorted'] ...
python
async def check_passwd(self, identity: str, passwd: str ) -> SessionIdentity : """ 通过密码检查身份 """ assert identity value, _ = await self._client.get(f"{self._prefix_identity}/{identity}") if value is None: logger.debug(f'Not found identity: {identity}') ...
python
def watermark(url, args=''): """ Returns the URL to a watermarked copy of the image specified. """ # initialize some variables args = args.split(',') params = dict( name=args.pop(0), opacity=0.5, tile=False, scale=1.0, greyscale=False, rotation=0...
java
public void clear() { //release a static buffer if possible if (_buffersToReuse != null && !_buffersToReuse.isEmpty()) { StaticBuffers.getInstance().releaseByteBuffer(BUFFER_KEY, _buffersToReuse.peek()); } else if (!_buffers.isEmpty()) { StaticBuffers.getInstance().releaseByteBuffer(BUFFER_KEY, _buffers.get...
java
public static Object jsoupParse(final ChainedHttpConfig config, final FromServer fromServer) { try { return Jsoup.parse(fromServer.getInputStream(), fromServer.getCharset().name(), fromServer.getUri().toString()); } catch (IOException e) { throw new TransportingException(e); ...
java
public static ExpressionTree stripParentheses(ExpressionTree tree) { while (tree instanceof ParenthesizedTree) { tree = ((ParenthesizedTree) tree).getExpression(); } return tree; }