language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Member addMember(Object groupIdOrPath, Integer userId, AccessLevel accessLevel, Date expiresAt) throws GitLabApiException { return (addMember(groupIdOrPath, userId, accessLevel.toValue(), expiresAt)); }
java
public static DroolsPackage init() { if (isInited) return (DroolsPackage)EPackage.Registry.INSTANCE.getEPackage(DroolsPackage.eNS_URI); // Obtain or create and register package DroolsPackageImpl theDroolsPackage = (DroolsPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof DroolsPackageImpl ? EPackage...
java
public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { try { Rectangle r = c.modelToView(c.getCaretPosition()); g.setColor( color ); g.fillRect(0, r.y, c.getWidth(), r.height); if (lastView == null) lastView = r; } catch(BadLocationException ble) {System.out.println(bl...
python
def parse_args(arglist=None): """Parse cmd line arguments. Update :attr:`stagpy.conf` accordingly. Args: arglist (list of str): the list of cmd line arguments. If set to None, the arguments are taken from :attr:`sys.argv`. Returns: function: the function implementing the s...
python
def nt_event_log_handler(name, logname, appname, dllname=None, logtype="Application"): """ A Bark logging handler logging output to the NT Event Log. Similar to logging.handlers.NTEventLogHandler. """ return wrap_log_handler(logging.handlers.NTEventLogHandler( appn...
python
def set_param(self, number, value): """Sets an internal Server object parameter. """ logger.debug("setting param number %s to %s" % (number, value)) type_ = param_types[number] return self.library.Cli_SetParam(self.pointer, number, byref(t...
python
def display_animation(anim, **kwargs): """Display the animation with an IPython HTML object""" from IPython.display import HTML return HTML(anim_to_html(anim, **kwargs))
python
def memory_zones(self): """Gets all memory zones supported by the current target. Some targets support multiple memory zones. This function provides the ability to get a list of all the memory zones to facilate using the memory zone routing functions. Args: self (JLi...
java
public final ListScanRunsPagedResponse listScanRuns(ScanConfigName parent) { ListScanRunsRequest request = ListScanRunsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listScanRuns(request); }
java
@Override public Object evaluate(Object exp, Map<String, ? extends Object> contextMap, LaContainer container, Class<?> resultType) { return viaVariableResolvedEvaluate((String) exp, contextMap, container, resultType); }
python
def execute(opts, data, func, args, kwargs): ''' Allow for the calling of execution modules via sudo. This module is invoked by the minion if the ``sudo_user`` minion config is present. Example minion config: .. code-block:: yaml sudo_user: saltdev Once this setting is made, any...
java
static BitReader newBitReader(BitStore store, final int finalPos, final int initialPos) { if (store == null) throw new IllegalArgumentException("null store"); if (finalPos < 0) throw new IllegalArgumentException("negative finalPos"); if (initialPos > store.size()) throw new IllegalArgumentException("initialPos to...
java
public void marshall(PutAttributesRequest putAttributesRequest, ProtocolMarshaller protocolMarshaller) { if (putAttributesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(putAttributesReques...
java
public ClassLoader resolve(MavenCoordinate mavenCoordinate) throws MojoFailureException, MojoExecutionException { ClassLoader classLoader = classLoaders.get(mavenCoordinate); if (classLoader == null) { classLoader = doResolve(mavenCoordinate); classLoaders.put(mavenCoordinate, cl...
python
def breaks_from_binwidth(x_range, binwidth=None, center=None, boundary=None): """ Calculate breaks given binwidth Parameters ---------- x_range : array_like Range over with to calculate the breaks. Must be of size 2. binwidth : float Separation b...
java
public final Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> limit8() { return this; }
python
def hash_and_serialize_chunk(chunk_pii_data, # type: Sequence[Sequence[str]] keys, # type: Sequence[Sequence[bytes]] schema # type: Schema ): # type: (...) -> Tuple[List[str], Sequence[int]] """ Generate Bloom filters ...
python
def _build_session(self, auth_class, *args, **kwargs): """Internal helper for creating a requests `session` with the correct authentication handling. """ session = requests.session() session.auth = auth_class(*args, **kwargs) session.headers.update({'CB-VERSION': self.API...
java
public static Collection grep(Object self, Object filter) { Collection answer = createSimilarOrDefaultCollection(self); BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase"); for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { Object obje...
java
@Override public void backward() { VarTensor tmp = new VarTensor(yAdj); // copy tmp.elemMultiply(y); tmp = tmp.copyAndConvertAlgebra(RealAlgebra.getInstance()); VarTensor xAdj = modInX.getOutputAdj(); xAdj.elemAdd(tmp); }
python
def to_latex(self): """ Returns a LaTeX representation of an attribute-value matrix """ latex = r"[{} " for attribute, value in self: if attribute in ['speaker_model', 'is_in_commonground']: continue value_l = value.to_latex() if value_l == "": continue ...
python
def p_intermfluent_def(self, p): '''intermfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI | IDENT COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI''' ...
python
def setup_logging( handler, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, log_level=logging.INFO ): """Attach a logging handler to the Python root logger Excludes loggers that this library itself uses to avoid infinite recursion. :type handler: :class:`logging.handler` :param handler: the handler...
java
public static INDArray im2col(INDArray img, int kh, int kw, int sy, int sx, int ph, int pw, int pval, boolean coverAll) { //number of images long n = img.size(0); //number of channels (depth) long c = img.size(1); //image height long h = img.size(2); ...
java
@Override final public LocalTransaction getLocalTransaction() throws ResourceException { if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, "getLocalTransaction"); } if (_coreConnection == null) { thro...
java
public void marshall(ListViolationEventsRequest listViolationEventsRequest, ProtocolMarshaller protocolMarshaller) { if (listViolationEventsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(l...
python
def get_random(self): """Get a kitten, either from the db, or a new one. """ num_kittens = self.count() new_cutoff = (num_kittens / (num_kittens + constants.KITTEN_FRESHNESS)) if random.random() < new_cutoff: return self._rand_inst() else: return s...
python
def generate(self): """Generate a new string and return it.""" key = self._propose_new_key() while self.key_exists(key): _logger.warning('Previous candidate was used.' ' Regenerating another...') key = self._propose_new_key() return key
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLDataPropertyImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
public static void fill( DMatrix6 a , double v ) { a.a1 = v; a.a2 = v; a.a3 = v; a.a4 = v; a.a5 = v; a.a6 = v; }
java
public boolean removeDisconnectedEventListener(PeerDisconnectedEventListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peerDisconnectedEventListeners); for (Peer peer : getConnectedPeers()) peer.removeDisconnectedEventListener(listener); for (Peer pee...
java
public static Writer leftShift(OutputStream self, Object value) throws IOException { OutputStreamWriter writer = new FlushingStreamWriter(self); leftShift(writer, value); return writer; }
java
public SofaResponseCallback getMethodOnreturn(String methodName) { return (SofaResponseCallback) getMethodConfigValue(methodName, RpcConstants.CONFIG_KEY_ONRETURN, getOnReturn()); }
java
private void setActiveCenters(IAtomContainer reactant) throws CDKException { if (AtomContainerManipulator.getTotalCharge(reactant) > 0) return; Iterator<IAtom> atoms = reactant.atoms().iterator(); while (atoms.hasNext()) { IAtom atomi = atoms.next(); // Atom pos 1 if ((a...
java
public String read(String path, Watcher watcher, Stat stat) throws InterruptedException, KeeperException { byte[] data = zk.getData(path, watcher, stat); return new String(data, CHARSET); }
java
public static boolean lineIntersects(Coordinate c1, Coordinate c2, Coordinate c3, Coordinate c4) { LineSegment ls1 = new LineSegment(c1, c2); LineSegment ls2 = new LineSegment(c3, c4); return ls1.intersects(ls2); }
python
def _float_values(self, shape): """ Return uniformly-distributed floats between -0.0 and 100.0. """ return self.state.uniform(low=0.0, high=100.0, size=shape)
java
protected SingleFilterAdapter<?> getAdapterForFilterOrThrow(Filter filter) { if (adapterMap.containsKey(filter.getClass())) { return adapterMap.get(filter.getClass()); } else { throw new UnsupportedFilterException( ImmutableList.of(FilterSupportStatus.newUnknownFilterType(filter))); } ...
python
def createResource(self): """ When invoked by L{PrefixURLMixin}, return a L{websharing.SharingIndex} for my application. """ pp = ixmantissa.IPublicPage(self.application, None) if pp is not None: warn( "Use the sharing system to provide public page...
java
private static void resolveTypeQualifierDefaults(AnnotationValue value, ElementType defaultFor, LinkedList<AnnotationValue> result) { try { XClass c = Global.getAnalysisCache().getClassAnalysis(XClass.class, value.getAnnotationClass()); AnnotationValue defaultAnnotation = c....
python
def array_subscripts(expr): """Given a subscript expression expr (i.e., an expression that denotes the set of elements of some array that are to be accessed), array_subscripts() returns a list of the elements denoted by expr.""" if isinstance(expr, Array): return all_subs(expr._bounds) ...
python
def mousePressEvent(self, event): """ Handle file link clicks. """ super(OutputWindow, self).mousePressEvent(event) if self._link_match: path = self._link_match.group('url') line = self._link_match.group('line') if line is not None: ...
python
def get_flags_for_objects(cls, objects_list, user=None, status=None): """Returns a dictionary with flag objects associated with the given model objects. The dictionary is indexed by objects IDs. Each dict entry contains a list of associated flag objects. :param list, QuerySet objects_li...
java
public void setHosts(final List<String> hosts) { this.hosts.clear(); for (String host: hosts) { this.hosts.add(RegexpUtil.compilePattern(host)); } }
java
public boolean estimate(List<Homography2D_F64> viewsI_to_view0 , CameraPinhole calibration ) { singular = false; int N = viewsI_to_view0.size(); ensureDeterminantOfOne(viewsI_to_view0); A.reshape(N*6,6); for (int i = 0; i < N; i++) { add(i,viewsI_to_view0.get(i),A); } // Compute the SVD for its nul...
java
public DescribeListenersRequest withListenerArns(String... listenerArns) { if (this.listenerArns == null) { setListenerArns(new java.util.ArrayList<String>(listenerArns.length)); } for (String ele : listenerArns) { this.listenerArns.add(ele); } return this...
java
public static PickupCollection all(Map<String, Object> params) throws EasyPostException { return all(params, null); }
python
def _get_remote_import_paths(self, pkg, gopath=None): """Returns the remote import paths declared by the given remote Go `pkg`. NB: This only includes production code imports, no test code imports. """ import_listing = self.import_oracle.list_imports(pkg, gopath=gopath) return [imp for imp in impor...
java
public @NotNull List<Resource> getResources() { return getResources((Predicate<Resource>)null, (Resource)null); }
java
public void redo() { if (isListChange()) { LOGGER.trace("Redoing list change: " + newList.get().toString()); setting.valueProperty().setValue(newList.get()); } else { setting.valueProperty().setValue(newValue.get()); } }
python
def create_parser(name, description=None): """Create an argument parser with the given ``name`` and ``description``. The name is used to make ``cnx-archive-<name>`` program name. This creates and returns a parser with the ``config_uri`` argument declared. """ prog = _gen_prog_name(name) par...
python
def balance(self, date=None): """ returns the account balance as of 'date' (datetime stamp) or now(). """ qs = self._entries() if date: qs = qs.filter(transaction__t_stamp__lt=date) r = qs.aggregate(b=Sum('amount')) b = r['b'] flip = self._DEBIT_IN_DB() ...
python
def _read_notebook(self, os_path, as_version=4): """Read a notebook from an os path.""" with self.open(os_path, 'r', encoding='utf-8') as f: try: # NEW file_ext = _file_extension(os_path) if file_ext == '.ipynb': return nbf...
python
def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name ...
java
public CompoundCurve toCompoundCurveFromList(List<List<LatLng>> polylineList) { return toCompoundCurveFromList(polylineList, false, false); }
python
def dict_print(self, output_file="dict.csv"): """ Print mapping from tokens to numeric indices. """ with codecs.open(output_file, "w", encoding='utf-8') as f: for (v, k) in self.token_key.items(): f.write("%s,%d\n" % (v, k))
java
public void serviceName_senders_sender_DELETE(String serviceName, String sender) throws IOException { String qPath = "/sms/{serviceName}/senders/{sender}"; StringBuilder sb = path(qPath, serviceName, sender); exec(qPath, "DELETE", sb.toString(), null); }
python
def _branch_name(cls, version): """Defines a mapping between versions and branches. In particular, `-dev` suffixed releases always live on master. Any other (modern) release lives in a branch. """ suffix = version.public[len(version.base_version):] components = version.base_version.split('.') +...
python
def extract(connection, filename, table_names = None, verbose = False, xsl_file = None): """ Convert the database at the given connection to a tabular LIGO Light-Weight XML document. The XML document is written to the file named filename. If table_names is not None, it should be a sequence of strings and only th...
java
public Observable<ServiceResponse<EntityExtractor>> getEntityWithServiceResponseAsync(UUID appId, String versionId, UUID entityId) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (app...
java
public static void histogram( GrayS64 input , long minValue , int histogram[] ) { if( BoofConcurrency.USE_CONCURRENT ) { ImplImageStatistics_MT.histogram(input,minValue,histogram); } else { ImplImageStatistics.histogram(input,minValue,histogram); } }
java
public void addAnimation(Element... elements) { if (elements == null || elements.length == 0) { throw new IllegalArgumentException("One or more elements must be specified."); } Set<String> elementIdsInPreviousAnimationSteps = new HashSet<>(); Set<Element> elementsInThisAnima...
java
@Override public Collection<MonetaryAmountFormat> getAmountFormats(AmountFormatQuery amountFormatQuery) { Objects.requireNonNull(amountFormatQuery, "AmountFormatContext required"); if (!amountFormatQuery.getProviderNames().isEmpty() && !amountFormatQuery.getProviderNames().contains(g...
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Link createLink(Data data) { return Link.fromSpanContext( SpanContext.create( TraceId.fromBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}), SpanId.fromBytes(new byte...
java
public static String formatWaypointNames(String[] waypointNames) { for (int i = 0; i < waypointNames.length; i++) { if (waypointNames[i] == null) { waypointNames[i] = ""; } } return TextUtils.join(";", waypointNames); }
python
def format_field(self, field): """ Format a single Dynamo value """ if field is None: return "NULL" elif isinstance(field, TypeError): return "TypeError" elif isinstance(field, Decimal): if field % 1 == 0: return str(int(field)) ...
java
private static long dateTimeDifference(final Temporal d1, final Temporal d2) { return ChronoUnit.SECONDS.between(d1, d2); }
java
public static double distance(SparseArray x, SparseArray y) { return Math.sqrt(squaredDistance(x, y)); }
java
public void handlerAppears( IMonitoringHandler handler ) { if( handler != null ) { this.logger.info( "Monitoring handler '" + handler.getName() + "' is now available." ); this.handlers.add( handler ); listHandlers( this.handlers, this.logger ); } }
python
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if sys.ver...
java
public SearchCriterion getSearchCriterion() { Object operator = operatorSelect.getValue(); Object value = valueItem.getValue(); if (selectedAttribute != null && operator != null) { String operatorString = getOperatorCodeFromLabel(operator.toString()); String valueString = ""; String nameString = selecte...
python
def hash_password(password, salt): """ Securely hash a password using a provided salt :param password: :param salt: :return: Hex encoded SHA512 hash of provided password """ password = str(password).encode('utf-8') salt = str(salt).encode('utf-8') return hashlib.sha512(password + sal...
python
def _host_notification(self, context, method, payload, host): """Notify the cfg agent that is handling the hosting device.""" LOG.debug('Notify Cisco cfg agent at %(host)s the message ' '%(method)s', {'host': host, 'method': method}) cctxt = self.client.prepare(server=host) ...
python
def article(self): """ | Comment: Id of the associated article, if present """ if self.api and self.article_id: return self.api._get_article(self.article_id)
java
@Override public void addReactant(IAtomContainer reactant, Double coefficient) { logger.debug("Adding reactant with coefficient: ", reactant, "" + coefficient); super.addReactant(reactant, coefficient); }
java
public static vpnglobal_authenticationnegotiatepolicy_binding[] get_filtered(nitro_service service, String filter) throws Exception{ vpnglobal_authenticationnegotiatepolicy_binding obj = new vpnglobal_authenticationnegotiatepolicy_binding(); options option = new options(); option.set_filter(filter); vpnglobal_a...
java
public MoneyAmountStyle withGroupingStyle(GroupingStyle groupingStyle) { MoneyFormatter.checkNotNull(groupingStyle, "groupingStyle"); if (this.groupingStyle == groupingStyle) { return this; } return new MoneyAmountStyle( zeroCharacter, p...
python
def hot(self, limit=None): """GETs hot links from this subreddit. Calls :meth:`narwal.Reddit.hot`. :param limit: max number of links to return """ return self._reddit.hot(self.display_name, limit=limit)
java
public Conversation createConversation(String content) { Conversation conversation = getInstance().create().conversation(this, content); return conversation; }
python
def save_expectations_config( self, filepath=None, discard_failed_expectations=True, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, suppress_warnings=False ): """Writes ``_expectation_confi...
java
public Location suffix( Location other ) { if( isSameStrand( other )) { if( other.mEnd <= mEnd ) { return new Location( (other.mEnd > mStart)? other.mEnd: mStart, mEnd ); } else { //other is out of bounds -- no suffix throw new IndexOutOfBoundsException( "Specified location not within th...
java
public static LatLong fromString(String latLonString) { String[] split = latLonString.split("[,;:\\s]"); if (split.length != 2) throw new IllegalArgumentException("cannot read coordinate, not a valid format"); double latitude = Double.parseDouble(split[0]); double longitude =...
java
public MessageLogModel getMessageLog(Object objTrxID) { MessageLogModel recMessageLog = (MessageLogModel)this.getRecord(MessageLogModel.MESSAGE_LOG_FILE); if (recMessageLog == null) recMessageLog = (MessageLogModel)Record.makeRecordFromClassName(MessageLogModel.THICK_CLASS, this); ...
python
def add_header(self, header): """Add a custom HTTP header to the client's request headers""" if type(header) is dict: self._headers.update(header) else: raise ValueError( "Dictionary expected, got '%s' instead" % type(header) )
python
def Row(self): """ The class for a row in this list. """ if not hasattr(self, '_row_class'): attrs = {'fields': self.fields, 'list': self, 'opener': self.opener} for field in self.fields.values(): attrs[field.name] = field.descriptor se...
python
def _parse_object_header(self, header_line): """ :param header_line: <hex_sha> type_string size_as_int :return: (hex_sha, type_string, size_as_int) :raise ValueError: if the header contains indication for an error due to incorrect input sha""" tokens = h...
python
def parse_cmdline(): """Parse command-line arguments""" parser = ArgumentParser(prog="genbank_get_genomes_by_taxon.py") parser.add_argument( "-o", "--outdir", dest="outdirname", required=True, action="store", default=None, help="Output directory (requi...
java
public String getDocument(String indexName, String documentId, Map<String, Object> options) throws ElasticSearchException{ return getDocument( indexName, _doc, documentId, options); }
python
def to_table_type(val, cls, colname): """Cast a value to the correct type for inclusion in a LIGO_LW table This method returns the input unmodified if a type mapping for ``colname`` isn't found. Parameters ---------- val : `object` The input object to convert, of any type cls : `t...
java
@SuppressWarnings("unchecked") // The constructor guarantees the type of ImmutableList. private SoyMsg resurrectMsg(long id, ImmutableList<SoyMsgPart> parts) { return SoyMsg.builder() .setId(id) .setLocaleString(localeString) .setIsPlrselMsg(MsgPartUtils.hasPlrselPart(parts)) .setP...
python
def write_sampler_metadata(self, sampler): """Writes the sampler's metadata.""" self.attrs['sampler'] = sampler.name self[self.sampler_group].attrs['nwalkers'] = sampler.nwalkers # write the model's metadata sampler.model.write_metadata(self)
java
public Pager<Event> getUserEvents(Object userIdOrUsername, ActionType action, TargetType targetType, Date before, Date after, SortOrder sortOrder, int itemsPerPage) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("action", action) ...
python
def methods(): "Names of operations provided by containerizers, as a set." pairs = inspect.getmembers(Containerizer, predicate=inspect.ismethod) return set(k for k, _ in pairs if k[0:1] != "_")
python
def notice(self, flag_message="Notice", padding=None, force=False): """ Log Level: :attr:NOTICE @flag_message: #str flags the message with the given text using :func:flag @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area with ...
python
def register(model_or_iterable, **options): """ Registers the given model(s) with the given translation options. The model(s) should be Model classes, not instances. Fields declared for translation on a base class are inherited by subclasses. If the model or one of its subclasses is already re...
java
@Override public Map<Boolean, List<T>> partitionTo(Predicate<? super T> predicate) { return partitionTo(predicate, Collectors.<T> toList()); }
java
public static MutableIntTuple add( IntTuple t0, IntTuple t1, MutableIntTuple result) { return IntTupleFunctions.apply( t0, t1, (a,b)->(a+b), result); }
java
private synchronized long getTimeSynchronized() throws OverClockedException { long current = 0; synchronized (ThreadClockImpl.class) { current = currentTimeMillis; } if (current != lastTimeMs) { generatedThisInterval = 0; lastTimeMs = curre...
python
def c_float_array(data): """Get pointer of float numpy array / list.""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): data = convert_from_sliced_object(data) assert data.flags.c_contiguous if data.dtype == np.float32: ptr_data ...
java
public void close() throws IOException { if (this.in != null) { skip(); this.in = null; if (this.digest != null) { this.digestStr = Base32.encode(this.digest.digest()); } } }