language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Format[] getFormatsByArgumentIndex() { if (msgPattern.hasNamedArguments()) { throw new IllegalArgumentException( "This method is not available in MessageFormat objects " + "that use alphanumeric argument names."); } ArrayList<Format> lis...
java
public static Map<String, String> mapBean(final Object bean, final String exclude) { final Set<String> excludes = new HashSet<String>(); if (!StringUtils.isBlank(exclude)) { excludes.add(exclude); } return mapBean(bean, excludes); }
java
private OSchemaHelper oClass(String className, boolean abstractClass, String... superClasses) { lastClass = schema.getClass(className); if(lastClass==null) { OClass[] superClassesArray = new OClass[superClasses.length]; for (int i = 0; i < superClasses.length; i++) { String superClassName = superClasse...
java
public static <T> T min(final Comparator<? super T> comp, final T a, final T b) { return a != null ? b != null ? comp.compare(a, b) <= 0 ? a : b : a : b; }
python
def setEnable(self, status, wanInterfaceId=1, timeout=1): """Set enable status for a WAN interface, be careful you don't cut yourself off. :param bool status: enable or disable the interface :param int wanInterfaceId: the id of the WAN interface :param float timeout: the timeout to wait...
python
def receive_datagram(self): """ Receive datagram from the UDP socket and invoke the callback function. """ logger.debug("Start receiver Thread") while not self.stopped.isSet(): self._socket.settimeout(0.1) try: datagram, addr = self._socket...
python
def F_to_K(self, F, method='doubling'): """ Compute agent 2's best cost-minimizing response K, given F. Parameters ---------- F : array_like(float, ndim=2) A k x n array method : str, optional(default='doubling') Solution method used in solving th...
python
def create_logstash(self, **kwargs): """ Creates an instance of the Logging Service. """ logstash = predix.admin.logstash.Logging(**kwargs) logstash.create() logstash.add_to_manifest(self) logging.info('Install Kibana-Me-Logs application by following GitHub instr...
java
protected InputStream readResource(ProtectedResourceDetails details, URL url, String httpMethod, OAuthConsumerToken token, Map<String, String> additionalParameters, Map<String, String> additionalRequestHeaders) { url = configureURLForProtectedAccess(url, token, details, httpMethod, additionalParameters); String...
python
def p44(msg): """Static pressure. Args: msg (String): 28 bytes hexadecimal message string Returns: int: static pressure in hPa """ d = hex2bin(data(msg)) if d[34] == '0': return None p = bin2int(d[35:46]) # hPa return p
python
def ctypes_parameter(self): """Returns the parameter list for this ValueElement adjusted for interoperability with the ctypes module. """ if self._ctypes_parameter is None: #Essentially, we just need to check if we are an array that doesn't have explicitly #define...
java
public Set<InstallLicense> getFeatureLicense(Collection<String> featureNames, Locale locale, String userId, String password) throws InstallException { Set<InstallLicense> licenses = new HashSet<InstallLicense>(); if (featureNames == null || featureNames.isEmpty()) return licenses; M...
python
def set_source_google_finance(self): """ Set data source to Google Finance """ self.data_worker = data_worker self.worker_args = {"function": pandas.io.data.DataReader, "input": self.input_queue, "output": self.output_map, "source": 'google'} s...
python
def read_inifile (self, noexistok=False, typed=False): """Open assuming an “ini-file” format and return a generator yielding data records using either :func:`pwkit.inifile.read_stream` (if *typed* is false) or :func:`pwkit.tinifile.read_stream` (if it’s true). The latter version is desig...
python
def updateEditor( self ): """ Updates the editor based on the current selection. """ # assignt the rule operators to the choice list rule = self.currentRule() operator = self.currentOperator() widget = self.uiWidgetAREA.widget() edi...
python
def table_columns(self): '''Yields column names.''' with self.conn.cursor() as cur: cur.execute(self.TABLE_COLUMNS_QUERY % self.database) for row in cur: yield row
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_label') and self.document_label is not None: _dict['document_label'] = self.document_label if hasattr(self, 'location') and self.location is not None: ...
java
public static boolean isTerminal(ArrayList<Configuration> beam) { for (Configuration configuration : beam) if (!configuration.state.isTerminalState()) return false; return true; }
java
public void addAttributesExcept(Map params, String ... exceptions){ List exceptionList = Arrays.asList(exceptions); for(Object key: params.keySet()){ if(!exceptionList.contains(key)){ attribute(key.toString(), params.get(key).toString()); } } }
python
def _redis_process_checkpoint(host, port): '''this helper method checks if redis server is available in the sys if not fires up one ''' try: subprocess.check_output("pgrep redis", shell=True) except Exception: logger.warning( 'Your redis server is offline, fake2db wil...
java
protected boolean isFromLocalhost(HttpServletRequest request) throws MalformedURLException { String host = new URL(request.getRequestURL().toString()).getHost(); return host.equals("localhost") || host.equals("127.0.0.1") || host.equals("0:0:0:0:0:0:0:1"); }
java
@Override public EClass getIfcCurtainWallType() { if (ifcCurtainWallTypeEClass == null) { ifcCurtainWallTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(160); } return ifcCurtainWallTypeEClass; }
java
private static void ensureStatusOk(HttpResponse<String> response) throws ClientErrorException, ServerErrorException, OtherCommunicationException { int responseStatus = response.getStatus(); if (isClientError(responseStatus)) { throw new ClientErrorException(response.getBody()); ...
python
def affine_mat(self)->AffineMatrix: "Get the affine matrix that will be applied by `refresh`." if self._affine_mat is None: self._affine_mat = torch.eye(3).to(self.device) return self._affine_mat
java
public EEnum getIfcReinforcingBarRoleEnum() { if (ifcReinforcingBarRoleEnumEEnum == null) { ifcReinforcingBarRoleEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(884); } return ifcReinforcingBarRoleEnumEEnum; }
python
def reply(self): """ Captures reply message within email """ reply = [] for f in self.fragments: if not (f.hidden or f.quoted): reply.append(f.content) return '\n'.join(reply)
java
public void setAudioDecoderConfiguration(IRTMPEvent decoderConfig) { if (decoderConfig instanceof IStreamData) { IoBuffer data = ((IStreamData<?>) decoderConfig).getData().asReadOnlyBuffer(); audioConfigurationTag = ImmutableTag.build(decoderConfig.getDataType(), 0, data, 0); ...
python
def _Open(self, path_spec=None, mode='rb'): """Opens the file-like object. Args: path_spec (Optional[PathSpec]): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like object could not be...
java
public Object execute(String method, Vector params) throws XmlRpcClientExecutorException { LOGGER.debug("executing method {} , with params {}", method, params); try { return client.execute(method, params); } catch (XmlRpcException ex) { throw new XmlRpcClientExecutorException(CALL_FAILED, ex); ...
java
@Override public ImageHeader readHeader(InputStream input) throws IOException { final long toSkip = 8L; final boolean bigEndian = 'M' == input.read(); checkSkippedError(input.skip(HEADER_SIZE - 1L), HEADER_SIZE - 1); final int ifd = readInt(input, 4, bigEndian); input.ski...
python
def create_subscription(self, subscription): """CreateSubscription. Create a subscription. :param :class:`<Subscription> <azure.devops.v5_0.service_hooks.models.Subscription>` subscription: Subscription to be created. :rtype: :class:`<Subscription> <azure.devops.v5_0.service_hooks.models...
python
def poll(self, timeout_ms=0, max_records=None): """Fetch data from assigned topics / partitions. Records are fetched and returned in batches by topic-partition. On each poll, consumer will try to use the last consumed offset as the starting offset and fetch sequentially. The last consum...
java
public SerialMessage getNoMoreInformationMessage() { logger.debug("Creating new message for application command WAKE_UP_NO_MORE_INFORMATION for node {}", this.getNode().getNodeId()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.Seria...
java
@Override public AliasType get(String key) { key = key.toUpperCase(); AliasType type = super.get(key); if (type == null) { register(type = new AliasType(key)); } return type; }
python
def checkpoint_filename(checkpoint, pipeline_name=None): """ Translate a checkpoint to a filename. This not only adds the checkpoint file extension but also standardizes the way in which checkpoint names are mapped to filenames. :param str | pypiper.Stage checkpoint: name of a pipeline phase/stage...
java
static long getLengthProperty(Context cx, Scriptable obj, boolean throwIfTooLarge) { // These will both give numeric lengths within Uint32 range. if (obj instanceof NativeString) { return ((NativeString)obj).getLength(); } if (obj instanceof NativeArray) { return ...
java
private HtmlResponse asListHtml() { return asHtml(path_AdminDuplicatehost_AdminDuplicatehostJsp).renderWith(data -> { RenderDataUtil.register(data, "duplicateHostItems", duplicateHostService.getDuplicateHostList(duplicateHostPager)); // page navi }).useForm(SearchForm.class, setup -> { ...
java
public static <MK, K, V> Map<K, V> getReadOnlyAtomicMap(Cache<MK, ?> cache, MK key) { AtomicMap<K, V> am = getAtomicMap(cache, key, false); if (am == null) return Collections.emptyMap(); else return immutableMapWrap(am); }
python
def to_log_level(value): """ Converts numbers and strings to standard log level values. :param value: a value to be converted :return: converted log level """ if value == None: return LogLevel.Info value = str(value).upper() if ("0" == value...
java
@Override public void setConstraintMappings(Configuration<?> config) throws IOException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "setConstraintMappings", config); } InputStream inputStream = null; ClassLoader ccl = getContextClassL...
java
protected boolean isValidInternal(Class < T > javaClass, CobolContext cobolContext, byte[] hostData, int start) { int end = start + getBytesLen(); // examine nibbles in each byte in turn int[] nibbles = new int[2]; // all nibbles, except the last one, must hold valid digit...
python
def draw_capitan_stroke_onto_canvas(self, export_path: ExportPath, stroke_thickness: int, margin: int): """ Draws the symbol strokes onto a canvas :param export_path: The path, where the symbols should be created on disk :param stroke_thickness: :param margin: """ ...
python
def read_string(data, length_fmt="H"): """ Reads a serialized string :param data: Bytes where to read the string from :param length_fmt: Structure format of the string length (H or Q) :return: The deserialized string """ (length,), data = read(data, ">{0}".format(length_fmt)) ba, data =...
python
def get_signature(token, contextable=False, comparison=False): """ Gets the signature tuple for any native tag contextable searchs for ``as`` variable to update context comparison if true uses ``negate`` (p) to ``not`` the result (~p) returns (``tag_name``, ``args``, ``kwargs``) """ bits = s...
python
def appendPadding(str, blocksize=AES_blocksize, mode='CMS'): ''' Pad (append padding to) string for use with symmetric encryption algorithm Input: (string) str - String to be padded (int) blocksize - block size of the encryption algorithm (string) mode - padding scheme one in (CMS, Bit, Z...
java
protected ArrayList<String> _split_multi_line(String text, int max_len) { // TODO Auto-generated method stub ArrayList<String> output = new ArrayList<String>(); text = text.trim(); if(text.length() <= max_len) { output.add(text); return output; } ArrayList<String> words = new ArrayList<String>(); C...
python
def stash(self, storage, url): """Stores the uploaded file in a temporary storage location.""" result = {} if self.is_valid(): upload = self.cleaned_data['upload'] name = storage.save(upload.name, upload) result['filename'] = os.path.basename(name) ...
python
def onselection(self, widget): """Called when a new item gets selected in the list.""" self._selected_key = None for k in self.children: if self.children[k] == widget: # widget is the selected ListItem self._selected_key = k if (self._selected_item is...
java
public <T> T lookupNodeDatum (Function<NodeObject,T> op) { for (T value : Iterables.filter(Iterables.transform(getNodeObjects(), op), Predicates.notNull())) { return value; } return null; }
python
def getPhenotypes(self,i0=None,i1=None,phenotype_IDs=None,geneIDs=None,environments=None,center=True,impute=True,intersection=False): """load Phenotypes Args: i0: phenotype indices to load (start individual index) i1: phenotype indices to load (st...
java
@Override public CommerceWishList fetchByPrimaryKey(Serializable primaryKey) { Serializable serializable = entityCache.getResult(CommerceWishListModelImpl.ENTITY_CACHE_ENABLED, CommerceWishListImpl.class, primaryKey); if (serializable == nullModel) { return null; } CommerceWishList commerceWishList = ...
java
public static ColumnField build(IntrospectedColumn column) { ColumnField field = new ColumnField(); field.setColumnName(column.getActualColumnName()); field.setJdbcType(column.getJdbcTypeName()); field.setFieldName(column.getJavaProperty()); field.setRemarks(column.getRemarks());...
java
@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = 0; for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int h ...
java
public Tuple shiftLeft() { if (degree() < 2) { return Tuple0.INSTANCE; } Object[] copy = new Object[degree() - 1]; System.arraycopy(array(), 1, copy, 0, copy.length); return NTuple.of(copy); }
python
def _check_sdp_from_eigen(w, tol=None): """Checks if some of the eigenvalues given are negative, up to a tolerance level, with a default value of the tolerance depending on the eigenvalues. Parameters ---------- w : array-like, shape=(n_eigenvalues,) Eigenvalues to check for non semidefinite posit...
python
def index(request, obj_id=None): """Handles a request based on method and calls the appropriate function""" if request.method == 'GET': return get(request, obj_id) elif request.method == 'POST': return post(request) elif request.method == 'PUT': getPutData(request) return...
java
public static <G extends Gene<?, G>, C extends Comparable<? super C>> EvolutionResult<G, C> of( final Optimize optimize, final ISeq<Phenotype<G, C>> population, final long generation, final long totalGenerations, final EvolutionDurations durations, final int killCount, final int invalidCount, final int...
python
def remove_indices(self, indices): """ Remove rows by which have the given indices. Parameters ---------- indices : list Returns ------- filtered_list : EList """ new_list = [] for index, element in enumerate(self): if...
python
def spkcpt(trgpos, trgctr, trgref, et, outref, refloc, abcorr, obsrvr): """ Return the state, relative to a specified observer, of a target having constant position in a specified reference frame. The target's position is provided by the calling program rather than by loaded SPK files. http://n...
python
def compute_scale(min_, max_, logarithmic, order_min, min_scale, max_scale): """Compute an optimal scale between min and max""" if min_ == 0 and max_ == 0: return [0] if max_ - min_ == 0: return [min_] if logarithmic: log_scale = compute_logarithmic_scale(min_, max_, min_scale, m...
python
def _cloglog_utility_transform(systematic_utilities, alt_IDs, rows_to_alts, shape_params, intercept_params, intercept_ref_pos=None, *a...
python
def reset(self): """ override reset behavior """ if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num
java
@JsonAnySetter public void putConfigurationValue(String key, Object value) { this.configuration.put(key, value); }
java
public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize) throws InterruptedException, IOException { URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); return new LargeFileUpload(). upload(this.getAPI(), this.getI...
python
def _parse_container(tokens, index, for_or_if=None): """Parse a high-level container, such as a list, tuple, etc.""" # Store the opening bracket. items = [Atom(Token(*tokens[index]))] index += 1 num_tokens = len(tokens) while index < num_tokens: tok = Token(*tokens[index]) if ...
java
public void marshall(GetDocumentRequest getDocumentRequest, ProtocolMarshaller protocolMarshaller) { if (getDocumentRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getDocumentRequest.getAut...
python
def set_id(self,pid): """ Set the property identifier @type pid: string @param pid: property identifier """ if self.type == 'KAF': return self.node.set('pid',pid) elif self.type == 'NAF': return self.node.set('id',pid)
java
public static <T> IndexChangeAdapter forUniqueValuedProperty( ExecutionContext context, NodeTypePredicate matcher, String workspaceName, ...
python
def _prepare_request(self, command, query): """ :param command: The Url command parameter :type command: str :param query: will get json encoded. :type query: dict :return: """ from luckydonaldUtils.encoding import to_native as n from pytgbot.a...
python
def clear_published(self): """Removes the published status. :raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ metadata = Metadata(**settings.METADATA['published...
java
public SearchParameterContactComponent addContact() { //3 SearchParameterContactComponent t = new SearchParameterContactComponent(); if (this.contact == null) this.contact = new ArrayList<SearchParameterContactComponent>(); this.contact.add(t); return t; }
java
@FFDCIgnore(value = { Throwable.class }) // Liberty Change for CXF End protected static Object createProvider(String className, Bus bus) { try { Class<?> cls = ClassLoaderUtils.loadClass(className, ProviderFactory.class); for (Constructor<?> c : cls.getConstructors()) { ...
python
def _gen_cache_key_for_slice(url_dict, start_int, total_int, authn_subj_list): """Generate cache key for the REST URL the client is currently accessing or is expected to access in order to get the slice starting at the given ``start_int`` of a multi-slice result set. When used for finding the key to ch...
python
def _encode_uvarint(data, n): ''' Encodes integer into variable-length format into data.''' if n < 0: raise ValueError('only support positive integer') while True: this_byte = n & 0x7f n >>= 7 if n == 0: data.append(this_byte) break data.append...
python
def get_domain_events(self, originator_id, gt=None, gte=None, lt=None, lte=None, limit=None, is_ascending=True, page_size=None): """ Returns domain events for given entity ID. """
java
private void initPortIdToGlyphMap(List<Glyph> glyphs) { for(Glyph glyph: glyphs) { for(Port p: glyph.getPort()) { portIDToOwnerGlyph.put(p.getId(), glyph ); } if(glyph.getGlyph().size() > 0) initPortIdToGlyphMap(glyph.ge...
python
def cancel(self): """ Forget about the changes """ logger.info("Index: Index update cancelled") if self.index_writer: self.index_writer.cancel() del self.index_writer self.index_writer = None if self.label_guesser_updater: self....
java
public CompletableFuture<Void> anoint() { if (role.role() == RaftServer.Role.LEADER) { return CompletableFuture.completedFuture(null); } CompletableFuture<Void> future = new CompletableFuture<>(); threadContext.execute(() -> { // Register a leader election listener to wait for the election...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.CFIRG__FCS_NAME: setFCSName(FCS_NAME_EDEFAULT); return; case AfplibPackage.CFIRG__CP_NAME: setCPName(CP_NAME_EDEFAULT); return; case AfplibPackage.CFIRG__SV_SIZE: setSVSize(SV_SIZE_EDEFAULT); return...
python
def display(self): """Displays the network to the screen.""" size = list(range(len(self.layers))) size.reverse() for i in size: layer = self.layers[i] if layer.active: print('%s layer (size %d)' % (layer.name, layer.size)) tlabel, o...
python
def diff(self, dim, n=1, label='upper'): """Calculate the n-th order discrete difference along given axis. Parameters ---------- dim : str, optional Dimension over which to calculate the finite difference. n : int, optional The number of times values are ...
python
def resize(self, signum, obj): """ handler for SIGWINCH """ self.s.clear() stream_cursor = self.pads['streams'].getyx()[0] for pad in self.pads.values(): pad.clear() self.s.refresh() self.set_screen_size() self.set_title(TITLE_STRING) self.init...
python
def run(self): """ Inserts data generated by rows() into target table. If the target table doesn't exist, self.create_table will be called to attempt to create the table. Normally you don't want to override this. """ if not (self.table and self.columns): rai...
java
public Acl updateBlobAcl(String bucketName, String blobName, long blobGeneration) { // [START updateBlobAcl] BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration); Acl acl = storage.updateAcl(blobId, Acl.of(User.ofAllAuthenticatedUsers(), Role.OWNER)); // [END updateBlobAcl] return acl; ...
java
@Override public void destroy() // PK20881 { if (tc.isEntryEnabled()) Tr.entry(tc, "destroy"); // Dummy transactionWrappers may not be in any table and so // will not have a resourceCallback registered to remove them. if (_resourceCallback != null) _resou...
python
def row_sparse_array(arg1, shape=None, ctx=None, dtype=None): """Creates a `RowSparseNDArray`, a multidimensional row sparse array with a set of \ tensor slices at given indices. The RowSparseNDArray can be instantiated in several ways: - row_sparse_array(D): to construct a RowSparseNDArray wi...
java
public void setDevicePools(java.util.Collection<DevicePool> devicePools) { if (devicePools == null) { this.devicePools = null; return; } this.devicePools = new java.util.ArrayList<DevicePool>(devicePools); }
python
def create_person(self, first_name, last_name, email, department = None, default_rate = None, admin = False, contractor = False): '''Creates a Person with the given information.''' person = {'user':{ 'first_name': first_name, 'last_name': last_name, 'email': emai...
python
def create_shell(shell=None, **kwargs): """Returns a Shell of the given type, or the current shell type if shell is None.""" if not shell: shell = config.default_shell if not shell: from rez.system import system shell = system.shell from rez.plugin_managers impor...
java
private void opNullCheckEndMemST() { int mem = code[ip++]; /* mem: null check id */ int isNull = nullCheckMemSt(mem, s); if (isNull != 0) { if (Config.DEBUG_MATCH) { Config.log.println("NULL_CHECK_END_MEMST: skip id:" + mem + ", s:" + s); } ...
python
def getEdges(self, vertex, inEdges = True, outEdges = True, rawResults = False) : """returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id. If rawResults a arango results will be return as fetched, if false, will return a liste of Edge ob...
python
def add_output(self, address, value, unit='satoshi'): """ Add an output (a person who will receive funds via this tx). If no unit is specified, satoshi is implied. """ value_satoshi = self.from_unit_to_satoshi(value, unit) if self.verbose: print("Adding outpu...
java
public Response post(String endpoint, Request params, File file) { return call(Method.POST, endpoint, params, file); }
java
public PagedList<DeletedCertificateItem> getDeletedCertificates(final String vaultBaseUrl) { ServiceResponse<Page<DeletedCertificateItem>> response = getDeletedCertificatesSinglePageAsync(vaultBaseUrl).toBlocking().single(); return new PagedList<DeletedCertificateItem>(response.body()) { @Ov...
python
def html(self) -> str: """Return html-escaped string representation of this node.""" if self.parentNode and self.parentNode._should_escape_text: return html.escape(self.data) return self.data
java
@XmlElementDecl(namespace = "http://www.opengis.net/citygml/bridge/2.0", name = "BridgeConstructionElement", substitutionHeadNamespace = "http://www.opengis.net/citygml/2.0", substitutionHeadName = "_CityObject") public JAXBElement<BridgeConstructionElementType> createBridgeConstructionElement(BridgeConstructionEle...
python
def get_editorTab(self, editor): """ Returns the **Script_Editor_tabWidget** Widget tab associated with the given editor. :param editor: Editor to search tab for. :type editor: Editor :return: Tab index. :rtype: Editor """ for i in range(self.Script_Edit...
python
def get_bandstructure_by_material_id(self, material_id, line_mode=True): """ Get a BandStructure corresponding to a material_id. REST Endpoint: https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure or https://www.materialsproject.org/rest/v2/materials/<mp-id>/vas...
java
public int transferFrom(MessageBatch other, boolean clear) { if(other == null || this == other) return 0; int capacity=messages.length, other_size=other.size(); if(other_size == 0) return 0; if(capacity < other_size) messages=new Message[other_size]; ...
python
def bump_option_validator(ctx, param, value): """In case a value is provided checks that it is a valid version string. If is not thrown :class:`click.UsageError`. Return a :class:`~braulio.version.Version` object or **None**. """ if value: try: value = Version(value) ex...