language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def new_pic_inline(cls, shape_id, rId, filename, cx, cy): """ Return a new `wp:inline` element containing the `pic:pic` element specified by the argument values. """ pic_id = 0 # Word doesn't seem to use this, but does not omit it pic = CT_Picture.new(pic_id, filename, r...
java
public boolean failsChecks(String text, CheckResult checkResult) { int length = text.length(); int result = 0; if (checkResult != null) { checkResult.position = 0; checkResult.numerics = null; checkResult.restrictionLevel = null; } if (0 != (...
python
def as_text(self, is_proof=True, is_pretty=False): """Return the DDO as a JSON text. :param if is_proof: if False then do not include the 'proof' element. :param is_pretty: If True return dictionary in a prettier way, bool :return: str """ data = self.as_dictionary(is_pr...
java
public HttpSession getSession(boolean create) { // 321485 if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_NAME,"getSession", "create " + String.valueOf(create) + ", this -> "+this); } if (WCCustomPrope...
java
public JSONObject antiPornGif(byte[] imgData) { AipRequest request = new AipRequest(); // check param JSONObject checkRet = checkImgFormat(imgData, "gif"); if (!"0".equals(checkRet.getString("error_code"))) { return checkRet; } preOperation(request); ...
java
public NotificationChain basicSetMemberCallTarget(XExpression newMemberCallTarget, NotificationChain msgs) { XExpression oldMemberCallTarget = memberCallTarget; memberCallTarget = newMemberCallTarget; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SE...
java
public alluxio.grpc.MasterHeartbeatPOptionsOrBuilder getOptionsOrBuilder() { return options_ == null ? alluxio.grpc.MasterHeartbeatPOptions.getDefaultInstance() : options_; }
python
def parse_resources_directory(self, rva, size=0, base_rva = None, level = 0, dirs=None): """Parse the resources directory. Given the RVA of the resources directory, it will process all its entries. The root will have the corresponding member of its structure, IM...
python
def get_candidate_config(self, merge=False, formal=False): """ Retrieve the configuration loaded as candidate config in your configuration session. :param merge: Merge candidate config with running config to return the complete configuration including all changed ...
java
protected int findBestMatch(double[] p) { int bestCluster = -1; bestDistance = Double.MAX_VALUE; for (int j = 0; j < clusters.size; j++) { double d = distanceSq(p,clusters.get(j)); if( d < bestDistance ) { bestDistance = d; bestCluster = j; } } return bestCluster; }
python
def stop(self, skip_final_snapshot=False, final_snapshot_id=''): """ Delete this DBInstance. :type skip_final_snapshot: bool :param skip_final_snapshot: This parameter determines whether a final db snapshot is created before the instance ...
python
def load_parameter_file(file_path, name = ''): """ Load parameters from a YAML file (or a directory containing YAML files). :returns: An instance of :any:`ParameterNode` or :any:`Scale` or :any:`Parameter`. """ if not os.path.exists(file_path): raise ValueError("{} doest not exist".format(f...
java
public Space merge(Space other) { float minx = Math.min(x, other.x); float miny = Math.min(y, other.y); float newwidth = width+other.width; float newheight = height+other.height; if (x == other.x) { newwidth = width; } else { newheight = height; } return new Space(minx, miny, newwidth, newheigh...
python
def remove(self, event, subscriber): """ Remove a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be removed. """ subs = self._subscribers if event not in subs: raise ValueError('No subscribers: %r' % ...
java
public void marshall(CreateComputerRequest createComputerRequest, ProtocolMarshaller protocolMarshaller) { if (createComputerRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createComputerRe...
java
public static Parser<Void> many1(CharPredicate predicate) { return Patterns.many1(predicate).toScanner(predicate + "+"); }
java
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters List<String> metaKeys = null; String url = null; // parse command-line input ar...
java
protected void ensureTransitionAllowed(CmmnActivityExecution execution, CaseExecutionState expected, CaseExecutionState target, String transition) { String id = execution.getId(); CaseExecutionState currentState = execution.getCurrentState(); // the state "suspending" or "terminating" will set immediately...
java
public ResourceBundle getResourceBundle(FacesContext ctx, String name) { if (defaultApplication != null) { return defaultApplication.getResourceBundle(ctx, name); } throw new UnsupportedOperationException(); }
java
private void copyBlock(DataInputStream in, VersionAndOpcode versionAndOpcode) throws IOException { // Read in the header CopyBlockHeader copyBlockHeader = new CopyBlockHeader(versionAndOpcode); copyBlockHeader.readFields(in); long startTime = System.currentTimeMillis(); int namespaceId = ...
java
public OvhTask serviceName_partition_partitionName_snapshot_POST(String serviceName, String partitionName, OvhSnapshotEnum snapshotType) throws IOException { String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot"; StringBuilder sb = path(qPath, serviceName, partitionName); HashMap<Stri...
python
def __is_valid_value_for_arg(self, arg, value, check_extension=True): """Check if value is allowed for arg Some commands only allow a limited set of values. The method always returns True for methods that do not provide such a set. :param arg: the argument's name :param...
java
ServiceName serviceName(final ModelNode operation) { String name = null; PathAddress pa = PathAddress.pathAddress(operation.require(OP_ADDR)); for (int i = pa.size() - 1; i > 0; i--) { PathElement pe = pa.getElement(i); if (key.equals(pe.getKey())) { name ...
java
public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println("Usage: JarHelper jarname.jar directory"); return; } JarHelper jarHelper = new JarHelper(); jarHelper.mVerbose = true; File destJar = new File(args[0]); File dirOrFile2Jar = new File(args[1]); ja...
java
public List<AlternativeInfo> calcAlternatives(int from, int to) { AlternativeBidirSearch altBidirDijktra = new AlternativeBidirSearch( graph, weighting, traversalMode, maxExplorationFactor * 2); altBidirDijktra.setMaxVisitedNodes(maxVisitedNodes); if (weightApproximator != null) ...
python
def create_service(self, *args, **kwargs): """Create a service to current scope. See :class:`pykechain.Client.create_service` for available parameters. .. versionadded:: 1.13 """ return self._client.create_service(*args, scope=self.id, **kwargs)
python
def _check_element(self, lookup_strings, instance): """Return True if lookup string/value pairs match against the passed object. """ for q, val in lookup_strings.items(): if not field_lookup(instance, q, val, True): return False return True
python
def create_wf_instances(self, roles=None): """ Creates wf instances. Args: roles (list): role list Returns: (list): wf instances """ # if roles specified then create an instance for each role # else create only one instance if ro...
java
private static void unregisterMBean(String name) { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { synchronized (mbs) { ObjectName objName = new ObjectName(name); if (mbs.isRegistered(objName)) { mbs.unregisterMBean(objN...
java
public static SynchronizedGeneratorIdentity basedOn(String quorum, String znode, Supplier<Duration> claimDurationSupplier) throws IOException { ZooKeeperConnection zooKeeperConnection = ne...
python
def teach_students(self): """ Train each model (student) with the labeled data using bootstrap aggregating (bagging). """ dataset = self.dataset for student in self.students: bag = self._labeled_uniform_sample(int(dataset.len_labeled())) while bag....
java
public DescribeVpcEndpointsRequest withVpcEndpointIds(String... vpcEndpointIds) { if (this.vpcEndpointIds == null) { setVpcEndpointIds(new com.amazonaws.internal.SdkInternalList<String>(vpcEndpointIds.length)); } for (String ele : vpcEndpointIds) { this.vpcEndpointIds.add...
python
def namedb_preorder_insert( cur, preorder_rec ): """ Add a name or namespace preorder record, if it doesn't exist already. DO NOT CALL THIS DIRECTLY. """ preorder_row = copy.deepcopy( preorder_rec ) assert 'preorder_hash' in preorder_row, "BUG: missing preorder_hash" try: pre...
java
@Override public synchronized void dropEntity(String entity) throws DatabaseEngineException { if (!containsEntity(entity)) { return; } dropEntity(entities.get(entity).getEntity()); }
java
@Override public UniversalKafkaQueue init() throws Exception { super.init(); if (getMessageFactory() == null) { setMessageFactory(UniversalIdIntQueueMessageFactory.INSTANCE); } return this; }
python
def iterator(self): """ Add the default language information to all returned objects. """ default_language = getattr(self, '_default_language', None) for obj in super(MultilingualModelQuerySet, self).iterator(): obj._default_language = default_language yie...
java
public static <T1, T2, R1, R2, R> CompletableFuture<R> forEach3(CompletableFuture<? extends T1> value1, Function<? super T1, ? extends CompletableFuture<R1>> value2, BiFunction<? super...
python
def op(scalars_layout, collections=None): """Creates a summary that contains a layout. When users navigate to the custom scalars dashboard, they will see a layout based on the proto provided to this function. Args: scalars_layout: The scalars_layout_pb2.Layout proto that specifies the layout. ...
java
public static List<String> getUnixGroups(String user) throws IOException { String result; List<String> groups = new ArrayList<>(); try { result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(user)); } catch (ExitCodeException e) { // if we didn't get the group - just return empt...
python
def cache_property(key, empty, type): """Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.""" return property(lambda x: x._get_cache_value(key, empty, type), lambda x, v: x._set_cache_value(key, v, type), ...
java
public Shape[] union(Shape target, Shape other) { target = target.transform(new Transform()); other = other.transform(new Transform()); if (!target.intersects(other)) { return new Shape[] {target, other}; } // handle the case where intersects is true but really we're talking // about edge ...
python
def _h_function(self,h): """ private method for the spherical variogram "h" function Parameters ---------- h : (float or numpy.ndarray) distance(s) Returns ------- h_function : float or numpy.ndarray the value of the "h" function implied ...
python
def _set_property(xml_root, name, value, properties=None): """Sets property to specified value.""" if properties is None: properties = xml_root.find("properties") for prop in properties: if prop.get("name") == name: prop.set("value", utils.get_unicode_str(value)) bre...
python
def _listdir(pth, extensions): """Non-raising listdir.""" try: return [fname for fname in os.listdir(pth) if os.path.splitext(fname)[1] in extensions] except OSError: # pragma: nocover pass
python
def get_polygons(self): """ Retrieves all of the user's polygons registered on the Agro API. :returns: list of `pyowm.agro10.polygon.Polygon` objects """ status, data = self.http_client.get_json( POLYGONS_URI, params={'appid': self.API_key}, ...
python
def aggregate(self, block_size): ''' geo.aggregate(block_size) Returns copy of raster aggregated to smaller resolution, by adding cells. ''' raster2 = block_reduce(self.raster, block_size, func=np.ma.sum) geot = self.geot geot = (geot[0], block_size[0] * geot[1],...
python
def dft_optsize(im, shape=None): """Resize image for optimal DFT and computes it Parameters ---------- im: 2d array The image shape: 2 numbers, optional The shape of the output image (None will optimize the shape) Returns ------- dft: 2d array The dft in CCS rep...
java
public static final <T> Stream<T> diGraph(T root, Function<? super T, ? extends Stream<T>> edges) { return DiGraphIterator.stream(root, edges); }
python
def is_numeric(property_name, *, numtype="float", min=None, max=None, present_optional=False, message=None): """Returns a Validation that checks a property as a number, with optional range constraints.""" if numtype == "int": cast = util.try_parse_int elif numtype == "decimal": ...
python
def get_quantile_levels(density, x, y, xp, yp, q, normalize=True): """Compute density levels for given quantiles by interpolation For a given 2D density, compute the density levels at which the resulting contours contain the fraction `1-q` of all data points. E.g. for a measurement of 1000 events, all ...
python
def sceneRect( self ): """ Returns the scene geometry for this node by resolving any \ inheritance position data since QGraphicsItem's return \ relative-space positions. :return <QRectF> """ pos = self.scenePos() rect = self.rect() ...
python
def moment2(self): """The second time delay weighted statistical momens of the instantaneous unit hydrograph.""" moment1 = self.moment1 delays, response = self.delay_response_series return statstools.calc_mean_time_deviation( delays, response, moment1)
python
def is_valid(self): ''' Validate form. Return True if Django validates the form, the username obeys the parameters, and passwords match. Return False otherwise. ''' if not super(DeleteUserForm, self).is_valid(): return False if self.user == self.request.user: ...
java
@Override public UpdateXssMatchSetResult updateXssMatchSet(UpdateXssMatchSetRequest request) { request = beforeClientExecution(request); return executeUpdateXssMatchSet(request); }
python
def parse(self,type_regex=None): """ Each line of the frame cache file is like the following: /frames/E13/LHO/frames/hoftMon_H1/H-H1_DMT_C00_L2-9246,H,H1_DMT_C00_L2,1,16 1240664820 6231 {924600000 924646720 924646784 924647472 924647712 924700000} The description is as follows: 1.1) Directory pat...
python
def association_rules(self): """ Returns association rules that were generated. Only if implements AssociationRulesProducer. :return: the association rules that were generated :rtype: AssociationRules """ if not self.check_type(self.jobject, "weka.associations.Associatio...
python
def msvc9_query_vcvarsall(ver, arch='x86', *args, **kwargs): """ Patched "distutils.msvc9compiler.query_vcvarsall" for support extra compilers. Set environment without use of "vcvarsall.bat". Known supported compilers ------------------------- Microsoft Visual C++ 9.0: Microsoft Vi...
python
def tables(self): """ :return: all tables stored in this database """ cursor = self.connection.cursor() cursor.execute("show tables in %s" % self.db) self._tables = [t.Table(r[0], con=self.connection, db=self.db) for r in cursor.fetchall()] return self._tables
python
def get_method_by_name(self, class_name, method_name, method_descriptor): """ Search for a :class:`EncodedMethod` in all classes in this analysis :param class_name: name of the class, for example 'Ljava/lang/Object;' :param method_name: name of the method, for example 'onCreate' ...
python
def most_populated(adf): """ Looks at each column, using the one with the most values Honours the Trump override/failsafe logic. """ # just look at the feeds, ignore overrides and failsafes: feeds_only = adf[adf.columns[1:-1]] # find the most populated feed cnt_...
java
public static String entityEncode(String text) { String result = text; if (result == null) { return result; } // The escapeXml function doesn't cope with some 'special' chrs return StringEscapeUtils.escapeXml10(XMLStringUtil.escapeControlChrs(result)); }
python
def _get_top_states(saltenv='base'): ''' Equivalent to a salt cli: salt web state.show_top ''' alt_states = [] try: returned = __salt__['state.show_top']() for i in returned[saltenv]: alt_states.append(i) except Exception: raise # log.info("top states: %s"...
python
def do_list_modules(self, long_output=None,sort_order=None): """Display a list of loaded modules. Config items: - shutit.list_modules['long'] If set, also print each module's run order value - shutit.list_modules['sort'] Select the column by which the list is ordered: - id: sort the list by mo...
java
public static void searchInFile(Pattern p, String inFile, String outFile, int seedLimit, int graphPerSeed) throws FileNotFoundException { SimpleIOHandler h = new SimpleIOHandler(); Model model = h.convertFromOWL(new FileInputStream(inFile)); Map<BioPAXElement,List<Match>> matchMap = Searcher.search(model, p);...
python
def configure(self, config_file): """ Parse configuration, and setup objects to use it. """ cfg = configparser.RawConfigParser() try: cfg.readfp(open(config_file)) except IOError as err: logger.critical( 'Error while reading config...
python
def read(self, size=-1): """Read at most `size` bytes from the file (less if there isn't enough data). The bytes are returned as an instance of :class:`str` (:class:`bytes` in python 3). If `size` is negative or omitted all data is read. :Parameters: - `size` (optiona...
python
async def get_devices(self): """Get the local installed version.""" data = await self.api("devices") if self.connected and self.authenticated: self._devices = data else: self._devices = self._devices _LOGGER.debug(self._devices)
java
public GroupName getGroupName(@NonNull List<String> prefixPath, @NonNull Map<String, MetricValue> extraTags) { final Stream<String> suffixPath = data.entrySet().stream() .filter(entry -> entry.getKey().getLeft().isPresent()) // Only retain int keys. .sorted(Comparator.comparing(e...
java
@Override public void releaseKam(String handle) { if (handle == null) { throw new InvalidArgument("handle", handle); } // Purge any cache entries purgeHandle(handle); }
python
def windowed_hudson_fst(pos, ac1, ac2, size=None, start=None, stop=None, step=None, windows=None, fill=np.nan): """Estimate average Fst in windows over a single chromosome/contig, following the method of Hudson (1992) elaborated by Bhatia et al. (2013). Parameters ---------- ...
python
def create_notification_channel(self, callback_url, calendar_ids=()): """Create a new channel for receiving push notifications. :param string callback_url: The url that will receive push notifications. Must not be longer than 128 characters and should be HTTPS. :param tuple calendar_ids...
java
protected void closeTargetResource( CompensatingTransactionHolderSupport transactionHolderSupport) { DirContextHolder contextHolder = (DirContextHolder) transactionHolderSupport; DirContext ctx = contextHolder.getCtx(); try { LOG.debug("Closing target context"); ...
python
def _generate(self, size=None): "Generates a new word" corpus_letters = list(self.vectors.keys()) current_letter = random.choice(corpus_letters) if size is None: size = int(random.normalvariate(self.avg, self.std_dev)) letters = [current_letter] for _ in ran...
java
@SuppressWarnings("unchecked") public static List<EntityPlayerMP> getPlayersWatchingChunk(WorldServer world, int x, int z) { if (playersWatchingChunk == null) return new ArrayList<>(); try { PlayerChunkMapEntry entry = world.getPlayerChunkMap().getEntry(x, z); if (entry == null) return Lists.newAr...
java
public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues) { // // Retrieve the LHS value // FieldType field = m_leftValue; Object lhs; if (field == null) { lhs = null; } else { lhs = container.getC...
java
public static boolean isSelfCall(JCTree tree) { Name name = calledMethodName(tree); if (name != null) { Names names = name.table.names; return name==names._this || name==names._super; } else { return false; } }
java
public static ResourceConfiguration deserialize(final File pFile, final String pResource) throws TTIOException { try { final File file = new File(new File(new File(pFile, StorageConfiguration.Paths.Data.getFile().getName()), pResource), Paths.ConfigBinary...
python
def securities(self): """ Returns securities aggregate """ if not self.__securities_aggregate: self.__securities_aggregate = SecuritiesAggregate(self.book) return self.__securities_aggregate
java
public final void setUtlInvLine(final UtlInvLine<RS, PurchaseInvoice, PurchaseInvoiceLine, PurchaseInvoiceTaxLine, PurchaseInvoiceGoodsTaxLine> pUtlInvLine) { this.utlInvLine = pUtlInvLine; }
python
def match_trailer(self, tokens, item): """Matches typedefs and as patterns.""" internal_assert(len(tokens) > 1 and len(tokens) % 2 == 1, "invalid trailer match tokens", tokens) match, trailers = tokens[0], tokens[1:] for i in range(0, len(trailers), 2): op, arg = trailers[i],...
python
def crackOCR(self, image): """ Attempts to crack the given OCR Uses the "darkest pixel" method to find the darkest pixel in the image. Once found it generates a virtual box around the rest of the pet and returns the x and y coordinate of the middle of the virtual box. About 98.7...
python
def neg_loglikelihood(y, mean, scale, shape, skewness): """ Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Poisson distribution scale : float ...
java
public void executePropertyModification(CmsPropertyModification propMod) { CmsClientSitemapEntry entry = getEntryById(propMod.getId()); if (entry != null) { Map<String, CmsClientProperty> props = getPropertiesForId(propMod.getId()); if (props != null) { propMod.u...
java
public static String formatRuntime(long runtime) { long seconds = (runtime / SECONDS) % 60; long minutes = (runtime / MINUTES) % 60; long hours = (runtime / HOURS) % 24; long days = runtime / DAYS; StringBuffer strBuf = new StringBuffer(); if (days > 0) { if...
python
def query(self, coords, mode='random_sample', return_flags=False, pct=None): """ Returns reddening at the requested coordinates. There are several different query modes, which handle the probabilistic nature of the map differently. Args: coords (:obj:`astropy.coordin...
java
public Calendar deserialize(String serString) throws ValueFormatException { final String[] parts = serString.split(CALENDAR_FIELDS_SEPARATOR); if (parts.length == 2) { // try parse serialized string with two formats // 1. Complete ISO 8610 compliant // 2. Complete ISO 86...
python
def merge(self, other): """ We can merge unless the merge results in an empty set -- a contradiction """ other = self.coerce(other) if self.is_equal(other): # pick among dependencies return self elif self.is_contradictory(other): ...
python
def _get_hparams_path(): """Get hyper-parameters file path.""" hparams_path = None if FLAGS.output_dir: hparams_path = os.path.join(FLAGS.output_dir, "hparams.json") else: tf.logging.warning( "--output_dir not specified. Hyper-parameters will be infered from" "--hparams_set and --hparams...
java
@Deprecated public static int decompose(char[] src,int srcStart, int srcLimit, char[] dest,int destStart, int destLimit, boolean compat, int options) { CharBuffer srcBuffer = CharBuffer.wrap(src, srcStart, srcLimit - srcStart); CharsApp...
java
public static String normalize(String val) { if (val == null || val.trim().length() == 0) return null; return val.trim(); }
java
@Override public XGBoostModel createImpl() { XGBoostV3.XGBoostParametersV3 p = this.parameters; XGBoostModel.XGBoostParameters parms = p.createImpl(); return new XGBoostModel(model_id.key(), parms, new XGBoostOutput(null), null, null); }
python
def push(self, undoObj): """ Add ``undoObj`` command to stack and run its ``commit`` method. |Args| * ``undoObj`` (**QtmacsUndoCommand**): the new command object. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an...
python
def s_magic(sfile, anisfile="specimens.txt", dir_path=".", atype="AMS", coord_type="s", sigma=False, samp_con="1", specnum=0, location="unknown", spec="unknown", sitename="unknown", user="", data_model_num=3, name_in_file=False, input_dir_path=""): """ converts .s format data...
java
@Override public Object getObject (String key) { // separate the key into path components, the "local" key value is the first component, so // use that to conduct the search. We are only interested in values that indicate the search // found the requested key String[] path = Key...
python
def describe_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Get an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto...
java
public ResolvableType getComponentType() { if (this == NONE) { return NONE; } if (this.componentType != null) { return this.componentType; } if (this.type instanceof Class) { Class<?> componentType = ((Class<?>) this.type).getComponentType(); ...
python
def moving_average(self, window, method=SIMPLE): '''Calculate a moving average using the specified method and window''' if len(self.points) < window: raise ArithmeticError('Not enough points for moving average') numpy = LazyImport.numpy() if method == TimeSeries.SIMPLE: ...
python
def _groupby_and_merge(by, on, left, right, _merge_pieces, check_duplicates=True): """ groupby & merge; we are always performing a left-by type operation Parameters ---------- by: field to group on: duplicates field left: left frame right: right frame _merge_p...
java
protected void updateIndex(I_CmsSearchIndex index, I_CmsReport report, List<CmsPublishedResource> resourcesToIndex) throws CmsException { if (shouldUpdateAtAll(index)) { try { SEARCH_MANAGER_LOCK.lock(); // copy the stored admin context for the indexing ...
python
def _molfile(stream): """Process ``Molfile``. :param stream: Queue containing lines of text. :type stream: :py:class:`collections.deque` :return: Tuples of data. """ yield MolfileStart() yield HeaderBlock(stream.popleft().strip(), stream.popleft().strip(), stream.popleft().strip()) ...