language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def fetch_gbwithparts(list_of_NC_accessions, email, folder): '''Download genbank files from NCBI using Biopython Entrez efetch. Args: list_of_NC_accessions (list): a list of strings, e.g ['NC_015758', 'NC_002695'] email (string): NCBI wants your email folder (string): Where the gb fil...
java
public void marshall(DeleteInputSecurityGroupRequest deleteInputSecurityGroupRequest, ProtocolMarshaller protocolMarshaller) { if (deleteInputSecurityGroupRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarsha...
python
def get_name_from_abbrev(abbrev, case_sensitive=False): """ Given a country code abbreviation, get the full name from the table. abbrev: (str) Country code to retrieve the full name of. case_sensitive: (bool) When True, enforce case sensitivity. """ if case_sensitive: country_code = abb...
python
def get_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs): """ Calculates both split ...
python
def msvs_parse_version(s): """ Split a Visual Studio version, which may in fact be something like '7.0Exp', into is version number (returned as a float) and trailing "suite" portion. """ num, suite = version_re.match(s).groups() return float(num), suite
python
def new_worker(self, name: str): """Creates a new Worker and start a new Thread with it. Returns the Worker.""" if not self.running: return self.immediate_worker worker = self._new_worker(name) self._start_worker(worker) return worker
java
public static Method getGetterMethod(Class<?> beanClass, String property, Class propertyType){ try{ try{ if(propertyType==boolean.class) return beanClass.getMethod(IS+getMethodSuffix(property)); }catch(NoSuchMethodException ignore){ // ...
java
public void jmolColorByChain(){ String script = "function color_by_chain(objtype, color_list) {"+ String.format("%n") + ""+ String.format("%n") + " if (color_list) {"+ String.format("%n") + " if (color_list.type == \"string\") {"+ String.format("%n") + " color_list = color_list.split(\...
java
public void train(String corpus) { CorpusLoader.walk(corpus, new CorpusLoader.Handler() { @Override public void handle(Document document) { List<List<Word>> simpleSentenceList = document.getSimpleSentenceList(); List<List<IWord>> co...
python
def get_states(self): """ Add outcome to variables of XMLBIF Return ------ dict: dict of type {variable: outcome tags} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_states() {'dog-out': [<Element OUTCOME at 0x7ffbabfcd...
java
public static void installSecureRandomProvider() { CoGProperties props = CoGProperties.getDefault(); String providerName = props.getSecureRandomProvider(); try { Class providerClass = Class.forName(providerName); Security.insertProviderAt( (Provider)providerClass.newInsta...
python
def process_tag(node): """ Recursively go through a tag's children, converting them, then convert the tag itself. """ text = '' exceptions = ['table'] for element in node.children: if isinstance(element, NavigableString): text += element elif not node.name in e...
python
def expand_batched_style(style, opts, mapping, nvals): """ Computes styles applied to a batched plot by iterating over the supplied list of style options and expanding any options found in the supplied style dictionary returning a data and mapping defining the data that should be added to the Column...
java
@SuppressWarnings("unchecked") @Override public EList<IfcRelAssociates> getHasAssociations() { return (EList<IfcRelAssociates>) eGet(Ifc4Package.Literals.IFC_OBJECT_DEFINITION__HAS_ASSOCIATIONS, true); }
python
def get_data_object(data_id, use_data_config=True): """ Normalize the data_id and query the server. If that is unavailable try the raw ID """ normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config) client = DataClient() data_obj = client.get(normalized_data_...
java
private Set<Integer> getConstraintNameIndexes() throws PropertyException{ Set<Integer> result = new HashSet<>(); Set<String> constraintNames = getConstraintNameList(); if(constraintNames.isEmpty()) return result; for(String constraintName: constraintNames){ int separatorIndex = constraintName.lastIndexOf(...
python
def effectiveness_from_NTU(NTU, Cr, subtype='counterflow'): r'''Returns the effectiveness of a heat exchanger at a specified heat capacity rate, number of transfer units, and configuration. The following configurations are supported: * Counterflow (ex. double-pipe) * Parallel (ex. ...
java
public static dospolicy_stats[] get(nitro_service service) throws Exception{ dospolicy_stats obj = new dospolicy_stats(); dospolicy_stats[] response = (dospolicy_stats[])obj.stat_resources(service); return response; }
java
public void setBaseConfigurationItems(java.util.Collection<BaseConfigurationItem> baseConfigurationItems) { if (baseConfigurationItems == null) { this.baseConfigurationItems = null; return; } this.baseConfigurationItems = new com.amazonaws.internal.SdkInternalList<BaseCo...
java
public <T extends Evaluation> T evaluateMDS(JavaRDD<MultiDataSet> data) { return evaluateMDS(data, DEFAULT_EVAL_SCORE_BATCH_SIZE); }
python
def decode_recvd(self, data): """ Decode and process the data from a received event. :param data: Data to decode and process. """ bits = data.split(':') if len(bits) == 2: key = self.keycheck.sub('_', bits[0]) fields = bits[1].split("|") ...
python
def cleanup(): """Close all sockets at exit""" for sck in list(Wdb._sockets): try: sck.close() except Exception: log.warn('Error in cleanup', exc_info=True)
python
def _process_incoming_data(self): """Retrieve and process any incoming data. :return: """ while self._running.is_set(): if self.poller.is_ready: self.data_in += self._receive() self.data_in = self._on_read_impl(self.data_in)
python
def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ clean_exit = False try: ...
python
def helper_predict_with_model(self, Xgrid, plot_raw, apply_link, percentiles, which_data_ycols, predict_kw, samples=0): """ Make the right decisions for prediction with a model based on the standard arguments of plotting. This is quite complex and will take a while to understand, so do not change a...
python
def get_json_types(annotated_type: SuperType) -> List[str]: """Returns the json types for the provided annotated type. This handles special cases for when we encounter UnionType and an Array. UnionType's will have all valid types returned. An Array will document what the items type is by placing that ...
java
private static boolean atLeastTwoPoints(Geometry[] points, int initialNumberOfPoints) throws SQLException { if (points.length < 1) { throw new SQLException("The geometry collection must not be empty"); } return atLeastTwoPoints(points[0].ge...
python
def get_last_modified_timestamp(self): """ Looks at the files in a git root directory and grabs the last modified timestamp """ cmd = "find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '" ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stde...
java
public String createSyslogHeader(int facility, int level, String localName, boolean sendLocalTimestamp, boolean sendLocalName) { StringBuffer buffer = new StringBuffer(); appendPriority(buffer, facility, level); if (sendLocalTimestamp) { appendTimestamp(buffer, new Date()); ...
python
def mid_point(self): ''' Returns the midpoint of the arc as a 1x2 numpy array. ''' midpoint_angle = self.from_angle + self.sign*self.length_degrees() / 2 return self.angle_as_point(midpoint_angle)
python
def stat_holidays(province='BC', year=2015): """ Returns a list of holiday dates for a province and year. """ return holidays.Canada(state=province, years=year).keys()
python
def get_scan_nr(element, attribname): """General method to get a scan nr from xml element of mzML/mzIdentML""" info = element.attrib[attribname] infomap = {y[0]: y[1] for y in [x.split('=') for x in info.split()]} return infomap['scan']
java
public static Symbol getSymbol(Tree tree) { if (tree instanceof JCFieldAccess) { return ((JCFieldAccess) tree).sym; } if (tree instanceof JCIdent) { return ((JCIdent) tree).sym; } if (tree instanceof JCMethodInvocation) { return ASTHelpers.getSymbol((MethodInvocationTree) tree); ...
python
def relative_path(path): """ Return the given path relative to this file. """ return os.path.join(os.path.dirname(__file__), path)
python
def get_chat_members_count( self, chat_id: Union[int, str] ) -> int: """Use this method to get the number of members in a chat. Args: chat_id (``int`` | ``str``): Unique identifier (int) or username (str) of the target chat. Returns: ...
java
public SyncMemberInner beginUpdate(String resourceGroupName, String serverName, String databaseName, String syncGroupName, String syncMemberName, SyncMemberInner parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName, syncMemberName, parameters).toBlo...
python
def _on_action_toggle(self): """Toggle the current fold trigger.""" block = FoldScope.find_parent_scope(self.editor.textCursor().block()) self.toggle_fold_trigger(block)
python
def step_undefined_step_snippets_should_not_exist_for_table(context): """ Checks if undefined-step snippets are not provided. EXAMPLE: Then undefined-step snippets should not exist for: | Step | | When an known step is used | | Then another known step is used | ...
java
public static Projection project(Projection... projection) { if (projection.length == 1) { return projection[0]; } else { Projection x = new Projection(true); for (Projection p : projection) { x.addToArray(p.toJson()); } return ...
java
public java.util.List<String> getEnableLogTypes() { if (enableLogTypes == null) { enableLogTypes = new com.amazonaws.internal.SdkInternalList<String>(); } return enableLogTypes; }
java
@SuppressWarnings("deprecation") public static java.sql.Time toSqlTime(LocalTime time) { return new java.sql.Time(time.getHour(), time.getMinute(), time.getSecond()); }
python
def BHS(self, params): """ BHS label Branch to the instruction at label if the C flag is set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BHS label def BHS_func(): if self.is_C_...
python
def get_linc_rna_genes( path_or_buffer, remove_duplicates=True, **kwargs): r"""Get list of all protein-coding genes based on Ensembl GTF file. Parameters ---------- See :func:`get_genes` function. Returns ------- `pandas.DataFrame` Table with rows corres...
python
def _wrap_jinja_filter(self, function): """Propagate exceptions as undefined values filter.""" def wrapper(*args, **kwargs): """Filter wrapper.""" try: return function(*args, **kwargs) except Exception: # pylint: disable=broad-except r...
java
public void marshall(DvbNitSettings dvbNitSettings, ProtocolMarshaller protocolMarshaller) { if (dvbNitSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(dvbNitSettings.getNetworkId(), NETWOR...
java
public boolean isTopLevelMenu() { MenuContainer container = WebUtilities.getAncestorOfClass(MenuContainer.class, this); if (container instanceof WMenuItemGroup) { container = WebUtilities.getAncestorOfClass(MenuContainer.class, container); } return container instanceof WMenu; }
java
protected List<ItemState> reindexSameNameSiblings(NodeData cause, ItemDataConsumer dataManager) throws RepositoryException { List<ItemState> changes = new ArrayList<ItemState>(); NodeData parentNodeData = (NodeData)dataManager.getItemData(cause.getParentIdentifier()); NodeData nextSibling =...
java
public static RebalanceTaskInfoMap encodeRebalanceTaskInfoMap(RebalanceTaskInfo stealInfo) { return RebalanceTaskInfoMap.newBuilder() .setStealerId(stealInfo.getStealerId()) .setDonorId(stealInfo.getDonorId()) ...
python
def p_expr_XOR_expr(p): """ expr : expr XOR expr """ p[0] = make_binary(p.lineno(2), 'XOR', p[1], p[3], lambda x, y: (x and not y) or (not x and y))
python
def getopt_default(self, option): """ Default method to get an option """ if option not in self.conf: print("Unrecognized option %r" % option) return print("%s: %s" % (option, self.conf[option]))
java
protected void doReset() { this.total = this.math.createZeroValue(); this.maximum = this.math.createZeroValue(); this.minimum = null; this.mean = this.math.createZeroValue(); this.meanValue = 0.0d; this.count = 0; }
java
public static authenticationvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{ authenticationvserver_authenticationradiuspolicy_binding obj = new authenticationvserver_authenticationradiuspolicy_binding(); obj.set_name(name); authenticationvserver_authentication...
java
private ClassTypeSignature getClassTypeSignature( ParameterizedType parameterizedType) { Class<?> rawType = (Class<?>) parameterizedType.getRawType(); Type[] typeArguments = parameterizedType.getActualTypeArguments(); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArguments.length]; for...
python
def _cholesky(self, A, **kwargs): """ method to handle potential problems with the cholesky decomposition. will try to increase L2 regularization of the penalty matrix to do away with non-positive-definite errors Parameters ---------- A : np.array Retur...
java
public FutureData<LimitList> listLimits(String service, int page, int perPage) { if (service == null || service.isEmpty()) { throw new IllegalArgumentException("A service is required"); } FutureData<LimitList> future = new FutureData<>(); ParamBuilder b = newParams(); ...
python
def observed(func): """ Just like :meth:`Observable.observed`. .. deprecated:: 1.99.1 """ def wrapper(*args, **kwargs): self = args[0] assert(isinstance(self, Observable)) self._notify_method_before(self, func.__name__, args, kwargs) res = func(*args, **kwargs) ...
java
@Override public EClass getIfcStructuralLoadOrResult() { if (ifcStructuralLoadOrResultEClass == null) { ifcStructuralLoadOrResultEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(645); } return ifcStructuralLoadOrResultEClass; }
python
def _get_ref(repo, name): ''' Return ref tuple if ref is in the repo. ''' if name == 'base': name = repo['base'] if name == repo['base'] or name in envs(): if repo['branch_method'] == 'branches': return _get_branch(repo['repo'], name) \ or _get_tag(repo['r...
java
@SuppressWarnings( "unchecked" ) public static String createClassPath( MavenProject project, List<Artifact> pluginArtifacts, List<String> outDirs ) { String cp = new String(); Set<Artifact> classPathElements = Collections.synchronizedSet( new LinkedHashSet<Artifact>() ); Set<Artifact> de...
python
def update_image(self, name): # The `_image` is to avoid conflicts with MutableMapping.update. """ Update (i.e., rename) the image :param str name: the new name for the image :return: an updated `Image` object :rtype: Image :raises DOAPIError: if the API endpoint...
python
def append(self, fdata, offset, query='/content/uploads'): """ append binary data to an upload `fdata` - binary data to send to pulp `offset` - the amount of previously-uploaded data """ query = '%s/%s/%s/' % (query, self.uid, offset) _r = self.connector.put(query...
python
def shrink(self, new_size): """ Reduce the size of this block :param int new_size: The new size :return: None """ self.size = new_size if self.sort == 'string': self.null_terminated = False # string without the null byte terminator self._...
java
public static OAuthRegisteredService getRegisteredOAuthServiceByRedirectUri(final ServicesManager servicesManager, final String redirectUri) { return getRegisteredOAuthServiceByPredicate(servicesManager, s -> s.matches(redirectUri)); }
java
public final String getDisplayName(boolean daylight, int style) { return getDisplayName(daylight, style, ULocale.getDefault(Category.DISPLAY)); }
python
def _map_content_types(archetype_tool, catalogs_definition): """ Updates the mapping for content_types against catalogs :archetype_tool: an archetype_tool object :catalogs_definition: a dictionary like { CATALOG_ID: { 'types': ['ContentType', ...], '...
java
@GwtIncompatible("java.util.regex.Pattern") public void matches(Pattern regex) { if (!regex.matcher(actual()).matches()) { failWithActual("expected to match", regex); } }
python
def get_pypi_version(): """ Returns the version info from pypi for this app. """ try: response = requests.get(PYPI_URL, timeout=HALF_SECOND_TIMEOUT) response.raise_for_status() data = response.json() version_str = data["info"]["version"] return _parse_version_str(...
python
def _tls_del_pad(p): """ Provided with a just decrypted TLSCiphertext (now a TLSPlaintext instance) p, the function removes the trailing padding found in p.data. It also performs some sanity checks on the padding (length, content, ...). False is returned if one of the check fails. Otherwise, True is...
python
def get(zpool, prop=None, show_source=False, parsable=True): ''' .. versionadded:: 2016.3.0 Retrieves the given list of properties zpool : string Name of storage pool prop : string Optional name of property to retrieve show_source : boolean Show source of property ...
java
public static Color HSVtoRGB (float h, float s, float v, float alpha) { Color c = HSVtoRGB(h, s, v); c.a = alpha; return c; }
python
def output_to_file(filename, tracklisting, action): """ Produce requested output; either output text file, tag audio file or do both. filename: a string of path + filename without file extension tracklisting: a string containing a tracklisting action: 'tag', 'text' or 'both', from command line ...
java
@GET @Path("/mode") @Produces(MediaType.APPLICATION_JSON) public Response getMode(@Context final HttpServletRequest req) { IndexTaskUtils.datasourceAuthorizationCheck(req, Action.READ, getDataSource(), authorizerMapper); return Response.ok(isParallelMode() ? "parallel" : "sequential").build(); }
java
public JcNumber mod(Number val) { JcNumber ret = new JcNumber(val, this, OPERATOR.Number.MOD); QueryRecorder.recordInvocationConditional(this, "mod", ret, QueryRecorder.literal(val)); return ret; }
python
def preprocess(self): """Preprocessing. Flattens the object. Important data comes on the 'theGroup' dictionary inside of the response. Instead, every element of the 'theGroup' dictionary is taken out to the main attrs dictionary. Notes on the group get some html tags removed. ...
java
public static Expression createExpressionForField(FieldExtension fieldExtension) { if (StringUtils.isNotEmpty(fieldExtension.getExpression())) { ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager(); return expressionManager.createExpression...
python
def _parse_color(self, color): """Setup the color scheme""" # If column was specified, force a scheme # It could be that there is a column named 'blue' for example if isinstance(color, dict): if 'column' not in color: raise ValueError("Color must include a 'co...
python
def min_eta_for_em_bright(bh_spin_z, ns_g_mass, mNS_pts, sBH_pts, eta_mins): """ Function that uses the end product of generate_em_constraint_data to swipe over a set of NS-BH binaries and determine the minimum symmetric mass ratio required by each binary to yield a remnant disk mass that exceeds a ...
java
@Override protected boolean prepare(final Context2D context, final Attributes attr, final double alpha) { final double end = attr.getEndAngle(); final double beg = attr.getStartAngle(); if (beg == end) { return false; } final double ord = attr.getOut...
java
private boolean saveForest(Document doc, String revID, Map<String, Object> properties) throws ForestException { // after insertRevision, the selected revision is inserted revision. // need to select current revision. doc.s...
python
def send_calibrate_magnetometer(self): """Request magnetometer calibration.""" # ArduPilot requires the MAV_CMD_DO_START_MAG_CAL command, only present in the ardupilotmega.xml definition if self._autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA: calibration_command = se...
python
def coverage(self): """ If there is a .coverage file available, this will attempt to form a DataFrame with that information in it, which will contain the columns: * filename * lines_covered * total_lines * coverage If it can't be found or parsed, an ...
java
public static String toHexString(float f) { if (Math.abs(f) < FloatConsts.MIN_NORMAL && f != 0.0f ) {// float subnormal // Adjust exponent to create subnormal double, then // replace subnormal double exponent with subnormal float // exponent String s ...
java
public CreateNotificationResponse createNotification(CreateNotificationRequest request) { checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string."); checkStringNotEmpty(request.getEndpoint(), "The parameter endpoint should NOT be nu...
python
def query(params=None): ''' Make a web call to QingCloud IaaS API. ''' path = 'https://api.qingcloud.com/iaas/' access_key_id = config.get_cloud_config_value( 'access_key_id', get_configured_provider(), __opts__, search_global=False ) access_key_secret = config.get_cloud_config_valu...
python
def find(self, regexp, negate_regexp=False, class_pattern=None, find_fnc=re.search, refresh_cache=False): """ yield the full path of the matching regular expression and the match itself """ if refresh_cache or not hasattr(self, ...
java
@Override public PersistentResourceXMLDescription getParserDescription() { return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace()) .addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT) .addAttribute(ElytronDefinition.INITIAL_...
java
@Override public CommerceRegion findByCommerceCountryId_First( long commerceCountryId, OrderByComparator<CommerceRegion> orderByComparator) throws NoSuchRegionException { CommerceRegion commerceRegion = fetchByCommerceCountryId_First(commerceCountryId, orderByComparator); if (commerceRegion != null) { ...
java
public double getValueAsPrice(double evaluationTime, AnalyticModel model) { ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); DiscountCurve discountCurve = model.getDiscountCurve(discountCurveName); DiscountCurve discountCurveForForward = null; if(forwardCurve == null && forwardCurveName != ...
python
def set_connection_type(self, connection_type): """ Sets the connection resource type, i.e the way in which the Clients connects to a PLC. :param connection_type: 1 for PG, 2 for OP, 3 to 10 for S7 Basic """ result = self.library.Cli_SetConnectionType(self.pointer, ...
java
public static void setWsLogger(Class<?> clazz) { try { Class<?>[] classParams = { String.class, Class.class, String.class }; wsLogger = clazz == null ? null : clazz.getConstructor(classParams); } catch (NoSuchMethodException e) { throw new RuntimeException(e); ...
python
def do_shutdown (self): """Shutdown the queue by not accepting any more URLs.""" with self.mutex: unfinished = self.unfinished_tasks - len(self.queue) self.queue.clear() if unfinished <= 0: if unfinished < 0: raise ValueError('shutd...
java
@SuppressWarnings("restriction") public static List<WorkItem> getResources(ChangeSet set) { if (set != null && !set.isEmpty()) { IResource[] resources = set.getResources(); List<WorkItem> filtered = new ArrayList<>(); for (IResource resource : resources) { ...
java
public static void serializeWriterFilePermissions(State state, int numBranches, int branchId, FsPermission fsPermissions) { serializeFsPermissions(state, ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PERMISSIONS, numBranches, branchId), fsPermissions); }
python
def uni_to(self, target, *args, **kwargs): """Unified to.""" logging.debug(_('target: %s, args: %s, kwargs: %s'), target, args, kwargs) return getattr(self, self.func_dict[target])(*args, **kwargs)
python
def get_film(film_id): ''' Return a single film ''' result = _get(film_id, settings.FILMS) return Film(result.content)
java
public static void sendDevTimeError( String messageKey, Object[] messageArgs, Throwable cause, int productionTimeErrorCode, ServletRequest request, ServletResponse response, ServletContext servletContext ) throws IOException ...
python
def get_position(self, subject): """Get offset in character for the given subject from the start of text edit area""" cursor = self.textCursor() if subject == 'cursor': pass elif subject == 'sol': cursor.movePosition(QTextCursor.StartOfBlock) ...
java
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception { // Wait until the length prefix is available. if (channelBuffer.readableBytes() < 4) { // If null is returned, it means there is not enough data yet. ...
java
private static boolean isParameterSeparator(char c) { if (Character.isWhitespace(c)) { return true; } for (char separator : PARAMETER_SEPARATORS) { if (c == separator) { return true; } } return false; }
python
def log(self, level, message, *args, **kwargs): """ This is the primary method to override to ensure logging with extra options gets correctly specified. """ extra = self.extras.copy() extra.update(kwargs.pop('extra', {})) kwargs['extra'] = extra self.log...