language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
async def getHiveKey(self, path): ''' Get the value of a key in the cell default hive ''' perm = ('hive:get',) + path self.user.allowed(perm) return await self.cell.hive.get(path)
python
def get_flat_models_from_fields(fields: Sequence[Field]) -> Set[Type['main.BaseModel']]: """ Take a list of Pydantic ``Field``s (from a model) that could have been declared as sublcasses of ``BaseModel`` (so, any of them could be a submodel), and generate a set with their models and all the sub-models in t...
java
public static <T extends ImageBase<T>> TrackerObjectQuad<T> meanShiftComaniciu2003(ConfigComaniciu2003 config, ImageType<T> imageType ) { TrackerMeanShiftComaniciu2003<T> alg = FactoryTrackerObjectAlgs.meanShiftComaniciu2003(config,imageType); return new Comaniciu2003_to_TrackerObjectQuad<>(alg, imageType); }
java
void setGeometryUserIndex(int geom, int index, int value) { AttributeStreamOfInt32 stream = m_geometry_indices.get(index); int pindex = getGeometryIndex_(geom); if (pindex >= stream.size()) stream.resize(Math.max((int) (pindex * 1.25), (int) 16), -1); stream.write(pindex, value); }
java
public void marshall(DeleteSubscriptionFilterRequest deleteSubscriptionFilterRequest, ProtocolMarshaller protocolMarshaller) { if (deleteSubscriptionFilterRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarsha...
java
public boolean checkKeyBelongsToNode(byte[] key, int nodeId) { List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds(); List<Integer> replicatingPartitions = getReplicatingPartitionList(key); // remove all partitions from the list, except those that belong to the // ...
java
static SourceFile extractSourceMap( SourceFile jsFile, String sourceMapURL, boolean parseInlineSourceMaps) { // Javascript version of the compiler can only deal with inline sources. if (sourceMapURL.startsWith(BASE64_URL_PREFIX)) { byte[] data = BaseEncoding.base64().decode(sourceMapURL.su...
python
def update_translations(request): """ Update translations: delete orphan translations and creates empty translations for new objects in database. """ FieldTranslation.delete_orphan_translations() num_translations = FieldTranslation.update_translations() return render_to_response('modeltranslation/admin/update_tra...
python
def save_diskspace(fname, reason, config): """Overwrite a file in place with a short message to save disk. This keeps files as a sanity check on processes working, but saves disk by replacing them with a short message. """ if config["algorithm"].get("save_diskspace", False): for ext in ["",...
python
def log(self, msg): '''Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout. ''' if self.logfile: fd = self.logfile.fileno() else: fd = sys.stdout.fileno() ...
java
@Override public void setValue(Object value) { super.setValue(value); if (parent != null) { Object parentValue = parent.getValue(); if (parentValue != null) { writeToObject(parentValue); parent.setValue(parentValue); } } ...
python
def create_flat_start_model(feature_filename, state_stay_probabilities, symbol_list, output_model_directory, output_prototype_filename, htk_trace): """ Creates a flat start...
python
def main(): """Provide the program's entry point when directly executed.""" if len(sys.argv) != 2: print("Usage: {} USERNAME".format(sys.argv[0])) return 1 caching_requestor = prawcore.Requestor( "prawcore_device_id_auth_example", session=CachingSession() ) authenticator = p...
java
private void addConnectionRequest() { if (totalConnection.get() < options.maxPoolSize && poolState.get() == POOL_STATE_OK) { //ensure to have one worker if was timeout connectionAppender.prestartCoreThread(); connectionAppenderQueue.offer(() -> { if ((totalConnection.get() < options.minP...
java
public static <T1, T2, T3, T4, R> Func4<T1, T2, T3, T4, Observable<R>> toAsyncThrowing(final ThrowingFunc4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> func, final Scheduler scheduler) { return new Func4<T1, T2, T3, T4, Observable<R>>() { @Override public Observable<R> ca...
python
def transfer_learning_tuner(self, additional_parents=None, estimator=None): """Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as "TransferL...
python
def process(self, item_session: ItemSession, request, response, file_writer_session): '''Process PhantomJS. Coroutine. ''' if response.status_code != 200: return if not HTMLReader.is_supported(request=request, response=response): return _logger....
python
def saveDirectory(alias): """save a directory to a certain alias/nickname""" if not settings.platformCompatible(): return False dataFile = open(settings.getDataFile(), "wb") currentDirectory = os.path.abspath(".") directory = {alias : currentDirectory} pickle.dump(directory, dataFile) speech.success(alias + " ...
java
public static String describeExtensionContext(StructureDefinition ext) { CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(); for (StringType t : ext.getContext()) b.append(t.getValue()); if (!ext.hasContextType()) throw new Error("no context type on "+ext.getUrl()); switch (ex...
python
def meth_set_acl(args): """ Assign an ACL role to a list of users for a workflow. """ acl_updates = [{"user": user, "role": args.role} \ for user in set(expand_fc_groups(args.users)) \ if user != fapi.whoami()] id = args.snapshot_id if not id: # get the lat...
python
def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) ...
python
def CreateMuskingumKfacFile(in_drainage_line, river_id, length_id, slope_id, celerity, formula_type, in_connectivity_file, o...
python
def start_stop_video(self): """Start and stop the video, and change the button. """ if self.parent.info.dataset is None: self.parent.statusBar().showMessage('No Dataset Loaded') return # & is added automatically by PyQt, it seems if 'Start' in self.idx_bu...
python
def api(self, name): '''return special API by package's name''' assert name, 'name is none' if flow.__name__ == name: api = flow.FlowApi() elif sign.__name__ == name: api = sign.SignApi() elif sms.__name__ == name: api = sms.SmsApi() e...
java
private void computeIv(byte label) { for (int i = 0; i < 14; i++) { ivStore[i] = masterSalt[i]; } ivStore[7] ^= label; ivStore[14] = ivStore[15] = 0; }
java
public BoxRequestsFile.UpdateFile getDisableSharedLinkRequest(String id) { BoxRequestsFile.UpdateFile request = new BoxRequestsFile.UpdateFile(id, getFileInfoUrl(id), mSession) .setSharedLink(null); return request; }
python
def author_name_from_json(author_json): "concatenate an author name from json data" author_name = None if author_json.get('type'): if author_json.get('type') == 'group' and author_json.get('name'): author_name = author_json.get('name') elif author_json.get('type') == 'person' and...
python
def build(self, recursive=True): """ Building an assembly buffers the :meth:`components` and :meth:`constraints`. Running ``build()`` is optional, it's automatically run when requesting :meth:`components` or :meth:`constraints`. Mostly it's used to test that there aren't any c...
python
def can_delete_objectives(self): """Tests if this user can delete Objectives. A return of true does not guarantee successful authorization. A return of false indicates that it is known deleting an Objective will result in a PermissionDenied. This is intended as a hint to an appli...
java
@Override public AppEngineGetList<E> filter(Filter<?>... filters) { if (filters == null) { throw new IllegalArgumentException("'filters' must not be [" + null + "]"); } this.filters = Arrays.asList(filters); return this; }
python
def get_members(self, access=None): """ returns list of members according to access type If access equals to None, then returned list will contain all members. You should not modify the list content, otherwise different optimization data will stop work and may to give you wrong ...
python
def check_license(package_info, *args): """ Does the package have a license classifier? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied) """ classifiers = package_info.get('classifiers') reason...
java
static boolean isFieldRequired(Field field) { BigQueryDataField bqAnnotation = field.getAnnotation(BigQueryDataField.class); return (bqAnnotation != null && bqAnnotation.mode().equals(BigQueryFieldMode.REQUIRED)) || field.getType().isPrimitive(); }
java
public static List<String> findAll(Pattern pattern, CharSequence content, int group) { return findAll(pattern, content, group, new ArrayList<String>()); }
java
private TernaryValue getBooleanValueWithTypes(Node n) { switch (n.getToken()) { case ASSIGN: case COMMA: return getBooleanValueWithTypes(n.getLastChild()); case NOT: return getBooleanValueWithTypes(n.getLastChild()).not(); case AND: // Assume the left-hand side is unk...
python
def GetStorageMediaImageTypeIndicators(cls, path_spec, resolver_context=None): """Determines if a file contains a supported storage media image types. Args: path_spec (PathSpec): path specification. resolver_context (Optional[Context]): resolver context, where None represents the built-in...
java
public List<JvmAnnotationReference> findAnnotations(Set<String> qualifiedNames, JvmAnnotationTarget annotationTarget) { List<JvmAnnotationReference> result = new ArrayList<>(); if (annotationTarget != null) { for (JvmAnnotationReference annotation : annotationTarget.getAnnotations()) { String id = annotatio...
python
def send_url(amount, redirect_url, url, api): ''' return payment gateway url to redirect user to it for payment. ''' values = {'api': api, 'amount': amount, 'redirect': redirect_url} send_request = requests.post(SEND_URL_FINAL, data=values) id_get = send_request.text print(id_get) if...
python
def delete_account(self, account): """ Account was deleted. """ try: luser = self._get_account(account.username) groups = luser['groups'].load(database=self._database) for group in groups: changes = changeset(group, {}) changes = group....
python
def charge( self, amount, currency=None, application_fee=None, capture=None, description=None, destination=None, metadata=None, shipping=None, source=None, statement_descriptor=None, idempotency_key=None, ): """ Creates a charge for this customer. Parameters not implemented: * **recei...
python
def getBottomLeft(self): """ Retrieves a tuple with the x,y coordinates of the lower left point of the ellipse. Requires the radius and the coordinates to be numbers """ return (float(self.get_cx()) - float(self.get_rx()), float(self.get_cy()) - float(self.get_ry()))
java
public void setAssociationIds(java.util.Collection<String> associationIds) { if (associationIds == null) { this.associationIds = null; return; } this.associationIds = new com.amazonaws.internal.SdkInternalList<String>(associationIds); }
java
public void marshall(ThirdPartyJobDetails thirdPartyJobDetails, ProtocolMarshaller protocolMarshaller) { if (thirdPartyJobDetails == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(thirdPartyJobDetail...
java
@Override public final Boolean apply(List<? extends TreeNode> path, TreeNode theNode) { return test(path, theNode); }
python
def _send_command_to_servers(self, head, body): """Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all server ...
python
def convert_ram_sdp_ar(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Simple-Dual-Port, Asynchronous Read''' clk = Signal(bool(0)) we = Signal(bool(0)) addrw = Signal(intbv(0)[ADDR_WIDTH:]) addrr = Signal(intbv(0)[ADDR_WIDTH:]) di = Signal(intbv(0)[DATA_WIDTH:]) do = Signal(intbv(0)[DATA_WIDT...
python
def glBufferData(target, data, usage): """ Data can be numpy array or the size of data to allocate. """ if isinstance(data, int): size = data data = ctypes.c_voidp(0) else: if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']: data = data.copy('C') d...
python
async def get_data(self): """Retrieve the data.""" url = '{}/{}'.format(self.url, 'all') try: with async_timeout.timeout(5, loop=self._loop): if self.password is None: response = await self._session.get(url) else: ...
python
def dot(self, rhs): """ Return the dot product of this vector and *rhs*. """ return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
java
public static ResourceField getMpxjField(int value) { ResourceField result = null; if (value >= 0 && value < MPX_MPXJ_ARRAY.length) { result = MPX_MPXJ_ARRAY[value]; } return (result); }
java
public final void rollbackRemoteTransaction(GlobalTransaction gtx) { RpcManager rpcManager = cache.getRpcManager(); CommandsFactory factory = cache.getComponentRegistry().getCommandsFactory(); try { RollbackCommand rollbackCommand = factory.buildRollbackCommand(gtx); rollbackCommand....
python
def set_ssh_creds(config, args): """ Set ssh credentials into config. Note that these values might also be set in ~/.bangrc. If they are specified both in ~/.bangrc and as command-line arguments to ``bang``, then the command-line arguments win. """ creds = config.get(A.DEPLOYER_CREDS, {})...
python
def find_schedules(self, courses=None, return_generator=False): """Returns all the possible course combinations. Assumes no duplicate courses. ``return_generator``: If True, returns a generator instead of collection. Generators are friendlier to your memory and save computation time if not ...
java
@Override public Response delete(String CorpNum, String MgtKey) throws PopbillException { if (MgtKey == null || MgtKey.isEmpty()) throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다."); return delete(CorpNum, MgtKey, null); }
python
def escape(url): ''' add escape character `|` to `url` ''' if salt.utils.platform.is_windows(): return url scheme = urlparse(url).scheme if not scheme: if url.startswith('|'): return url else: return '|{0}'.format(url) elif scheme == 'salt': ...
python
def _correct_build_location(self): # type: () -> None """Move self._temp_build_dir to self._ideal_build_dir/self.req.name For some requirements (e.g. a path to a directory), the name of the package is not available until we run egg_info, so the build_location will return a tempo...
java
@SuppressWarnings("squid:S1067") protected boolean isAtStartOfNumber() { return input.current().isDigit() || input.current().is('-') && input.next().isDigit() || input.current().is('-') && input.next().is('.') && input.next(2).isDigit() || input.current().is('.')...
java
public alluxio.proto.dataserver.Protocol.CreateUfsBlockOptionsOrBuilder getCreateUfsBlockOptionsOrBuilder() { return createUfsBlockOptions_ == null ? alluxio.proto.dataserver.Protocol.CreateUfsBlockOptions.getDefaultInstance() : createUfsBlockOptions_; }
java
@Setup public void setup() { System.setProperty("io.netty.buffer.checkAccessible", checkAccessible); System.setProperty("io.netty.buffer.checkBounds", checkBounds); buffer = bufferType.newBuffer(); }
java
private byte[] filterHTML(HttpServletRequest request, DataResponseWrapper response) throws ServletException { byte[] data = response.getData(); InputStream is = new ByteArrayInputStream(data); Document doc = tidy.parseDOM(is, null); XPath xpath...
java
private void downloadStormCode(Map conf, String topologyId, String masterCodeDir) throws IOException, TException { String clusterMode = StormConfig.cluster_mode(conf); if (clusterMode.endsWith("distributed")) { BlobStoreUtils.downloadDistributeStormCode(conf, topologyId, masterCodeDir); ...
java
public static String getZone(String[] availZones, InstanceInfo myInfo) { String instanceZone = ((availZones == null || availZones.length == 0) ? "default" : availZones[0]); if (myInfo != null && myInfo.getDataCenterInfo().getName() == DataCenterInfo.Name.Amazon) { ...
python
def acquire(self, timeout=None): """Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine. """ green = getcurrent() parent = green.parent if parent is None: raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet') ...
java
public static int[] stringsToInts(String[] stringreps) { int[] nums = new int[stringreps.length]; for (int i = 0; i < stringreps.length; i++) nums[i] = Integer.parseInt(stringreps[i]); return nums; }
python
def issuperset(self, other): """ Check if the contents of `self` is a superset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` """...
python
def run(self): """ Captures remote hosts memory """ logger = logging.getLogger(__name__) try: # Check repository GPG settings before starting workers # Handling this here prevents subprocesses from needing stdin access repo_conf = self.config['...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.GSCOL__COL: return COL_EDEFAULT == null ? col != null : !COL_EDEFAULT.equals(col); } return super.eIsSet(featureID); }
python
def get_version(self, is_full: bool = False) -> dict or str: """ This interface is used to get the version information of the connected node in current network. Return: the version information of the connected node. """ payload = self.generate_json_rpc_payload(RpcMet...
python
def _break_reads(self, contig, position, fout, min_read_length=250): '''Get all reads from contig, but breaks them all at given position (0-based) in the reference. Writes to fout. Currently pproximate where it breaks (ignores indels in the alignment)''' sam_reader = pysam.Samfile(self.bam, "rb") ...
java
protected void fireKNNsInserted(DBIDs insertions, DBIDs updates) { KNNChangeEvent e = new KNNChangeEvent(this, KNNChangeEvent.Type.INSERT, insertions, updates); Object[] listeners = listenerList.getListenerList(); for(int i = listeners.length - 2; i >= 0; i -= 2) { if(listeners[i] == KNNListener.class...
java
public List<ServerMonitoringStatistics> getMonitoringStats(GroupFilter groupFilter, ServerMonitoringFilter config) { return getMonitoringStats(Arrays.asList(getRefsFromFilter(groupFilter)), config); }
java
public BaseListener getNextValidListener(int iMoveMode) { if (m_listener != null) { if ((m_listener.isEnabled()) & (m_listener.respondsToMode(iMoveMode))) return m_listener; else return m_listener.getNextValidListener(iMoveMode); } ...
python
def init_package(path=None, name='manage'): """Initialize (import) the submodules, and recursively the subpackages, of a "manage" package at ``path``. ``path`` may be specified as either a system directory path or a list of these. If ``path`` is unspecified, it is inferred from the already-importe...
java
public org.tensorflow.util.BundleHeaderProto.Endianness getEndianness() { org.tensorflow.util.BundleHeaderProto.Endianness result = org.tensorflow.util.BundleHeaderProto.Endianness.valueOf(endianness_); return result == null ? org.tensorflow.util.BundleHeaderProto.Endianness.UNRECOGNIZED : result; }
python
def update(self, **kwargs) -> "UpdateQuery": """ Update all objects in QuerySet with given kwargs. """ return UpdateQuery( db=self._db, model=self.model, update_kwargs=kwargs, q_objects=self._q_objects, annotations=self._annotat...
java
public static void drop(DB db, String tableName) { DBSetup.drop(CallInfo.create(), db, tableName); }
java
public static int mix(int base, int added) { float bAlpha = ColorHelper.getAlpha(base) / 255f; float aAlpha = ColorHelper.getAlpha(added) / 255f; float alpha = 1 - (1 - bAlpha) * (1 - aAlpha); // alpha int bR = ColorHelper.getRed(base); int bG = ColorHelper.getGreen(base); ...
java
public DataSource<StringValue> readTextFileWithValue(String filePath, String charsetName, boolean skipInvalidLines) { Preconditions.checkNotNull(filePath, "The file path may not be null."); TextValueInputFormat format = new TextValueInputFormat(new Path(filePath)); format.setCharsetName(charsetName); format.se...
python
def _parse_error_message(self, message): """Parses the eAPI failure response message This method accepts an eAPI failure message and parses the necesary parts in order to generate a CommandError. Args: message (str): The error message to parse Returns: ...
python
def topics_count(self): """ Returns the number of topics associated with the current node and its descendants. """ return self.obj.direct_topics_count + sum(n.topics_count for n in self.children)
python
def purge_stream(self, stream_id, remove_definition=False, sandbox=None): """ Purge the stream :param stream_id: The stream identifier :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox for this stream :return: None ...
python
def _det_tc(detector_name, ra, dec, tc, ref_frame='geocentric'): """Returns the coalescence time of a signal in the given detector. Parameters ---------- detector_name : string The name of the detector, e.g., 'H1'. ra : float The right ascension of the signal, in radians. dec : ...
java
public <FT> void registerConverter(Class<FT> clazz, Converter<FT, ?> converter) { converterMap.put(clazz, converter); }
java
void updateCornerLeft() { if (m_corner != null) { int popupLeft = popup.getPopupLeft(); int dif = (getAbsoluteLeft() - popupLeft) + OFFSET; m_corner.getStyle().setLeft(dif, Unit.PX); } }
python
def add(self, val): """Add the element *val* to the list.""" _maxes, _lists = self._maxes, self._lists if _maxes: pos = bisect_right(_maxes, val) if pos == len(_maxes): pos -= 1 _maxes[pos] = val _lists[pos].append(val) ...
python
def define_task(name, tick_script, task_type='stream', database=None, retention_policy='default', dbrps=None): ''' Define a task. Serves as both create/update. name Name of the task. tick_script Path to the...
java
public Nfs3AccessResponse wrapped_getAccess(NfsAccessRequest request) throws IOException { NfsResponseHandler<Nfs3AccessResponse> responseHandler = new NfsResponseHandler<Nfs3AccessResponse>() { /* (non-Javadoc) * @see com.emc.ecs.nfsclient.rpc.RpcResponseHandler#makeNewResponse() ...
java
@Override public void endImport() { if (!m_batch.isEmpty()) { mergeInTransaction(m_em, m_batch); } if (m_em != null && m_em.isOpen()) { m_em.close(); } if (m_emf != null) { m_emf.close(); } }
python
def topic_matches_sub(sub, topic): """Check whether a topic matches a subscription. For example: foo/bar would match the subscription foo/# or +/bar non/matching would not match the subscription non/+/+ """ result = True multilevel_wildcard = False slen = len(sub) tlen = len(topic...
java
public static void assertOpenAndActive(@NonNull String ws, @NonNull String errorMsg) throws ND4JWorkspaceException { if (!Nd4j.getWorkspaceManager().checkIfWorkspaceExistsAndActive(ws)) { throw new ND4JWorkspaceException(errorMsg); } }
python
def export(gandi, resource, output, force, intermediate): """ Write the certificate to <output> or <fqdn>.crt. Resource can be a CN or an ID """ ids = [] for res in resource: ids.extend(gandi.certificate.usable_ids(res)) if output and len(ids) > 1: gandi.echo('Too many certs fo...
java
@Deprecated public static JsonObject readFrom(Reader reader) throws IOException { return JsonValue.readFrom(reader).asObject(); }
java
@BetaApi public final Instance getInstance(String instance) { GetInstanceHttpRequest request = GetInstanceHttpRequest.newBuilder().setInstance(instance).build(); return getInstance(request); }
python
def _do_subst(node, subs): """ Fetch the node contents and replace all instances of the keys with their values. For example, if subs is {'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'}, then all instances of %VERSION% in the file will be replaced with 1.2345 and so forth. ...
java
public DomainInner beginCreateOrUpdate(String resourceGroupName, String domainName, DomainInner domain) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, domainName, domain).toBlocking().single().body(); }
java
public static <T> List<T> loadAll( Class<T> klass, Iterable<Class<?>> hardcoded, ClassLoader cl, final PriorityAccessor<T> priorityAccessor) { Iterable<T> candidates; if (isAndroid(cl)) { candidates = getCandidatesViaHardCoded(klass, hardcoded); } else { candidates = getC...
java
public void sendInteger4(int val) throws IOException { int4Buf[0] = (byte) (val >>> 24); int4Buf[1] = (byte) (val >>> 16); int4Buf[2] = (byte) (val >>> 8); int4Buf[3] = (byte) (val); pgOutput.write(int4Buf); }
python
def get_entries(path): """Return sorted lists of directories and files in the given path.""" dirs, files = [], [] for entry in os.listdir(path): # Categorize entry as directory or file. if os.path.isdir(os.path.join(path, entry)): dirs.append(entry) else: ...
python
def record_to_objects(self): """Create config records to match the file metadata""" from ambry.orm.exc import NotFoundError fr = self.record contents = fr.unpacked_contents if not contents: return # Zip transposes an array when in the form of a list of lis...
java
public static <T> Set<T> wrap(final Set<T> source) { val list = new LinkedHashSet<T>(); if (source != null && !source.isEmpty()) { list.addAll(source); } return list; }