language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void updateWriter() { HdfsStreamWriter result = new HdfsStreamWriter(); String suffix = this.config.getTmpFileSuffix(); int suffixIndex = 0; boolean isFileSyncEachTime = this.config.isFileSyncEachTime(); boolean isSucceed = false; while (suffixIndex < ...
java
@Override public void set(final String key, final R resource) { this.resourceMap.put(key, new SoftReference<>(resource)); }
java
public static nd6ravariables[] get(nitro_service service, options option) throws Exception{ nd6ravariables obj = new nd6ravariables(); nd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option); return response; }
python
def fit(self, X, y=None, **kwargs): """ The fit method is the primary drawing input for the UMAP projection since the visualization requires both X and an optional y value. The fit method expects an array of numeric vectors, so text documents must be vectorized before passing the...
java
private OperatorSymbol makeOperator(Name name, List<OperatorType> formals, OperatorType res, int... opcodes) { MethodType opType = new MethodType( formals.stream() .map(o -> o.asType(syms)) .collect(List.collector()), res.asType(sym...
python
def my_glob(pattern): """ get a listing matching pattern @param pattern: @return: """ result = [] if pattern[0:4] == 'vos:': dirname = os.path.dirname(pattern) flist = listdir(dirname) for fname in flist: fname = '/'.join([dirname, fname]) if ...
python
def search(self, term): """ Search for images on Docker Hub. Similar to the ``docker search`` command. Args: term (str): A term to search for. Returns: (list of dicts): The response of the search. Raises: :py:class:`docker.errors.API...
python
def rax(a, boot, threads, \ fast = False, run_rax = False, run_iq = False, model = False, cluster = False, node = False): """ run raxml on 'a' (alignment) with 'boot' (bootstraps) and 'threads' (threads) store all files in raxml_a_b 1. give every sequence a short identifier 2. convert fa...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.TEXT_ORIENTATION__IAXIS: setIAxis(IAXIS_EDEFAULT); return; case AfplibPackage.TEXT_ORIENTATION__BAXIS: setBAxis(BAXIS_EDEFAULT); return; } super.eUnset(featureID); }
python
def _select_meshes(self, data): """ Define the x and y indices with respect to the low-resolution mesh image of the meshes to use for the background interpolation. The ``exclude_percentile`` keyword determines which meshes are not used for the background interpolation. ...
java
private void assertAttributeExists(String attribute) throws UnknownColumnException { for (DataColumn column : columns) { if (column.getCode().equals(attribute)) { return; } } throw new UnknownColumnException(attribute); }
python
def batchseeds(args): """ %prog batchseeds folder Extract seed metrics for each image in a directory. """ from jcvi.formats.pdf import cat xargs = args[1:] p = OptionParser(batchseeds.__doc__) opts, args, iopts = add_seeds_options(p, args) if len(args) != 1: sys.exit(not p...
python
def convert_ilsvrc2012(directory, output_directory, output_filename='ilsvrc2012.hdf5', shuffle_seed=config.default_seed): """Converter for data from the ILSVRC 2012 competition. Source files for this dataset can be obtained by registering at [ILSVRC2012WEB]. ...
python
def _get_logger_file_handles(self): """ Find the file handles used by our logger's handlers. """ handles = [] for handler in self.logger.handlers: # The following code works for logging's SysLogHandler, # StreamHandler, SocketHandler, and their subclasses....
java
public static ImmutableMap<String, Object> prepareArguments(String param, Object value) { ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); builder.put(param, value); return builder.build(); }
java
public Matrix4d rotateXYZ(Vector3d angles) { return rotateXYZ(angles.x, angles.y, angles.z); }
java
public List<LogSegment> trunc(int newStart) { if (newStart < 0) { throw new IllegalArgumentException("Starting index must be positive."); } while (true) { List<LogSegment> curr = contents.get(); int newLength = Math.max(curr.size() - newStart, 0); ...
java
protected boolean isDate(String item) { if (item == null) { return false; } if (item.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z$")) { return true; } if (item.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")) { return t...
python
def _fit_data(self, X): """Binarize the data for each column separately. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- X_transformed : array-like Returns the data where in each columns the labels are ...
java
public java.util.List<PropertyDifference> getPropertyDifferences() { if (propertyDifferences == null) { propertyDifferences = new com.amazonaws.internal.SdkInternalList<PropertyDifference>(); } return propertyDifferences; }
java
@VisibleForTesting void rollbackTasks(String workflowId, List<Task> createdTasks) { String description = "rolling back task from DAO for " + workflowId; String operation = "rollbackTasks"; try { // rollback all newly created tasks in the workflow createdTasks.forEach...
java
public Observable<ListContainerItemsInner> listAsync(String resourceGroupName, String accountName) { return listWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<ListContainerItemsInner>, ListContainerItemsInner>() { @Override public ListContainerItem...
java
public EClass getPTD() { if (ptdEClass == null) { ptdEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(317); } return ptdEClass; }
java
Type mostSpecificReturnType(Type mt1, Type mt2) { Type rt1 = mt1.getReturnType(); Type rt2 = mt2.getReturnType(); if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) { //if both are generic methods, adjust return type ahead of subtyping check rt1 = types.subst(rt1, mt1.getType...
python
def get_analysis_config(self, group_name): """ Gets any config data saved for the analysis. :param group_name: The name of the analysis group. :returns: A dictionary of dictionaries. Each key represents an analysis step. Each value is a dictionary containing the analysis...
python
def circular_mask(size): """Create a circular mask for an array Useful when sampling rasters for a laser shot """ r = size/2 c = (r,r) y,x = np.ogrid[-c[0]:size-c[0], -c[1]:size-c[1]] mask = ~(x*x + y*y <= r*r) return mask
python
def feedback_results_to_measurements_frame(feedback_result): ''' Extract measured data from `FeedbackResults` instance into `pandas.DataFrame`. ''' index = pd.Index(feedback_result.time * 1e-3, name='seconds') df_feedback = pd.DataFrame(np.column_stack([feedback_result.V_fb, ...
java
public static ManagedChannel createChannelPool(final String host, final BigtableOptions options, int count) throws IOException, GeneralSecurityException { final List<ClientInterceptor> interceptorList = new ArrayList<>(); ClientInterceptor credentialsInterceptor = CredentialInterceptorCache.getInstance()...
java
public void setIconAnchor(@Property.ICON_ANCHOR String value) { jsonObject.addProperty(SymbolOptions.PROPERTY_ICON_ANCHOR, value); }
python
def search_string(self): """" Returns the JSON string that LendingClub expects for it's search """ self.__normalize() # Get the template tmpl_source = unicode(open(self.tmpl_file).read()) # Process template compiler = Compiler() template = compil...
java
public static List<DnsCacheEntry> listDnsCache() { try { return InetAddressCacheUtil.listInetAddressCache().getCache(); } catch (Exception e) { throw new DnsCacheManipulatorException("Fail to listDnsCache, cause: " + e.toString(), e); } }
java
public static boolean greater(final Object o1, final Object o2) { switch (getTypeMark(o1, o2)) { case BYTE: case SHORT: case INTEGER: return ((Number) o1).intValue() > ((Number) o2).intValue(); case LONG: return ((Number) o1).longVa...
python
def Contains(self, other): """Checks if the passed parameter is in the range of this object. """ if other is None: raise ValueError("other is None.") if isinstance(other, Range): if other.low >= self.low and other.high <= self.high: return True ...
java
private boolean canPushdownLimit() { boolean limitCanPushdown = (m_limitOffset.hasLimit() && !m_distinct); if (limitCanPushdown) { for (ParsedColInfo col : m_displayColumns) { AbstractExpression rootExpr = col.m_expression; if (rootExpr instanceof AggregateExp...
java
@Override protected void addNavDetailLink(boolean link, Content liNav) { if (link) { liNav.addContent(writer.getHyperLink( SectionName.CONSTRUCTOR_DETAIL, contents.navConstructor)); } else { liNav.addContent(contents.navConstructor); ...
java
@Override @LogarithmicTime(amortized = true) public K deleteMin() { if (Constants.NOT_BENCHMARK && size == 0) { throw new NoSuchElementException(); } K result = array[0]; size--; array[0] = array[size]; array[size] = null; if (size > 1) { ...
python
def WriteFromFD(self, src_fd, arcname=None, compress_type=None, st=None): """Write a zip member from a file like object. Args: src_fd: A file like object, must support seek(), tell(), read(). arcname: The name in the archive this should take. compress_type: Compression type (zipfile.ZIP_DEFLA...
python
def wigner_d_small(J, beta): u"""Return the small Wigner d matrix for angular momentum J. We use the general formula from [Edmonds74]_, equation 4.1.15. Some examples form [Edmonds74]_: >>> from sympy import Integer, symbols, pi >>> half = 1/Integer(2) >>> beta = symbols("beta", real=True) ...
java
@BQConfigProperty("Specify the levels of specific warnings") public void setWarningLevels(Map<String, Severity> levels) { if (levels == null) { this.warningLevels = new HashMap<>(); } else { this.warningLevels = levels; } }
java
public static MimeBodyPart newMultipartBodyPart( Multipart multipart ) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(multipart); return mimeBodyPart; }
java
public static String encodeQ(byte[] bytes, Usage usage) { BitSet qChars = usage == Usage.TEXT_TOKEN ? Q_REGULAR_CHARS : Q_RESTRICTED_CHARS; StringBuilder sb = new StringBuilder(); final int end = bytes.length; for (int idx = 0; idx < end; idx++) { int v = bytes[idx] & 0xff; if (v == 32) { sb.append(...
python
def _trigger(self, obj, old, value, hint=None, setter=None): ''' Unconditionally send a change event notification for the property. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property ...
python
def rest(url, req="GET", data=None): """Main function to be called from this module. send a request using method 'req' and to the url. the _rest() function will add the base_url to this, so 'url' should be something like '/ips'. """ load_variables() return _rest(base_url + url, req, data)
python
def get_ip_interface_input_request_type_get_request_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface input = ET.SubElement(get_ip_interface, "input") ...
python
def removeRootFromName(string): """Helper function to remove /pub, /files from string.""" global garbageRoots for root in garbageRoots: if root in string: string = string[string.find(root) + len(root):] return string
java
private static void assignObjectIds(final Object jsonVal, final Map<ReferenceEqualityKey<Object>, JSONObject> objToJSONVal, final ClassFieldCache classFieldCache, final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId, final AtomicInteger objId, final boolean ...
python
def get_response(self): """ Get a response from the chatbot and display it. """ user_input = self.usr_input.get() self.usr_input.delete(0, tk.END) response = self.chatbot.get_response(user_input) self.conversation['state'] = 'normal' self.conversation.in...
python
def redirect(self, url, status=None): """ Redirect to the specified url, optional status code defaults to 302. """ self.status_code = 302 if status is None else status self.headers = Headers([('location', url)]) self.message = '' self.end()
java
@Override public CommerceShipment create(long commerceShipmentId) { CommerceShipment commerceShipment = new CommerceShipmentImpl(); commerceShipment.setNew(true); commerceShipment.setPrimaryKey(commerceShipmentId); commerceShipment.setCompanyId(companyProvider.getCompanyId()); return commerceShipment; }
python
def _init_value(self, key): """Initialize a value. Lock must be held by caller.""" encoded = key.encode('utf-8') # Pad to be 8-byte aligned. padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8)) value = struct.pack('i{0}sd'.format(len(padded)).encode(), len(encoded), padded, 0...
python
def get_pip(mov=None, api=None, name=None): """get value of pip""" # ~ check args if mov is None and api is None: logger.error("need at least one of those") raise ValueError() elif mov is not None and api is not None: logger.error("mov and api are exclusive") raise ValueE...
java
public static Optional<SamlRegisteredServiceServiceProviderMetadataFacade> get(final SamlRegisteredServiceCachingMetadataResolver resolver, final SamlRegisteredService registeredService, ...
java
public static CmsMessageContainer validateUserAndPasswordNotEmpty(String username, String password) { boolean userEmpty = CmsStringUtil.isEmpty(username); boolean passwordEmpty = CmsStringUtil.isEmpty(password); // login was requested if (userEmpty && passwordEmpty) { retur...
java
public void marshall(UpdatePolicyRequest updatePolicyRequest, ProtocolMarshaller protocolMarshaller) { if (updatePolicyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updatePolicyRequest.ge...
java
public Closeable onUnsubscribeChannelEvent(final Consumer<BitfinexStreamSymbol> listener) { unsubscribeChannelConsumers.offer(listener); return () -> unsubscribeChannelConsumers.remove(listener); }
java
public static int sizeOfIA5String(String value) { return DerUtils.sizeOf(ASN1_IA5STRING_TAG_NUM, (value == null) ? 0 : value.getBytes().length); }
python
def _order_by_pks(qs, pks): """ Adjust the given queryset to order items according to the explicit ordering of PKs provided. This is a PostgreSQL-specific DB hack, based on: blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html """ pk_colname = '%s.%s' % ( ...
python
def _set_meta(self, title, published, category='', tags=''): """ the header :param title: the title of the post :param published: the date when the data has been published by the provider :param category: category of this data :param tags:...
java
public static Object remove (Object[] list, int index) { if (list == null) { return null; } int llength = list.length; if (llength <= index || index < 0) { return null; } Object elem = list[index]; System.arraycopy(list, index+1, list...
python
def do_bl(self, arg): """ bl - list the breakpoints for the current process bl * - list the breakpoints for all processes [~process] bl - list the breakpoints for the given process bl <process> [process...] - list the breakpoints for each given process """ debug =...
python
def num_throats(self, labels='all', mode='union'): r""" Return the number of throats of the specified labels Parameters ---------- labels : list of strings, optional The throat labels that should be included in the count. If not supplied, all throats are ...
java
public static servicegroup[] get_filtered(nitro_service service, String filter) throws Exception{ servicegroup obj = new servicegroup(); options option = new options(); option.set_filter(filter); servicegroup[] response = (servicegroup[]) obj.getfiltered(service, option); return response; }
python
def from_ops(*operations: ops.OP_TREE, strategy: InsertStrategy = InsertStrategy.EARLIEST, device: devices.Device = devices.UnconstrainedDevice ) -> 'Circuit': """Creates an empty circuit and appends the given operations. Args: operations: ...
java
public static boolean shouldEnableACRA(@NonNull SharedPreferences prefs) { boolean enableAcra = true; try { final boolean disableAcra = prefs.getBoolean(ACRA.PREF_DISABLE_ACRA, false); enableAcra = prefs.getBoolean(ACRA.PREF_ENABLE_ACRA, !disableAcra); } catch (Exception ...
java
@Override public Long getValue(int pollerIndex) { final long n = getCount(pollerIndex); return n > 0 ? totalMeasurement.getValue(pollerIndex).longValue() / n : 0L; }
python
def file_exists(original_file): """ Check to make sure the original file exists """ if original_file.startswith("s3://"): from filesystem import s3 return s3.file_exists(original_file) else: if not os.path.exists(original_file): return False if not os.path...
python
def Input_dispatchTouchEvent(self, type, touchPoints, **kwargs): """ Function path: Input.dispatchTouchEvent Domain: Input Method name: dispatchTouchEvent WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'type' (type: string) -> Type of the touch event. Tou...
java
public String getDescription() { StringBuffer buf = new StringBuffer(); String transportName = config.getName(); for (ProbeSender sender : senders) { buf.append(transportName).append(" -- ").append(isEnabled() ? "Enabled" : "Disabled") .append(" -- ").append(sender.getDescription()); } ...
java
public EventHandlerStatus dispatchEvent(HttpServletRequest httpRequest) { ApiContext apiContext = new MozuApiContext(httpRequest); Event event = null; // get the event from the request and validate try { String body = IOUtils.toString(httpRequest.getInputStream()); ...
python
def encode_bbox_target(boxes, anchors): """ Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape. """ anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2)) anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y...
java
private int computePixelSize(final SampleModel sampleModel) { int size = 0; for (int i = 0; i < sampleModel.getNumBands(); i++) { size += sampleModel.getSampleSize(i); } return size; }
java
public static double huntKennedyCMSAdjustedRate( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit) { double a = 1.0/swapMaturity; double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; double convexityAdjustment =...
python
def features_keep_within_radius(obj, center, radius, units): """ Filter all features in a collection by retaining only those that fall within the specified radius. """ features_keep = [] for feature in tqdm(obj['features']): if all([getattr(geopy.distance.vincenty((lat,lon), center), uni...
java
private ElemDesc getElemDesc2(String name) { Object obj = m_htmlInfo.get2(name); if (null != obj) return (ElemDesc)obj; return m_dummy; }
python
def fast_clone(self, VM, clone_name, mem=None): """ Create a 'fast' clone of a VM. This means we make a snapshot of the disk and copy some of the settings and then create a new VM based on the snapshot and settings The VM is transient so when it is shutdown it deletes itself ...
java
public void flush() throws IOException { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "flush"); boolean crlfWrite = false; // check for nonblocking if(this._listener!= null){ synchronized(this){ WebContainer...
python
def write_layout(_path): """ Write a valid gentoo layout file to :path:. Args: path - The output path of the layout.conf """ path.mkdir_uchroot("/etc/portage/metadata") path.mkfile_uchroot("/etc/portage/metadata/layout.conf") with open(_path, 'w') as layoutconf: lines = '''...
python
def stop_proxying(self, signal_source, *signal_names, weak_ref=False): """ :meth:`.WSignalProxyProto.stop_proxying` implementation """ callback = self.__callback if weak_ref is False else self.__weak_ref_callback for signal_name in signal_names: signal_source.remove_callback(signal_name, callback)
python
def get_cusum(self, mag): """ Return max - min of cumulative sum. Parameters ---------- mag : array_like An array of magnitudes. Returns ------- mm_cusum : float Max - min of cumulative sum. """ c = np.cumsum(mag ...
python
def _delAccountRights(sidObject, user_right): ''' helper function to remove an account right from a user ''' try: _polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS) user_rights_list = [user_right] _ret = win32security.LsaRemoveAccountRights(_polHandle...
java
public static long unionCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.pop_union( a.bits, b.bits, 0, Math.min( a.wlen, b.wlen ) ); if (a.wlen < b.wlen) { tot += BitUtil.pop_array( b.bits, a.wlen, b.wlen - a.wlen ); } else if (a.wlen > b.wlen) { tot += BitUtil.pop_...
java
public Object withBuilder(Map attributes, FactoryBuilderSupport builder, String name, Closure closure) { if (name == null) { return null; } Object result = getProxyBuilder().withBuilder(builder, closure); return getProxyBuilder().invokeMethod(name, new Object[]{attributes, re...
java
@GET @Path("table/{tableName}/inputs/graph") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public Response inputsGraph(@Context HttpServletRequest request, @PathParam("tableName") String tableName) { if (LOG.isDebugEnabled()) { LOG.debug("==> DataSetLineageR...
python
def setText(self, sequence): """Qt method extension.""" self.setToolTip(sequence) super(ShortcutLineEdit, self).setText(sequence)
python
def GetCollectionNode(self, partition_key): """Gets the SelfLink/ID based link of the collection node that maps to the partition key based on the hashing algorithm used for finding the node in the ring. :param str partition_key: The partition key to be used for finding the node in t...
java
private void closeConnection(WsOutbound outbound, GuacamoleStatus guacStatus) { closeConnection(outbound, guacStatus.getGuacamoleStatusCode(), guacStatus.getWebSocketCode()); }
java
public Expression convertToMutableBooleanExpression(ImmutableExpression booleanExpression) { OperationPredicate pred = booleanExpression.getFunctionSymbol(); return termFactory.getExpression(pred, convertToMutableTerms(booleanExpression.getTerms())); }
java
@Override public T poll(long timeout, TimeUnit unit) throws InterruptedException { T old = poll(); long endTimeMillis = System.currentTimeMillis() + unit.toMillis(timeout); long timeLeftMillis = endTimeMillis - System.currentTimeMillis(); int spinctr = SPINS_TAKE_; while (ol...
python
def ClearAllVar(self): """Clear this Value.""" self.value = None # Call OnClearAllVar on options. _ = [option.OnClearAllVar() for option in self.options]
python
def matchPrefix(text): """ This is silver bullet, cornerstone and magic wand of speed of this algorithm it filters patterns using manually selected rules. Yes, yes, it's "dirty" code and it could be beautified in many ways but this library intended to be fast, not beautiful. Without matching is x1.3 slo...
java
public void modifyFirstLegBo(KiteConnect kiteConnect) throws KiteException, IOException { OrderParams orderParams = new OrderParams(); orderParams.quantity = 1; orderParams.price = 31.0; orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; orderParams.tradingsymbol = "SO...
java
public String toDOTString() { StringBuilder sb = new StringBuilder(); // id [label=id: value-type <value-type-attributes>]; // id -> child_id; // id -> child_id; sb.append(m_id).append(" [label=\"").append(m_id).append(": ").append(getPlanNodeType()).append("\" "); sb.a...
python
def updateD_H(self, x): """ Compute Hessian for update of D See [2] for derivation of Hessian """ self.precompute(x) H = zeros((len(x), len(x))) Ai = zeros(self.A.shape[0]) Aj = zeros(Ai.shape) for i in range(len(x)): Ai = self.A[:, i]...
java
public static EntityType create(@NonNull String name, EntityType parent) { EntityType toReturn = DynamicEnum.register(new EntityType(name, parent)); if (toReturn.setParentIfAbsent(parent)) { Config.setProperty(toReturn.canonicalName() + ".parent", parent.canonicalName()); } values.add(t...
python
def export_for_schema(self): """ Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement. """ ret = "{'class': 'NetworkTopologyStrategy'" for dc, repl_factor in sorted(self.dc_replication_factors.items()): ...
java
static public int getFreeServerPort(int port){ int resultPort = 0; ServerSocket s; try { s = new ServerSocket(port); resultPort = s.getLocalPort(); s.close(); } catch (IOException e) { resultPort = 0; } return resultPort; }
java
protected Response post(MultivaluedMap<String, String> queryParams, URL url) { return (invocation(url, queryParams).post(null)); }
python
def add_style_opts(cls, component, new_options, backend=None): """ Given a component such as an Element (e.g. Image, Curve) or a container (e.g Layout) specify new style options to be accepted by the corresponding plotting class. Note: This is supplied for advanced users who kno...
java
public ByteBuffer read(long offset, int length, ByteBuffer block) throws IllegalArgumentException, IllegalStateException, IOException { if (!this.valid) { throw new IllegalStateException("Attempting to read an " + "known-to-be invalid piece!"); } return this._read(offset, leng...
python
def merge_model_instances(self, primary_object, alias_objects): """ Merge several model instances into one, the `primary_object`. Use this function to merge model objects and migrate all of the related fields from the alias objects the primary object. """ generic_fields =...