language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public boolean hasAncestorOfType( Type firstType, Type... additionalTypes ) { return hasAncestorOfType(EnumSet.of(firstType, additionalTypes)); }
java
public static TopicWrapper cloneTopic(final DataProviderFactory providerFactory, final ITopicNode specTopic, final ServerEntitiesWrapper serverEntities) { final TopicProvider topicProvider = providerFactory.getProvider(TopicProvider.class); final TopicSourceURLProvider topicSourceUrlProvider...
python
def from_spacegroup(cls, sg, lattice, species, coords, site_properties=None, coords_are_cartesian=False, tol=1e-5): """ Generate a structure using a spacegroup. Note that only symmetrically distinct species and coords should be provided. All equivalent sites are g...
python
def client_getname(self, encoding=_NOTSET): """Get the current connection name.""" return self.execute(b'CLIENT', b'GETNAME', encoding=encoding)
java
public void parseAndExecuteCommand() { CommandLineParser parser = new DefaultParser(); try { CommandLine parsedOpts = parser.parse(this.options, this.args, true); GlobalOptions globalOptions = createGlobalOptions(parsedOpts); // Fetch the command and fail if there is ambiguity String[] ...
python
def get_source_var_declaration(self, var): """ Return the source mapping where the variable is declared Args: var (str): variable name Returns: (dict): sourceMapping """ return next((x.source_mapping for x in self.variables if x.name == var))
java
static ProxyConnection getProxyConnection(final PoolEntry poolEntry, final Connection connection, final FastList<Statement> openStatements, final ProxyLeakTask leakTask, final long now, final boolean isReadOnly, final boolean isAutoCommit) { // Body is replaced (injected) by JavassistProxyFactory throw n...
python
def amortize(rate, nper, pv, freq="M"): """Construct an amortization schedule for a fixed-rate loan. Rate -> annualized input Example ------- # a 6.75% $200,000 loan, 30-year tenor, payments due monthly # view the 5 final months print(amortize(rate=.0675, nper=30, pv=200000).round...
python
def fire_event(self, evt_name, *args, **kwargs): """触发事件 :params evt_name: 事件名称 :params args: 给事件接受者的参数 :params kwargs: 给事件接受者的参数 """ listeners = self.__get_listeners(evt_name) evt = self.generate_event(evt_name) for listener in listeners: lis...
java
public static <T extends Annotation> List<Method> introspectAnnotationMultiple( final Class<?> klass, final Class<T> annotationType) { final List<Method> result = new ArrayList<Method>(); for (final Method method : klass.getMethods()) { if (method.getAnnotation(annotationType) !=...
java
public static <T> T InThread( T anInterface ) { Actor sender = Actor.sender.get(); if ( sender != null ) return sender.getScheduler().inThread(sender.getActor(),anInterface); else return anInterface; }
python
def _GenClientLibCallback(args, client_func=_GenClientLib): """Generate a client library to file. Args: args: An argparse.Namespace object to extract parameters from client_func: A function that generates client libraries and stores them to files, accepting a path to a discovery doc, a client library...
java
protected Object doGetTransaction() { Object dataSourceTransactionObject = super.doGetTransaction(); Object contextSourceTransactionObject = ldapManagerDelegate .doGetTransaction(); return new ContextSourceAndHibernateTransactionObject( contextSourceTransactionOb...
python
def set_estimate(self, bitrate: int, now_ms: int): """ For testing purposes. """ self.current_bitrate = self._clamp_bitrate(bitrate, bitrate) self.current_bitrate_initialized = True self.last_change_ms = now_ms
python
def classify_wherex(scope_, fromx, wherex): "helper for wherex_to_rowlist. returns [SingleTableCond,...], [CartesianCond,...]" exprs = [] for exp in fromx: if isinstance(exp, sqparse2.JoinX): # todo: probably just add exp.on_stmt as a CartesianCond. don't write this until tests are ready. # todo: ...
java
public void setBackupSelectionsList(java.util.Collection<BackupSelectionsListMember> backupSelectionsList) { if (backupSelectionsList == null) { this.backupSelectionsList = null; return; } this.backupSelectionsList = new java.util.ArrayList<BackupSelectionsListMember>(ba...
java
public static IndexPlanner both( final IndexPlanner planner1, final IndexPlanner planner2 ) { if (planner1 == null) return planner2; if (planner2 == null) return planner1; return new IndexPlanner() { @Override public void applyIndexes...
java
private boolean isCertExpired(X509Certificate cert) { if (cert != null && cert.getNotAfter().before(new Date())) { return true; } return false; }
python
def scope_lookup(self, node, name, offset=0): """Lookup where the given names is assigned. :param node: The node to look for assignments up to. Any assignments after the given node are ignored. :type node: NodeNG :param name: The name to find assignments for. :type ...
python
def _get_shortcut_string(shortcut): """Return a string representation of a shortcut.""" if shortcut is None: return '' if isinstance(shortcut, (tuple, list)): return ', '.join([_get_shortcut_string(s) for s in shortcut]) if isinstance(shortcut, string_types): if hasattr(QKeySeque...
python
def _get_super_entities_by_ctype(model_objs_by_ctype, model_ids_to_sync, sync_all): """ Given model objects organized by content type and a dictionary of all model IDs that need to be synced, organize all super entity relationships that need to be synced. Ensure that the model_ids_to_sync dict is updat...
python
def users(self, team, params={}, **options): """Returns the compact records for all users that are members of the team. Parameters ---------- team : {Id} Globally unique identifier for the team. [params] : {Object} Parameters for the request """ path = "/teams/%...
python
def _make_hlog_numeric(b, r, d): """ Return a function that numerically computes the hlog transformation for given parameter values. """ hlog_obj = lambda y, x, b, r, d: hlog_inv(y, b, r, d) - x find_inv = vectorize(lambda x: brentq(hlog_obj, -2 * r, 2 * r, ...
python
def _data_execute(self, data, program, executor): """Execute the Data object. The activities carried out here include target directory preparation, executor copying, setting serialization and actual execution of the object. :param data: The :class:`~resolwe.flow.models.Data` ob...
java
protected void buildModulePackagesIndexFile(String title, boolean includeScript, ModuleElement mdle) throws DocFileIOException { String windowOverview = configuration.getText(title); Content body = getBody(includeScript, getWindowTitle(windowOverview)); addNavigationBarHeader(body); ...
java
private RootElementInfo createRootElementInfo(org.jsoup.nodes.Element root, String subclass) { List<Attribute> attributes = root.attributes().asList().stream() .filter(attribute -> !attribute.getKey().equals("data-element")) .collect(Collectors.toList()); ExpressionParse...
java
public void initWorklist(boolean addAll) { if (addAll) { Block last = null; for (Block b = blocklistHead; b != null; b = b.nextBlock) { b.nextInWorklist = b.nextBlock; last = b; } worklistHead = blocklistHead; worklistTa...
python
def webui_data_stores_user_profile_saved_query_value(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") webui = ET.SubElement(config, "webui", xmlns="http://tail-f.com/ns/webui") data_stores = ET.SubElement(webui, "data-stores") user_profile = ET.Su...
python
def network_lpf_contingency(network, snapshots=None, branch_outages=None): """ Computes linear power flow for a selection of branch outages. Parameters ---------- snapshots : list-like|single snapshot A subset or an elements of network.snapshots on which to run the power flow, defau...
python
def remoteIndexer2to3(oldIndexer): """ The documentType keyword was added to all indexable items. Indexes need to be regenerated for this to take effect. Also, PyLucene no longer stores the text of messages it indexes, so deleting and re-creating the indexes will make them much smaller. """ ...
java
public CapsuleLauncher setProperties(Properties properties) { this.properties = properties != null ? properties : new Properties(System.getProperties()); set(null, getCapsuleField("PROPERTIES"), this.properties); return this; }
java
protected int isBetter2D(Box a, Box b) { int compare = Long.compare(a.getVolume(), b.getVolume()); if(compare != 0) { return compare; } return Long.compare(b.getFootprint(), a.getFootprint()); // i.e. smaller i better }
java
public <Value> PushMeasure<Value> wrapMeasure( final PushMeasure<Value> wrapped) { if (wrapped == null) { throw new IllegalArgumentException("No measure provided"); } else { @SuppressWarnings("unchecked") PushMeasure<Value> wrapper = (PushMeasure<Value>) measureCache .get(wrapped); if (wrapper ...
python
def loop_forever(self, timeout=1.0, max_packets=1, retry_first_connection=False): """This function call loop() for you in an infinite blocking loop. It is useful for the case where you only want to run the MQTT client loop in your program. loop_forever() will handle reconnecting for you...
java
public void implicitDefinitions(SClassDefinition d, Environment publicClasses) { if (d instanceof ASystemClassDefinition) { af.createPDefinitionAssistant().implicitDefinitions(d, publicClasses); // ASystemClassDefinitionAssistantTC.implicitDefinitions((ASystemClassDefinition) d, ); } else { implici...
java
public CacheSubnetGroup withSubnets(Subnet... subnets) { if (this.subnets == null) { setSubnets(new com.amazonaws.internal.SdkInternalList<Subnet>(subnets.length)); } for (Subnet ele : subnets) { this.subnets.add(ele); } return this; }
java
@Override public CPDefinitionOptionValueRel[] findByUuid_PrevAndNext( long CPDefinitionOptionValueRelId, String uuid, OrderByComparator<CPDefinitionOptionValueRel> orderByComparator) throws NoSuchCPDefinitionOptionValueRelException { CPDefinitionOptionValueRel cpDefinitionOptionValueRel = findByPrimaryKey(CPDe...
python
def push_note(device=None, title=None, body=None): ''' Pushing a text note. :param device: Pushbullet target device :param title: Note title :param body: Note body :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt "...
java
public static Point from(double lon, double lat, double alt) { return new Point(new SinglePosition(lon, lat, alt)); }
java
public int span(CharSequence s, int start, SpanCondition spanCondition) { if (spanCondition == SpanCondition.NOT_CONTAINED) { return spanNot(s, start, null); } int spanLimit = spanSet.span(s, start, SpanCondition.CONTAINED); if (spanLimit == s.length()) { return s...
java
public PathBuilder cubicTo(Point2d cp1, Point2d cp2, Point2d ep) { add(new CubicTo(cp1, cp2, ep)); return this; }
python
def solve( solver, mzn, *dzn_files, data=None, include=None, stdlib_dir=None, globals_dir=None, allow_multiple_assignments=False, output_mode='item', timeout=None, two_pass=None, pre_passes=None, output_objective=False, non_unique=False, all_solutions=False, num_solutions=None, free_search=False, pa...
java
private void propagateToSharedSketch() { //noinspection StatementWithEmptyBody while (localPropagationInProgress.get()) { } //busy wait until previous propagation completed final CompactSketch compactSketch = compact(propagateOrderedCompact, null); localPropagationInProgress.set(true); shared.p...
python
def register(self, model, include_fields=[], exclude_fields=[]): """ Register a model with actionslog. Actionslog will then track mutations on this model's instances. :param model: The model to register. :type model: Model :param include_fields: The fields to include. Implicitly...
python
def _listen_for_dweets_from_response(response): """Yields dweets as received from dweet.io's streaming API """ streambuffer = '' for byte in response.iter_content(): if byte: streambuffer += byte.decode('ascii') try: dweet = json.loads(streambuffer.splitli...
java
public static CommerceOrderItem[] findByC_I_PrevAndNext( long commerceOrderItemId, long commerceOrderId, long CPInstanceId, OrderByComparator<CommerceOrderItem> orderByComparator) throws com.liferay.commerce.exception.NoSuchOrderItemException { return getPersistence() .findByC_I_PrevAndNext(commerceOrder...
python
def set_pending_symbol(self, pending_symbol=None): """Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``. If the input is None, an empty :class:`CodePointArray` is used. """ if pending_symbol is None: pending_symbol = Cod...
python
def print_upper_triangular_matrix_as_complete(matrix): """Prints a CVRP data dict upper triangular matrix as a normal matrix Doesn't print headers. Arguments --------- matrix : dict Description """ for i in sorted(matrix.keys()): for j in sorted(matrix.keys...
java
public static CPDefinitionGroupedEntry fetchByUUID_G(String uuid, long groupId, boolean retrieveFromCache) { return getPersistence().fetchByUUID_G(uuid, groupId, retrieveFromCache); }
python
def _set_queue_size(self, v, load=False): """ Setter method for queue_size, mapped from YANG variable /interface/ethernet/qos/rx_queue/multicast/queue_size (list) If this variable is read-only (config: false) in the source YANG file, then _set_queue_size is considered as a private method. Backends l...
java
public void marshall(PutConfigurationSetDeliveryOptionsRequest putConfigurationSetDeliveryOptionsRequest, ProtocolMarshaller protocolMarshaller) { if (putConfigurationSetDeliveryOptionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } tr...
java
public void updateProfile(ProfileFieldValues values) { getResourceFactory().getApiResource("/user/profile/") .entity(values, MediaType.APPLICATION_JSON_TYPE).put(); }
java
public SearchResponse searchWithTargetCount( SearchRequestBuilder searchRequestBuilder, AggregationBuilder[] aggregationBuilders) { return searchWithTargetCount(getSearchRequestBuilder( getSearchRequestBuilderWithCount(searchRequestBuilder), aggregationBui...
python
def add_link(self, rel, value, href=None): """ Add a Link metadata element to the IOC. :param rel: Type of the link. :param value: Value of the link text. :param href: A href value assigned to the link. :return: True """ links_node = self.metadata.find('l...
python
def pattern_for_view(self, view, action): """ Returns the URL pattern for the passed in action. """ # if this view knows how to define a URL pattern, call that if getattr(view, 'derive_url_pattern', None): return view.derive_url_pattern(self.path, action) # o...
java
public static ServerSocketPredicate tag(String... tags) { return socket -> socket.tags().containsAll(Arrays.asList(tags)); }
java
public static List<CommerceOrder> findByG_U_O(long groupId, long userId, int orderStatus) { return getPersistence().findByG_U_O(groupId, userId, orderStatus); }
python
def dict_stack(dict_list, key_prefix=''): r""" stacks values from two dicts into a new dict where the values are list of the input values. the keys are the same. DEPRICATE in favor of dict_stack2 Args: dict_list (list): list of dicts with similar keys Returns: dict dict_stacke...
python
def get_packages(self, feed_id, protocol_type=None, package_name_query=None, normalized_package_name=None, include_urls=None, include_all_versions=None, is_listed=None, get_top_package_versions=None, is_release=None, include_description=None, top=None, skip=None, include_deleted=None, is_cached=None, direct_upstream_id...
python
def dumpkey(key): """ Helper to convert result of `getch` (string) or `getchars` (list) to hex string. """ def hex3fy(key): """Helper to convert string into hex string (Python 3 compatible)""" from binascii import hexlify # Python 3 strings are no longer binary, encode them f...
python
def add_implem(self, transition, attribute, function, **kwargs): """Add an implementation. Args: transition (Transition): the transition for which the implementation is added attribute (str): the name of the attribute where the implementation will...
java
public static Map makeMap(Mapper mapper, Iterator i) { return makeMap(mapper, i, false); }
java
public void setSparkLineColor(final LcdColor LCD_COLOR) { this.lineColor = LCD_COLOR.TEXT_COLOR; this.sparkLineColor = LCD_COLOR; recreateImages = true; init(INNER_BOUNDS.width, INNER_BOUNDS.height); repaint(INNER_BOUNDS); }
python
def _doCleanup(self): """ Perform any periodic database cleanup tasks. @returns: Deferred """ # pass on this if we're not configured yet if not self.configured_url: return d = self.changes.pruneChanges(self.master.config.changeHorizon) d.addE...
python
def diskwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None): """Helper function for diskwarp of multiple input GDAL Datasets """ return warp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, warptype=diskwarp, outdir=outdir,...
python
def check_validation(self, cert): """ Checks to see if a certificate has been validated, and if so, returns the ValidationPath used to validate it. :param cert: An asn1crypto.x509.Certificate object :return: None if not validated, or a certvalidator.path...
java
@Override public double similarity(VariantCall call1, VariantCall call2) { int minNumberOfGenotypes = Math.min(call1.getGenotypeCount(), call2.getGenotypeCount()); int numberOfSharedAlleles = 0; for (int i = 0; i < minNumberOfGenotypes; ++i) { if (call1.getGenotype(i) == call2.getGenotype(i)) { ...
java
public PlateFactor getFactorByName(String name) { int index = factorNames.indexOf(name); if (index == -1) { return null; } else { return plateFactors.get(index); } }
java
public static int parseBlockComment(final char[] query, int offset) { if (offset + 1 < query.length && query[offset + 1] == '*') { // /* /* */ */ nest, according to SQL spec int level = 1; for (offset += 2; offset < query.length; ++offset) { switch (query[offset - 1]) { case '*':...
java
private Optional<String[]> parseCredentials(String url) { if (!Strings.isNullOrEmpty(url)) { int p; if ((p = url.indexOf("://")) != -1) { url = url.substring(p + 3); } if ((p = url.indexOf('@')) != -1) { String[] result = new String...
java
public static Element createElement(String tagName, String id) { return IMPL.createElement(tagName, id); }
java
@RequestMapping(value = "/create-payment", method = RequestMethod.POST) public @ResponseBody Map<String, String> createPayment(@RequestParam("performCheckout") Boolean performCheckout) throws PaymentException { Map<String, String> response = new HashMap<>(); Payment createdPayment = paymentService.c...
python
def j1_2(a=1): r"""Hankel transform pair J1_2 ([Ande75]_).""" def lhs(x): return np.exp(-a*x) def rhs(b): return (np.sqrt(b**2 + a**2) - a)/(b*np.sqrt(b**2 + a**2)) return Ghosh('j1', lhs, rhs)
java
private ResultItem pollResultItem(long timeout, boolean idle) { ResultItem result = getResult(); if (result != null) { result.remainingIdleTimeout = timeout; } if (result == null && timeout > 0) { long start = System.currentTimeMillis(); internalWait(timeout); long end = System....
python
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=FLAGS): """Ensures that only one flag among flag_names is set. Args: flag_names: [str], a list of the flag names to be checked. required: Boolean, if set, exactly one of the flags must be set. ...
java
public synchronized void setVal(int offset, Constant val) { byte[] byteval = val.asBytes(); // Append the size of value if it is not fixed size if (!val.getType().isFixedSize()) { // check the field capacity and value size if (offset + ByteHelper.INT_SIZE + byteval.length > BLOCK_SIZE) throw new...
java
public void marshall(InstanceGroup instanceGroup, ProtocolMarshaller protocolMarshaller) { if (instanceGroup == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(instanceGroup.getId(), ID_BINDING); ...
python
def html(self): """ str: HTML representation of the page Note: Not settable Warning: This can be slow for very large pages """ if self._html is False: self._html = None query_params = { "prop": "revisions", ...
python
def update_many(cls, filter, update, upsert=False): """ Updates all documents that pass the filter with the update value Will upsert a new document if upsert=True and no document is filtered """ return cls.collection.update_many(filter, update, upsert).raw_result
java
public void api_credential_credentialId_DELETE(Long credentialId) throws IOException { String qPath = "/me/api/credential/{credentialId}"; StringBuilder sb = path(qPath, credentialId); exec(qPath, "DELETE", sb.toString(), null); }
python
def save_controls(self, parameterstep: 'timetools.PeriodConstrArg' = None, simulationstep: 'timetools.PeriodConstrArg' = None, auxfiler: 'Optional[auxfiletools.Auxfiler]' = None): """Save the control parameters of the |Model| object handled by each |Element| o...
python
def save_report(self, file_path): """Write coveralls report to file.""" try: report = self.create_report() except coverage.CoverageException as e: log.error('Failure to gather coverage:', exc_info=e) else: with open(file_path, 'w') as report_file: ...
java
public static boolean isTypeOf(final Class<?> clazz, TypeMirror type) { checkNotNull(clazz); return type.accept(new IsTypeOf(clazz), null); }
java
public static Vector zero(int length) { return length > 1000 ? SparseVector.zero(length) : DenseVector.zero(length); }
python
def add_row(self, label='', item=''): """ Add a row to the grid """ self.AppendRows(1) last_row = self.GetNumberRows() - 1 self.SetCellValue(last_row, 0, str(label)) self.row_labels.append(label) self.row_items.append(item)
python
def db_chainstate_get_block(cls, cur, block_height): """ Get the list of virtualchain transactions accepted at a given block. Returns the list of rows, where each row is a dict. """ query = 'SELECT * FROM chainstate WHERE block_id = ? ORDER BY vtxindex;' args = (block_hei...
java
public final static int readMdLinkId(final StringBuilder out, final String in, final int start) { int pos = start; int counter = 1; while (pos < in.length()) { final char ch = in.charAt(pos); boolean endReached = false; switch (ch) { ...
python
def handle_string(self, strreq): ''' Handle a string representing a jsonrpc-request strreq - jsonrpc-request as a string returns jsonrpc-response as a string ''' #convert to jsonrpc-dict req = None try: req = json.loads(strreq) excep...
python
def from_transform(cls, matrix): r""" :param matrix: 4x4 3d affine transform matrix :type matrix: :class:`FreeCAD.Matrix` :return: a unit, zero offset coordinate system transformed by the given matrix :rtype: :class:`CoordSystem` Individual rotation & translation matrici...
python
def get_transformed_feature_info(features, schema): """Returns information about the transformed features. Returns: Dict in the from {transformed_feature_name: {dtype: tf type, size: int or None}}. If the size is None, then the tensor is a sparse tensor. """ info = collections.defaultdict(dict) ...
python
def _call_command(self, name, *args, **kwargs): """ If a command is called for the main field, without dynamic part, an ImplementationError is raised: commands can only be applied on dynamic versions. On dynamic versions, if the command is a modifier, we add the version in ...
python
def inc_nbrs(self, node): """ List of nodes connected by incoming edges """ l = map(self.head, self.inc_edges(node)) #l.sort() return l
python
def getAsKmlAnimation(self, session, channelInputFile, path=None, documentName=None, styles={}): """ Generate a KML visualization of the the link node dataset file. Link node dataset files are time stamped link node value datasets. This will yield a value for each stream node at each ti...
java
public Method getEndpointMethod() throws ResourceAdapterInternalException { final String methodName = "getEndpointMethod"; if (TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } if (ON_MESSAGE_METHOD == null) { try { ON_MESSAGE_M...
python
def do_authorization(self, transactionid, amt): """Shortcut for the DoAuthorization method. Use the TRANSACTIONID from DoExpressCheckoutPayment for the ``transactionid``. The latest version of the API does not support the creation of an Order from `DoDirectPayment`. The `amt` s...
java
public static Environment merge(Environment env1, Environment env2) { final Environment mergedEnv = new Environment(); // merge tables final Map<String, TableEntry> tables = new LinkedHashMap<>(env1.getTables()); tables.putAll(env2.getTables()); mergedEnv.tables = tables; // merge functions final Map<St...
python
def nice_number(number, thousands_separator=',', max_ndigits_after_dot=None): """Return nicely printed number NUMBER in language LN. Return nicely printed number NUMBER in language LN using given THOUSANDS_SEPARATOR character. If max_ndigits_after_dot is specified and the number is float, the numbe...
python
def tx_mean(tasmax, freq='YS'): r"""Mean max temperature The mean of daily maximum temperature. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Mean of...
java
protected CLVar var(final int lit) { final int idx = Math.abs(lit); assert 0 < idx && idx < this.vars.size(); return this.vars.get(idx); }
java
private BigInteger getLower(int n) { if (isZero()) { return BigInteger.ZERO; } else if (intLen < n) { return toBigInteger(1); } else { // strip zeros int len = n; while (len > 0 && value[offset+intLen-len] == 0) len--; ...