language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_openapi_dict(self, services, hostname=None, x_google_api_name=False): """JSON dict description of a protorpc.remote.Service in OpenAPI format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the ...
python
def has_parent_families(self, family_id): """Tests if the ``Family`` has any parents. arg: family_id (osid.id.Id): the ``Id`` of a family return: (boolean) - ``true`` if the family has parents, ``false`` otherwise raise: NotFound - ``family_id`` is not found ...
python
def fit_mle(self, data, b=None): """%(super)s b : float The upper bound of the distribution. If None, fixed at sum(data) """ data = np.array(data) length = len(data) if not b: b = np.sum(data) return _trunc_logser_solver(length, b), b
python
async def put_object(self, Body: Union[bytes, IO], Bucket: str, Key: str, Metadata: Dict = None, **kwargs): """ PutObject. Takes same args as Boto3 documentation Encrypts files :param: Body: File data :param Bucket: S3 Bucket :param Key: S3 Key (filepath) """ ...
python
def make_level_set(level): '''make level set will convert one level into a set''' new_level = dict() for key,value in level.items(): if isinstance(value,list): new_level[key] = set(value) else: new_level[key] = value return new_level
java
protected void setByteArrayValue(byte[] input, int offset, int length) { if ((offset + length) > input.length) { throw new IllegalArgumentException( "Invalid length: " + offset + "+" + length + " > " + input.length); } this.sValue = null; this.bVal...
python
def _derX(self,x,y,z): ''' Returns the derivative with respect to x of the interpolated function at each value in x,y,z. Only called internally by HARKinterpolator3D.derivativeX. ''' if _isscalar(x): x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1) ...
java
public void marshall(OrganizationSummary organizationSummary, ProtocolMarshaller protocolMarshaller) { if (organizationSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(organizationSummary.ge...
java
public List<ProcessorResult> handleWrite() throws ODataException { LOG.info("Handling transactional operations per each odata request."); List<ProcessorResult> resultList = new ArrayList<>(); try { for (ChangeSetEntity changeSetEntity : changeSetEntities) { ODataRequ...
python
def _to_string(self): """ Return a string representing this location. """ # Allow access to _to_string protected method return u"{course_key}+{BLOCK_TYPE_PREFIX}@{block_type}+{BLOCK_PREFIX}@{block_id}".format( course_key=self.course_key._to_string(), # pylint: disabl...
python
def gammatone(freq, bandwidth, phase=0, eta=4): """ ``Bellini, D. J. S. "AudioLazy: Processamento digital de sinais expressivo e em tempo real", IME-USP, Mastership Thesis, 2013.`` This implementation have the impulse response (for each sample ``n``, keeping the input parameter names): .. math:: ...
java
public TargetsResponse getRecentTargets(BigDecimal limit) throws ApiException { ApiResponse<TargetsResponse> resp = getRecentTargetsWithHttpInfo(limit); return resp.getData(); }
java
public static void applyMask(GrayF32 disparity , GrayU8 mask , int radius ) { if( disparity.isSubimage() || mask.isSubimage() ) throw new RuntimeException("Input is subimage. Currently not support but no reason why it can't be. Ask for it"); int N = disparity.width*disparity.height; for (int i = 0; i < N; i++...
java
public MessageBuilder replace(String target, String replacement) { int index = builder.indexOf(target); while (index != -1) { builder.replace(index, index + target.length(), replacement); index = builder.indexOf(target, index + replacement.length()); } ...
java
protected static void calculateSelectivityCoeffs(List<DoubleObjPair<DAFile>> daFiles, NumberVector query, double epsilon) { final int dimensions = query.getDimensionality(); double[] lowerVals = new double[dimensions]; double[] upperVals = new double[dimensions]; VectorApproximation queryApprox = calcu...
java
public static FSDataOutputStream create(FileSystem fs, Path file, FsPermission permission) throws IOException { // create the file with default permission FSDataOutputStream out = fs.create(file); // set its permission to the supplied one fs.setPermission(file, permission); return out; }
python
def reload_instance(self, instance_id, post_uri=None, ssh_keys=None, image_id=None): """Perform an OS reload of an instance. :param integer instance_id: the instance ID to reload :param string post_url: The URI of the post-...
java
@Override public void flush() { ObjectMapper mapper = ObjectMapperFactory.getObjectMapper(); String dtoDump; URI incidentURI; try { dtoDump = mapper.writeValueAsString(new IncidentV2DTO(this)); } catch (JsonProcessingException ex) { logger.error("Incident registration fa...
java
public static String[] split(String text, String expression) { if (text.length() == 0) { return EMPTY_STRING_ARRAY; } else { return text.split(expression, -1); } }
java
@SuppressWarnings("unchecked") @Override public <T> T adapt(Class<T> adaptTarget) throws UnableToAdaptException { //intercept the adapt to parent entry, to return interpreted entry if (adaptTarget == Entry.class) { return (T) getInterpretedEntryInEnclosingContainer(); } else ...
python
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint): """Preprocess data locally.""" import apache_beam as beam from google.datalab.utils import LambdaJob from . import _preprocess if checkpoint is None: checkpoint = _util._DEFAULT_CHECKPOINT_GSURL job_id = ('preprocess-im...
python
def _fx_mapping(raw_rates): ''' Map raw output to clearer labels ''' return {pair[0].lower(): { 'timeStamp': pair[1], 'bid': float(pair[2] + pair[3]), 'ask': float(pair[4] + pair[5]), 'high': float(pair[6]), 'low': float(pair[7]) } for pair in map(lambda x: x.split(',...
python
def create(cls, name, email, cb): """ Create the basic structure of a player """ it = cls(name, create_structure=True) it.value['email'] = email # In an actual application you'd probably want to use 'add', # but since this app might be run multiple times, you don...
java
@ReadOperation(produces = MediaType.APPLICATION_JSON_VALUE) public Map<?, ?> fetchAccountStatus(@Selector final String username, @Nullable final String providerId) { val results = new LinkedHashMap<>(); val providers = applicationContext.getBeansOfType(DuoMultifactorAuthenticationProvider.class).val...
python
def chao_shen(q): """ Computes some terms needed for the Chao-Shen KL correction. """ yx = q[q > 0] # remove bins with zero counts n = np.sum(yx) p = yx.astype(float)/n f1 = np.sum(yx == 1) # number of singletons in the sample if f1 == n: # avoid C == 0 f1 -= 1 C = 1 - (f1/n)...
python
def _run_callback( self, callback: Callable, *args: Any, **kwargs: Any ) -> "Optional[Future[Any]]": """Runs the given callback with exception handling. If the callback is a coroutine, returns its Future. On error, aborts the websocket connection and returns None. """ ...
java
public static <T> Map<String, List<T>> groupByClusterName(List<T> inputs, AsgNameProvider<T> nameProvider) { Map<String, List<T>> clusterNamesToAsgs = new HashMap<String, List<T>>(); for (T input : inputs) { String clusterName = Names.parseName(nameProvider.extractAsgName(input)).getCluster(...
java
public static boolean hasNonEmptyPath(Config config, String key) { return config.hasPath(key) && StringUtils.isNotBlank(config.getString(key)); }
java
public List<Process> read(final InputStream inputStream) throws SAXException, IOException { this.processes = ((ProcessBuildData) this.parser.read( inputStream )).getProcesses(); return this.processes; }
python
def _handle_end_way(self): """ Handle closing way element """ self._result.append(Way(result=self._result, **self._curr)) self._curr = {}
python
def metadata(dataset, node, entityids, extended=False, api_key=None): """ Request metadata for a given scene in a USGS dataset. :param dataset: :param node: :param entityids: :param extended: Send a second request to the metadata url to get extended metadata on the scene. :param api...
java
private RedBlackTreeNode<Key, Value> select(RedBlackTreeNode<Key, Value> x, int k) { // assert x != null; // assert k >= 0 && k < size(x); int t = size(x.getLeft()); if (t > k) return select(x.getLeft(), k); else if (t < k) return select(x.getRight(), k - t - 1); else return x; }
python
def unregister_handler(self, handler_or_func): """ Remove the handler from this hook's list of handlers. This does not give up until the handler is found in the class hierarchy. """ index = -1 for i, handler in enumerate(self._direct_handlers): if handler is h...
java
public static String compressChunks(String text) throws IOException { Path tempFolder = Paths.get(JAVA_TEMP_DIR, ZIP_UTILS); File tempFileIn = File.createTempFile(TMP_IN_, ZIP_UTILS_SUFFIX, tempFolder.toFile()); File tempFileOut = File.createTempFile(TMP_OUT_, ZIP_UTILS_SUFFIX, tempFolder.toFile...
python
def DbGetPropertyHist(self, argin): """ Retrieve object property history :param argin: Str[0] = Object name Str[2] = Property name :type: tango.DevVarStringArray :return: Str[0] = Property name Str[1] = date Str[2] = Property value number (array case) St...
java
static int indexOfImpl(List<?> list, @Nullable Object element) { ListIterator<?> listIterator = list.listIterator(); while (listIterator.hasNext()) { if (Objects.equal(element, listIterator.next())) { return listIterator.previousIndex(); } } return -1; }
python
def get_overlay_gateway(self): """ Get overlay-gateway name on the switch Args: callback (function): A function executed upon completion of the method. Returns: Dictionary containing details of VXLAN Overlay G...
python
def detect_outliers(in_arr, thresh=3.0): """ Detects outliers more than X standard deviations from mean. Parameters ---------- in_list: ndarray An array of measures for which outliers need to be detected. thresh: float (optional) Threshold number of standard deviations...
java
@Override protected void xFunc() throws SQLException { int argCount = args(); if (argCount != 1) { throw new SQLException("Single argument is required. args: " + argCount); } byte[] bytes = value_blob(0); GeoPackageGeometryData geometryData = null; if (bytes != null && bytes.length > 0) { geom...
python
def get_band_structure_from_vasp_multiple_branches(dir_name, efermi=None, projections=False): """ This method is used to get band structure info from a VASP directory. It takes into account that the run can be divided in several branches named "branch_x...
python
def take_ordereds_out_of_turn(self) -> tuple: """ Takes all Ordered messages from outbox out of turn """ for replica in self._replicas.values(): yield replica.instId, replica._remove_ordered_from_queue()
java
private static Terminal createDefaultTerminal() { try { return TerminalBuilder.builder() .name(CliStrings.CLI_NAME) .build(); } catch (IOException e) { throw new SqlClientException("Error opening command line interface.", e); } }
java
public static Class<?>[] getAllSuperClasses(Class<?> clz) { List<Class<?>> list = new ArrayList<>(); while ((clz = clz.getSuperclass()) != null) { list.add(clz); } return list.toArray(new Class<?>[list.size()]); }
python
def edit_securitygroup_rule(self, group_id, rule_id, remote_ip=None, remote_group=None, direction=None, ethertype=None, port_max=None, port_min=None, protocol=None): """Edit a security group rule. :param int...
python
def EmitirRemito(self, archivo="qr.png"): "Emitir Remitos que se encuentren en estado Pendiente de Emitir." response = self.client.emitirRemito( authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit}, codRemito=...
java
public final Source updateSource(Source source) { UpdateSourceRequest request = UpdateSourceRequest.newBuilder().setSource(source).build(); return updateSource(request); }
python
def load_config(deploy_dir): ''' Loads any local config.py file. ''' config = Config() config_filename = path.join(deploy_dir, 'config.py') if path.exists(config_filename): extract_file_config(config_filename, config) # Now execute the file to trigger loading of any hooks ...
python
def search_vip_request(self, search): """ Method to list vip request param search: search """ uri = 'api/v3/vip-request/?%s' % urllib.urlencode({'search': search}) return super(ApiVipRequest, self).get(uri)
java
public Matrix4f transpose(Matrix4f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.identity(); return transposeGeneric(dest); }
java
@Override public void getUserSessionKey ( CIFSContext tc, byte[] chlng, byte[] dest, int offset ) throws SmbException { if ( this.hashesExternal ) { return; } super.getUserSessionKey(tc, chlng, dest, offset); }
java
private static String getEncoding(String text) { String result = "UTF-8";//默认编码格式 String xml = text.trim(); if (xml.startsWith("<?xml")) { int end = xml.indexOf("?>"); String sub = xml.substring(0, end); StringTokenizer tokens = new StringTokenizer(sub, " =\...
python
def get_type(full_path): """Get the type (socket, file, dir, symlink, ...) for the provided path""" status = {'type': []} if os.path.ismount(full_path): status['type'] += ['mount-point'] elif os.path.islink(full_path): status['type'] += ['symlink'] if os.path.isfile(full_path): ...
python
async def verify_credentials(self): """Verify credentials with device.""" _, public_key = self.srp.initialize() msg = messages.crypto_pairing({ tlv8.TLV_SEQ_NO: b'\x01', tlv8.TLV_PUBLIC_KEY: public_key}) resp = await self.protocol.send_and_receive( ms...
python
def construct_tpb_graph(experiments: TomographyExperiment): """ Construct a graph where an edge signifies two experiments are diagonal in a TPB. """ g = nx.Graph() for expt in experiments: assert len(expt) == 1, 'already grouped?' expt = expt[0] if expt not in g: ...
java
public static final int codePointBefore(char[] text, int index) { char c2 = text[--index]; if (isLowSurrogate(c2)) { if (index > 0) { char c1 = text[--index]; if (isHighSurrogate(c1)) { return toCodePoint(c1, c2); } ...
java
public static void dumpAll(String name, Object obj, StringPrinter printer) { dumpIf(name, obj, Predicates.alwaysTrue(), Predicates.alwaysTrue(), printer); }
java
void updateFromResponseOnDeletePost(Response<ResponseBody> response) throws IOException { this.withResponse(response); String responseContent = null; if (response.body() != null) { responseContent = response.body().string(); response.body().close(); } this...
java
private void setValue(boolean rollover) { if (!ValueUtils.areEqual(this.rollover, rollover)) { boolean oldValue = this.rollover; this.rollover = rollover; maybeNotifyListeners(oldValue, rollover); } }
java
public void eInit(SarlScript script, String name, IJvmTypeProvider context) { setTypeResolutionContext(context); if (this.sarlAnnotationType == null) { this.container = script; this.sarlAnnotationType = SarlFactory.eINSTANCE.createSarlAnnotationType(); script.getXtendTypes().add(this.sarlAnnotationType); ...
python
def to_html(self): ''' Returns ------- str, the html file representation ''' javascript_to_insert = '\n'.join([ PackedDataUtils.full_content_of_javascript_files(), self.category_scatterplot_structure._visualization_data.to_javascript('getCategoryD...
python
def has_prop_value(self, prop: typing.Union[str, EnvvarProfileProperty]) -> bool: """ Returns True if the property has a concrete value set either via environment variables or on the froze profile instance. If a property only has a default value set, this returns False. """ ...
python
def inverse(self): """Return the inverse operator. Examples -------- >>> r3 = odl.rn(3) >>> vec = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2.0) >>> inv = op.inverse >>> inv(op(vec)) == vec True >>> op(inv(vec)) == vec Tru...
python
def close(self): """Closes the gzip with care to handle multiple members. """ if self.fileobj is None: return if self.mode == WRITE: self.close_member() self.fileobj = None elif self.mode == READ: self.fileobj = None ...
python
def currentPage(self): """ Return a sequence of mappings of attribute IDs to column values, to display to the user. nextPage/prevPage will strive never to skip items whose column values have not been returned by this method. This is best explained by a demonstration. L...
java
public static SplitExtractsResult splitExtractsByPredicate( Multimap<Extract, WorkUnitState> extractToWorkUnitStateMap, Predicate<WorkUnitState> predicate) { Multimap<Extract, WorkUnitState> retained = ArrayListMultimap.create(); Multimap<Extract, WorkUnitState> filtered = ArrayListMultimap.create(); ...
java
@Override public MonetaryAmount apply(MonetaryAmount amount) { return amount.getFactory().setCurrency(amount.getCurrency()).setNumber( amount.getNumber().numberValue(BigDecimal.class) .setScale(this.context.getInt(SCALE_KEY), this.context.get(RoundingMode.class))).cre...
python
def qeuler(yaw, pitch, roll): """Convert Euler angle to quaternion. Parameters ---------- yaw: number pitch: number roll: number Returns ------- np.array """ yaw = np.radians(yaw) pitch = np.radians(pitch) roll = np.radians(roll) cy = np.cos(yaw * 0.5) sy ...
java
public java.util.List<? extends com.google.api.Monitoring.MonitoringDestinationOrBuilder> getProducerDestinationsOrBuilderList() { return producerDestinations_; }
java
public int addServerRedirect(String region, String srcUrl, String destUrl, String hostHeader, int profileId, int groupId) throws Exception { int serverId = -1; PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { ...
java
public ServiceFuture<WorkbookInner> updateAsync(String resourceGroupName, String resourceName, WorkbookInner workbookProperties, final ServiceCallback<WorkbookInner> serviceCallback) { return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, resourceName, workbookProperties), serviceC...
python
def _get_predicted_embedding_addition(self, checklist_state: ChecklistStatelet, action_ids: List[int], action_embeddings: torch.Tensor) -> torch.Tensor: """ Gets the embeddings o...
python
def _get_stddevs(self, coeffs, stddev_types, num_sites): """ Return total sigma as reported in Table 2, p. 1202. """ stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES stddevs.append(coeffs['sigma'...
java
private Set<GeoFence> findGeoPointsFence( GeoPoint geoPoint, Set<GeoFence> geoFences ) { Set<GeoFence> pointFences = new HashSet<GeoFence>(); for( GeoFence geoFence : geoFences ) { if( isPointInFence( geoPoint, geoFence ) ) { pointFences.add( geoFence ); } } return poi...
java
private static boolean validateSiRNADesign(PolymerNotation one, PolymerNotation two, String rnaDesignType) throws RNAUtilsException, HELM2HandledException, NotationException, ChemistryException { if (NucleotideParser.RNA_DESIGN_NONE.equalsIgnoreCase(rnaDesignType)) { return true; } if (!NucleotidePar...
java
@Override public DeleteComputeEnvironmentResult deleteComputeEnvironment(DeleteComputeEnvironmentRequest request) { request = beforeClientExecution(request); return executeDeleteComputeEnvironment(request); }
python
def _identifier_data(self): """Return a unique identifier for the folder data""" # Use only file names data = [ff.name for ff in self.files] data.sort() # also use the folder name data.append(self.path.name) # add meta data data += self._identifier_meta() ...
java
protected base_resource[] delete_resource(nitro_service service) throws Exception { if (!service.isLogin()) service.login(); String str = nitro_util.object_to_string_withoutquotes(this); String response = _delete(service, str); return get_nitro_response(service, response); }
java
@Override public String getArrayFunction(String function, Object[] ary) { if (ary == null || ary.length == 0) { return function + "([]);"; } StringBuilder sb = new StringBuilder(); sb.append(function).append("(["); for (Object arg : ary) { if (arg inst...
python
def extract(self, cell): """ Extract a cell from the this GDSII file and include it in the current global library, including referenced dependencies. Parameters ---------- cell : ``Cell`` or string Cell or name of the cell to be extracted from the imported ...
java
private boolean add(int i, T type) { Set<T> types = edges.get(i); // If there weren't any edges to this vertex, then special case the // creation and return true. if (types == null) { types = new HashSet<T>(); edges.put(i, types); } boolea...
python
def get_ylimits(name, trg=None): """ This function will get extract the y-limits from the Tplot Variables stored in memory. Parameters: name : str Name of the tplot variable trg : list, optional The time range that you would like to look in Retur...
java
public synchronized Entry previous() { if (tc.isEntryEnabled()) SibTr.entry(tc, "previous"); // can only do anything if the cursor is still pointing in to a list checkEntryParent(); Entry previousEntry = null; synchronized(parentList) { //get the previous entry previousEn...
java
Inclusion[] rule7(Inclusion[] gcis) { assert isRule7Applicable(); final Conjunction conjunction = (Conjunction) rhs; final AbstractConcept[] concepts = conjunction.getConcepts(); if (concepts.length > gcis.length) { gcis = new Inclusion[concepts.length]; } ...
java
protected void hookCurtainFinally(FwAssistantDirector assistantDirector) { final FwCoreDirection coreDirection = assistantDirector.assistCoreDirection(); final CurtainFinallyHook hook = coreDirection.assistCurtainFinallyHook(); if (hook != null) { hook.hook(assistantDirector); ...
java
public static SerializationFormat getOutputFormat(String name) { for (SerializationFormat ft : Instance.serializationFormats) { if (ft.isAcceptedAsOutput(name)) { return ft; } } return null; }
java
public void dissect(final Parsable<?> parsable, final String inputname, final InetAddress ipAddress) throws DissectionFailure { IspResponse response; try { response = reader.isp(ipAddress); } catch (IOException | GeoIp2Exception e) { return; } extractAsnF...
java
private void initUnaryOperators() { initOperators(unaryOperators, new UnaryNumericOperator(Tag.POS) .addUnaryOperator(DOUBLE, DOUBLE, nop) .addUnaryOperator(FLOAT, FLOAT, nop) .addUnaryOperator(LONG, LONG, nop) ...
python
def read_iiasa(name, meta=False, **kwargs): """ Query an IIASA database. See Connection.query() for more documentation Parameters ---------- name : str A valid IIASA database name, see pyam.iiasa.valid_connection_names() meta : bool or list of strings If not False, also include ...
python
def rotate(self, radians): """Modifies the current transformation matrix (CTM) by rotating the user-space axes by angle :obj:`radians`. The rotation of the axes takes places after any existing transformation of user space. :type radians: float :param radians: ...
python
def update_compatibility(self, level, subject=None): """ PUT /config/(string: subject) Update the compatibility level for a subject. Level must be one of: :param str level: ex: 'NONE','FULL','FORWARD', or 'BACKWARD' """ if level not in VALID_LEVELS: raise C...
python
def write_error(self, text): """Simulate stderr""" self.flush() self.write(text, flush=True, error=True) if get_debug_level(): STDERR.write(text)
java
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments) { return new ParameterizedTypeName(null, rawType, Arrays.asList(typeArguments)); }
python
def addldapgrouplink(self, group_id, cn, group_access, provider): """ Add LDAP group link :param id: The ID of a group :param cn: The CN of a LDAP group :param group_access: Minimum access level for members of the LDAP group :param provider: LDAP provider for the LDAP gr...
java
public final HttpClient doAfterRequest(BiConsumer<? super HttpClientRequest, ? super Connection> doAfterRequest) { Objects.requireNonNull(doAfterRequest, "doAfterRequest"); return new HttpClientDoOn(this, null, doAfterRequest, null, null); }
java
public static <E> E parse(InputStream is, ParameterizedType<E> jsonObjectType) throws IOException { return mapperFor(jsonObjectType).parse(is); }
python
def keep_season(show, keep): """ Keep only the latest season. """ deleted = 0 print('%s Cleaning %s to latest season.' % (datestr(), show.title)) for season in show.seasons()[:-1]: for episode in season.episodes(): delete_episode(episode) deleted += 1 return deleted
java
public Observable<TrendingVideos> trendingAsync(TrendingOptionalParameter trendingOptionalParameter) { return trendingWithServiceResponseAsync(trendingOptionalParameter).map(new Func1<ServiceResponse<TrendingVideos>, TrendingVideos>() { @Override public TrendingVideos call(ServiceRespons...
python
def parse_arguments(): """Parse command line arguments""" import argparse parser = argparse.ArgumentParser( description=('pyNeuroML v%s: Python utilities for NeuroML2' % __version__ + "\n libNeuroML v%s"%(neuroml.__version__) + "\n jNe...
java
public void createEvent(String eventName, String entityType, String entityId, String targetEntityType, String targetEntityId, Map<String, Object> properties, DateTime eventTime) throws IOException { if (eventTime == null) { eventTime = new DateTime(); } Event event = new Event() ...
java
private static <T> void removeIdentity(List<T> list, T object) { Iterator<T> it = list.iterator(); while (it.hasNext()) { if (object == it.next()) { it.remove(); } } }