language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def generate_features( self, sentence_text, wid ): ''' Generates and returns a list of strings, containing tab-separated features ID, FORM, LEMMA, CPOSTAG, POSTAG, FEATS of the word (the word with index *wid* from the given *sentence_text*). Parameters ----------...
java
public RateLimit getRateLimit() throws OAuthSystemException, OAuthProblemException { cleanError(); prepareToken(); OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient(); OAuthClient oAuthClient = new OAuthClient(httpClient); OAuthClientRequest bearerRequest = new OAuthBearerClientRequest...
java
public CachedData encode( final Object object ) { final CachedData result = _delegate.encode( object ); _statistics.register( StatsType.CACHED_DATA_SIZE, result.getData().length ); return result; }
java
@Override protected Object doExec(Element element, Object scope, String format, Object... arguments) throws IOException { Stack<Index> indexes = this.serializer.getIndexes(); if(indexes.size() == 0) { throw new TemplateException("Required ordered collection index is missing. Numbering operator ca...
java
private void learn(T[] data, RNNSearch<T,T> nns, int k, double radius, int[] y) { if (k < 2) { throw new IllegalArgumentException("Invalid k: " + k); } if (radius <= 0.0) { throw new IllegalArgumentException("Invalid radius: " + radius); } this.k = k; ...
python
def get_gene_source_set(gtf): """ get a dictionary of the set of all sources for a gene """ gene_to_source = {} db = get_gtf_db(gtf) for feature in complete_features(db): gene_id = feature['gene_id'][0] sources = gene_to_source.get(gene_id, set([])).union(set([feature.source])) ...
java
public <T> T getViewRepresentation(Class<T> T, boolean forceRefresh) { ScenarioGlobals currentScenarioGlobals = SenBotContext.getSenBotContext().getCucumberManager().getCurrentScenarioGlobals(); T foundView = currentScenarioGlobals == null ? null : (T) currentScenarioGlobals.getAttribute(T.getName()); if...
java
public static Boolean getAttributeBoolean(Tag tag, String attrName) throws EvaluatorException { Boolean b = getAttributeLiteral(tag, attrName).getBoolean(null); if (b == null) throw new EvaluatorException("attribute [" + attrName + "] must be a constant boolean value"); return b; }
python
def pairwise_point_combinations(xs, ys, anchors): """ Does an in-place addition of the four points that can be composed by combining coordinates from the two lists to the given list of anchors """ for i in xs: anchors.append((i, max(ys))) anchors.append((i, min(ys))) for i in ys:...
python
def ResolveHostnameToIP(host, port): """Resolves a hostname to an IP address.""" ip_addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC, 0, socket.IPPROTO_TCP) # getaddrinfo returns tuples (family, socktype, proto, canonname, sockaddr). # We are interested in sockaddr which i...
python
def process_params(mod_id, params, type_params): """ Takes as input a dictionary of parameters defined on a module and the information about the required parameters defined on the corresponding module type. Validatates that are required parameters were supplied and fills any missing parameters with ...
python
def get_values(self): """ Returns the cpd Examples -------- >>> from pgmpy.factors.discrete import TabularCPD >>> cpd = TabularCPD('grade', 3, [[0.1, 0.1], ... [0.1, 0.1], ... [0.8, 0.8]], ...
python
def get(self, interface_id): """ Get the interface from engine json :param str interface_id: interface ID to find :raises InterfaceNotFound: Cannot find interface """ # From within engine, skips nested iterators for this find # Make sure were dealing with...
java
Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) { MethodType optype = (MethodType)operator.type; int opcode = operator.opcode; if (opcode >= if_icmpeq && opcode <= if_icmple && rhs.type.constValue() instanceof Number && ((Number) rh...
java
protected OutputStream getAsynchronousOutputStream( final OutputStream outputStream) throws IOException { final int SIZE = 1024 * 1024 * 10; final PipedOutputStream pos = new PipedOutputStream(); final PipedInputStream pis = new PipedInputStream(pos, SIZE); final FinishableRunnable run = new FinishableRunna...
java
public static void load() { if (!isLoaded()) { ScriptInjector.fromString(LocalForageResources.INSTANCE.js().getText()).setWindow(ScriptInjector.TOP_WINDOW).inject(); } }
python
def _handle_stdout_event(self, fd, events): """Eventhandler for stdout""" assert fd == self.fd_stdout if events & self.ioloop.READ: # got data ready to read data = '' # Now basically we have two cases: either the client supports # HTTP/1.1 in wh...
java
public static void printHeaders(HttpServletRequest request) { Enumeration<String> e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = e.nextElement(); String value = request.getHeader(name); logger.info("header " + name + ":" + value); } }
python
def email_from_name(self): """Portal email name """ lab_from_name = self.laboratory.getName() portal_from_name = self.portal.email_from_name return lab_from_name or portal_from_name
python
def entry_to_matrix(prodigy_entry): """ Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating t...
python
def fromagp(args): """ %prog fromagp agpfile componentfasta objectfasta Generate chain file from AGP format. The components represent the old genome (target) and the objects represent new genome (query). """ from jcvi.formats.agp import AGP from jcvi.formats.sizes import Sizes p = Opti...
java
private ConfListVo convert(Config config, String appNameString, String envName, ZkDisconfData zkDisconfData) { ConfListVo confListVo = new ConfListVo(); confListVo.setConfigId(config.getId()); confListVo.setAppId(config.getAppId()); confListVo.setAppName(appNameString); confLis...
python
def _executor(self, host): ''' handler for multiprocessing library ''' try: exec_rc = self._executor_internal(host) #if type(exec_rc) != ReturnData and type(exec_rc) != ansible.runner.return_data.ReturnData: # raise Exception("unexpected return type: %s" % type(ex...
java
public OvhTask serviceName_domainTrust_domainTrustId_addDomainUserOnComposer_POST(String serviceName, Long domainTrustId, String domain, String password, String username) throws IOException { String qPath = "/horizonView/{serviceName}/domainTrust/{domainTrustId}/addDomainUserOnComposer"; StringBuilder sb = path(qPa...
java
public void initDriver(File shpFile, ShapeType shapeType, DbaseFileHeader dbaseHeader) throws IOException { String path = shpFile.getAbsolutePath(); String nameWithoutExt = path.substring(0,path.lastIndexOf('.')); this.shpFile = new File(nameWithoutExt+".shp"); this.shxFile = new File(na...
python
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ParticipantContext for this ParticipantInstance :rtype: twilio.rest.api.v2010.account.conference....
java
public void disambiguateHistoricDates(JCas jcas){ // build up a list with all found TIMEX expressions List<Timex3> linearDates = new ArrayList<Timex3>(); FSIterator iterTimex = jcas.getAnnotationIndex(Timex3.type).iterator(); // Create List of all Timexes of types "date" and "time" while (iterTimex.hasNex...
python
def get_installed_version_of(name, location=None): '''Gets the installed version of the given dap or None if not installed Searches in all dirs by default, otherwise in the given one''' if location: locations = [location] else: locations = _data_dirs() for loc in locations: ...
python
def gen_date_by_year(year): """ 获取当前年的随机时间字符串 :param: * year: (string) 长度为 4 位的年份字符串 :return: * date_str: (string) 传入年份的随机合法的日期 举例如下:: print('--- GetRandomTime.gen_date_by_year demo ---') print(GetRandomTime.gen_...
python
def _extract_attr_typed_value(txn_data): """ ATTR and GET_ATTR can have one of 'raw', 'enc' and 'hash' fields. This method checks which of them presents and return it's name and value in it. """ existing_keys = [key for key in ALL_ATR_KEYS if key in txn_data] if len(existing_keys) == 0: ...
java
public void include(String target, String element, Map<String, ?> parameterMap) throws JspException { include(target, element, false, parameterMap); }
java
public static boolean delete(File file) { if (!file.exists()) return false; if (file.isDirectory()) { File[] files = file.listFiles(); for (int i=0;files!=null && i<files.length;i++) delete(files[i]); } return file.delete();...
python
def get_trending_daily_not_starred(self): """Gets trending repositories NOT starred by user :return: List of daily-trending repositories which are not starred """ trending_daily = self.get_trending_daily() # repos trending daily starred_repos = self.get_starred_repos() # repos ...
java
protected int decodeMandatoryParameters(ISUPParameterFactory parameterFactory, byte[] b, int index) throws ParameterException { int localIndex = index; index += super.decodeMandatoryParameters(parameterFactory, b, index); if (b.length - index > 1) { try { ...
java
@Pure public List<Object> getCurrentValues() { if (this.allValues == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.allValues); }
java
private void initXmlBundle() throws CmsException { CmsFile file = m_cms.readFile(m_resource); m_bundleFiles.put(null, m_resource); m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file); initKeySetForXmlBundle(); }
python
def is_length(property_name, *, min_length=1, max_length=None, present_optional=False): """Returns a Validation that checks the length of a string.""" def check(val): """Checks that a value matches a scope-enclosed set of length parameters.""" if not val: return present_optional else: ...
python
def which(program): """Locate `program` in PATH Arguments: program (str): Name of program, e.g. "python" """ def is_exe(fpath): if os.path.isfile(fpath) and os.access(fpath, os.X_OK): return True return False for path in os.environ["PATH"].split(os.pathsep): ...
java
@Deprecated public static void setIntHeader(HttpMessage message, String name, Iterable<Integer> values) { message.headers().set(name, values); }
java
public boolean verify() throws SignatureException { if (verified) return verifyResult; if (sigAttr != null) { sig.update(sigAttr); if (RSAdata != null) { byte msd[] = messageDigest.digest(); messageDigest.update(msd); } ...
python
def _watch_progress(handler): """Context manager for creating a unix-domain socket and listen for ffmpeg progress events. The socket filename is yielded from the context manager and the socket is closed when the context manager is exited. Args: handler: a function to be called when progres...
java
@Override public ValueComparator compare(Value o) { if (o == null) { return ValueComparator.NOT_EQUAL_TO; } switch (o.getType()) { case NUMBERVALUE: NumberValue other = (NumberValue) o; int comp = compareTo(other); retur...
python
def replace(self, key, value, time, compress_level=-1): """ Replace a key/value to server ony if it does exist. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param time: Time in seconds that ...
java
final void close(final ConnectionPoolConnection conn) { if(closeQueue != null) { closeQueue.add(conn); } else { closer.close(conn); } }
java
void setClosedPath(int path, boolean b_yes_no) { if (isClosedPath(path) == b_yes_no) return; if (getPathSize(path) > 0) { int first = getFirstVertex(path); int last = getLastVertex(path); if (b_yes_no) { // make a circular list setNextVertex_(last, first); setPrevVertex_(first, last); //...
java
public final void setUndoManagerPolicy(UndoManagerPolicy policy) throws NullPointerException { if (policy == null) { throw new NullPointerException("The policy must not be null."); } if (this.policy == policy) { return; } final UndoManagerPolicy oldPolicy = this.policy; this.policy = policy; ...
python
def extract_variables(href): """Return a list of variable names used in a URI template.""" patterns = [re.sub(r'\*|:\d+', '', pattern) for pattern in re.findall(r'{[\+#\./;\?&]?([^}]+)*}', href)] variables = [] for pattern in patterns: for part in pattern.split(","): ...
python
def _decode_addr_key(self, obj_dict): """ Callback function to handle the decoding of the 'Addr' field. Serf msgpack 'Addr' as an IPv6 address, and the data needs to be unpack using socket.inet_ntop(). See: https://github.com/KushalP/serfclient-py/issues/20 :param obj_...
java
synchronized public Class toClass() throws ClassNotFoundException, UtilEvalError { if ( asClass != null ) return asClass; reset(); // "var" means untyped, return null class if ( evalName.equals("var") ) return asClass = null; /* Try straight...
python
def imresize(img, size, interpolate="bilinear", channel_first=False, **kwargs): """ Resize ``img`` to ``size``. As default, the shape of input image has to be (height, width, channel). Args: img (numpy.ndarray): Input image. size (tuple of int): Output shape. The order is (width, height...
python
def where(i): """ Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ o=i.get('out','') duoa=i.get('data_uoa','') r=c...
java
public static <T extends GraphQLType> List<T> sortGraphQLTypes(Collection<T> types) { List<T> sorted = new ArrayList<>(types); sorted.sort(graphQLTypeComparator()); return sorted; }
python
def _get_col_epsg(mapped_class, geom_attr): """Get the EPSG code associated with a geometry attribute. Arguments: geom_attr the key of the geometry property as defined in the SQLAlchemy mapper. If you use ``declarative_base`` this is the name of the geometry attribute as defined i...
python
def __extract_directory(self, path, files, destination): """Extracts a single directory to the specified directory on disk. Args: path (str): Relative (to the root of the archive) path of the directory to extract. files (dict): A ...
java
public Optional<DataType> handleFinalSet( TraversalStep traversalStep, Object tree, String key, DataType data ) { Optional<DataType> optSub = traversalStep.get( tree, key ); if ( !optSub.isPresent() || optSub.get() == null ) { // nothing is here so just set the data traversalSt...
java
public boolean validate(OneKey cnKey) throws CoseException { CBORObject obj = CBORObject.NewArray(); obj.Add(contextString); if (objProtected.size() > 0) obj.Add(rgbProtected); else obj.Add(CBORObject.FromObject(new byte[0])); obj.Add(externalData); obj.Add(rgbContent); ...
java
private FieldPosition[] getNegativePrefixFieldPositions() { if (negativePrefixFieldPositions == null) { if (negPrefixPattern != null) { negativePrefixFieldPositions = expandAffix(negPrefixPattern); } else { negativePrefixFieldPositions = EmptyFieldPosition...
python
def next(self): """ Handles the iteration by pulling the next line out of the stream, attempting to convert the response to JSON if necessary. :returns: Data representing what was seen in the feed """ while True: if not self._resp: self._start...
java
protected void logSoapMessage(String logMessage, SoapMessage soapMessage, boolean incoming) throws TransformerException { Transformer transformer = createIndentingTransformer(); StringWriter writer = new StringWriter(); transformer.transform(soapMessage.getEnvelope().getSource(), new St...
python
def fix_vcf_line(parts, ref_base): """Orient VCF allele calls with respect to reference base. Handles cases with ref and variant swaps. strand complements. """ swap = {"1/1": "0/0", "0/1": "0/1", "0/0": "1/1", "./.": "./."} complements = {"G": "C", "A": "T", "C": "G", "T": "A", "N": "N"} varinf...
java
public static Number count(char[] self, Object value) { return count(InvokerHelper.asIterator(self), value); }
python
def depends_on(self, dependency): """ List of packages that depend on dependency :param dependency: package name, e.g. 'vext' or 'Pillow' """ packages = self.package_info() return [package for package in packages if dependency in package.get("requires", "")]
python
def script(klass, args, interval): """ Run the script *args* every *interval* (e.g. "10s") to peform health check """ if isinstance(args, six.string_types) \ or isinstance(args, six.binary_type): warnings.warn( "Check.script should take...
java
public static Long createLong(final String str) { if (str == null) { return null; } return Long.decode(str); }
java
protected static BufferedImage loadImage (InputStream iis) throws IOException { BufferedImage image; if (iis instanceof ImageInputStream) { image = ImageIO.read(iis); } else { // if we don't already have an image input stream, create a memory cache image inp...
java
private void doMultiMapRemove(final Message<JsonObject> message) { final String name = message.body().getString("name"); if (name == null) { message.reply(new JsonObject().putString("status", "error").putString("message", "No name specified.")); return; } final Object key = message.body().g...
python
def notify_change(self, change): """Called when a property has changed.""" # Send the state to the frontend before the user-registered callbacks # are called. name = change['name'] if self.comm is not None and self.comm.kernel is not None: # Make sure this isn't infor...
python
def parse(self, vd, extent_loc): # type: (bytes, int) -> None ''' Parse a Volume Descriptor out of a string. Parameters: vd - The string containing the Volume Descriptor. extent_loc - The location on the ISO of this Volume Descriptor. Returns: Nothing....
python
def build_response( self, data: AwaitableOrValue[Optional[Dict[str, Any]]] ) -> AwaitableOrValue[ExecutionResult]: """Build response. Given a completed execution context and data, build the (data, errors) response defined by the "Response" section of the GraphQL spec. """ ...
java
@Override public void lock(T entity, LockModeType lockMode) { getEntityManager().lock(entity, lockMode); }
java
public byte[] readBytes() throws IORuntimeException { long len = file.length(); if (len >= Integer.MAX_VALUE) { throw new IORuntimeException("File is larger then max array size"); } byte[] bytes = new byte[(int) len]; FileInputStream in = null; int readLength; try { in = new FileInputStre...
python
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True): """ Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve. To only update the object, set the commit param to False. Returns the number of rows altered or None if...
java
@SuppressWarnings("unchecked") private StringBuffer buildEngineScript(StringBuffer engineScript,ServletContext servletContext) { List<Container> containers = ContainerUtil.getAllPublishedContainers(servletContext); String allowGetForSafariButMakeForgeryEasier = ""; String scriptTagProtection = DwrConstants.SCRIP...
java
public static String transform(File xmlFile, boolean verbose) throws SAXException, IOException { if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "transform(InputStream, boolean)"); } FileInputStream fis = new FileInputStream(xmlFile); S...
java
@Override public void clearCache(CPDefinition cpDefinition) { entityCache.removeResult(CPDefinitionModelImpl.ENTITY_CACHE_ENABLED, CPDefinitionImpl.class, cpDefinition.getPrimaryKey()); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGIN...
java
public BigDecimal getDecimalSecond() { BigDecimal sec = BigDecimal.valueOf(_second); if (_fraction != null) { sec = sec.add(_fraction); } return sec; }
python
def _get_arg_parser(func, types, args_and_defaults, delimiter_chars): """Return an ArgumentParser for the given function. Arguments are defined from the function arguments and their associated defaults. Args: func: function for which we want an ArgumentParser types: types to which the c...
java
public static Properties getSystemProperties() { try { return new Properties(System.getProperties()); } catch (final SecurityException ex) { LowLevelLogUtil.logException("Unable to access system properties.", ex); // Sandboxed - can't read System Properties ...
java
public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _jspService(request, response); }
java
@Nullable static Drawable maybeWrapWithScaleType( @Nullable Drawable drawable, @Nullable ScalingUtils.ScaleType scaleType, @Nullable PointF focusPoint) { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection("WrappingUtils#maybeWrapWithScaleType"); } if (drawable == null ||...
java
public InputType getOutputType(InputType... inputType) throws InvalidKerasConfigurationException { if (inputType.length > 1) throw new InvalidKerasConfigurationException( "Keras BatchNorm layer accepts only one input (received " + inputType.length + ")"); return this.getB...
python
def _parse_name(self, config): """ _parse_name scans the provided configuration block and extracts the vlan name. The config block is expected to always return the vlan name. The return dict is intended to be merged into the response dict. Args: config (str): The v...
java
@Override public void init(ServletConfig config) throws ServletException{ super.init(config); getStats = new ServletStats("get", getMonitoringIntervals()); postStats = new ServletStats("post", getMonitoringIntervals()); putStats = new ServletStats("put", getMonitoringIntervals()); ...
python
def save_training_samples(self, domain='', filename=''): """ Saves data previously added via add_training_sample(). Data saved in folder specified by Train.get_corpus_path(). :param domain: Name for domain folder. If not set, current timestamp will be used. ...
python
def queryjoin(argdict=dict(), **kwargs): """Turn a dictionary into a querystring for a URL. >>> args = dict(a=1, b=2, c="foo") >>> queryjoin(args) "a=1&b=2&c=foo" """ if kwargs: argdict.update(kwargs) if issubclass(type(argdict), dict): args = ["{}={}".f...
python
def wait(name, url='http://localhost:8080/manager', timeout=180): ''' Wait for the Tomcat Manager to load. Notice that if tomcat is not running we won't wait for it start and the state will fail. This state can be required in the tomcat.war_deployed state to make sure tomcat is running and that the...
java
@Override public DescribeProvisioningParametersResult describeProvisioningParameters(DescribeProvisioningParametersRequest request) { request = beforeClientExecution(request); return executeDescribeProvisioningParameters(request); }
java
public static boolean isTypeIncludedIn(TypeName value, Type... types) { for (Type item : types) { if (value.equals(typeName(item))) { return true; } } return false; }
python
def save(self): """ Saves changes made to the locally cached SecurityDocument object's data structures to the remote database. """ resp = self.r_session.put( self.document_url, data=self.json(), headers={'Content-Type': 'application/json'} ...
python
def show_current_number(parser, token): """Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} ...
python
def allocate_mid(mids): """ Allocate a MID which has not been used yet. """ i = 0 while True: mid = str(i) if mid not in mids: mids.add(mid) return mid i += 1
java
@Override public String get(Object key) { return this.groupedMap.get(DEFAULT_GROUP, Convert.toStr(key)); }
java
public static int getOptionPos(String flag, String[] options) { if (options == null) return -1; for (int i = 0; i < options.length; i++) { if ((options[i].length() > 0) && (options[i].charAt(0) == '-')) { // Check if it is a negative number try { Double.valueOf(options[i]); } catch (Num...
java
public Set<TypeSignature> findNamedTypes() { final Set<TypeSignature> collectedNamedTypes = new HashSet<>(); methods().forEach(m -> { findNamedTypes(collectedNamedTypes, m.returnTypeSignature()); m.parameters().forEach(p -> findNamedTypes(collectedNamedTypes, p.typeSignature()));...
java
public synchronized PaymentChannelServerState getOrCreateState(Wallet wallet, TransactionBroadcaster broadcaster) throws VerificationException { if (state == null) { switch (majorVersion) { case 1: state = new PaymentChannelV1ServerState(this, wallet, broadcaster)...
python
def _initialize_stretching_matrix(self): """ Set up the stretching matrix """ self.S = np.zeros((self.nz, self.nz)) if (self.nz==2) and (self.rd) and (self.delta): self.del1 = self.delta/(self.delta+1.) self.del2 = (self.delta+1.)**-1 self.Us = self.Ubg[0]-...
python
def update(self, activity_sid=values.unset, attributes=values.unset, friendly_name=values.unset, reject_pending_reservations=values.unset): """ Update the WorkerInstance :param unicode activity_sid: The activity_sid :param unicode attributes: The attributes...
python
def escape_html(value, allowed_tags=[], allowed_attributes=[], allowed_styles=[]): """ Template tag to sanitize string values. It accepts lists of allowed tags, attributes or styles in comma separated string or list format. For example: {% load sanitizer %} {% escape_html '<a h...
python
def rectify(self, slitlet2d, resampling, inverse=False): """Rectify slitlet using computed transformation. Parameters ---------- slitlet2d : numpy array Image containing the 2d slitlet image. resampling : int 1: nearest neighbour, 2: flux preserving inter...
python
def get_requirements(): """Get the dependencies.""" with open("requirements/project.txt") as f: requirements = [] for line in f.readlines(): line = line.strip() if line and not line.startswith('#'): requirements.append(line) return requirements