language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Chart getMSDLineChart(ArrayList<? extends Trajectory> t, int lagMin, int lagMax, AbstractMeanSquaredDisplacmentEvaluator msdeval) { double[] xData = new double[lagMax - lagMin + 1]; double[] yData = new double[lagMax - lagMin + 1]; for (int j = lagMin; j < lagMax + 1; j++) { double msd = 0; ...
java
public alluxio.grpc.TierList getAddedBlocksOnTiersOrDefault( java.lang.String key, alluxio.grpc.TierList defaultValue) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, alluxio.grpc.TierList> map = internalGetAddedBlocksOnTiers().getMap(); ...
java
public EClass getIfcShapeModel() { if (ifcShapeModelEClass == null) { ifcShapeModelEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(511); } return ifcShapeModelEClass; }
java
@Deprecated public void compact(boolean exhaustive) { if (!isCompact) { int limitCompacted = 0; int iBlockStart = 0; char iUntouched = 0xFFFF; for (int i = 0; i < indices.length; ++i, iBlockStart += BLOCKCOUNT) { indices[i] = 0xFFFF; ...
java
public void addSoftFormula(final Formula formula, int weight) { if (this.result != UNDEF) throw new IllegalStateException("The MaxSAT solver does currently not support an incremental interface. Reset the solver."); if (weight < 1) throw new IllegalArgumentException("The weight of a formula must be ...
java
protected PExp makeAnd(PExp root, PExp e) { if (root != null) { AAndBooleanBinaryExp a = new AAndBooleanBinaryExp(); a.setLeft(root.clone()); a.setOp(new LexKeywordToken(VDMToken.AND, null)); a.setType(new ABooleanBasicType()); a.setRight(e.clone()); return a; } else { return e; } }
python
def take_break(minutes: hug.types.number=5): """Enables temporarily breaking concentration""" print("") print("######################################### ARE YOU SURE? #####################################") try: for remaining in range(60, -1, -1): sys.stdout.write("\r") s...
python
def gc(args): """ %prog gc fastafile Plot G+C content distribution. """ p = OptionParser(gc.__doc__) p.add_option("--binsize", default=500, type="int", help="Bin size to use") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) ...
python
def get_sql_select(self, columns, table, distinct=False): """Creates and returns an SQL SELECT statement""" sql = 'SELECT {0} {1} FROM {2}' dist = {True: 'DISTINCT', False: ''}[distinct] return sql.format(dist, ', '.join(columns), table)
java
private Class getPrimativeClass(Object obj) { if (obj instanceof XPath) return XPath.class; Class cl = obj.getClass(); if (cl == Double.class) { cl = double.class; } if (cl == Float.class) { cl = float.class; } else if (cl == Boolean.class) { cl = bo...
python
def get_rsa_pub_key(path): ''' Read a public key off the disk. ''' log.debug('salt.crypt.get_rsa_pub_key: Loading public key') if HAS_M2: with salt.utils.files.fopen(path, 'rb') as f: data = f.read().replace(b'RSA ', b'') bio = BIO.MemoryBuffer(data) key = RSA.loa...
python
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)): '''Return direction between two points on N dimensions. List of vectors per pair of dimensions are returned in radians. E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and returned value is [pi/4, -pi/4], then the vector will be coming out the ...
python
def on_epoch_end(self, epoch_info): """ Update data in visdom on push """ metrics_df = pd.DataFrame([epoch_info.result]).set_index('epoch_idx') visdom_append_metrics( self.vis, metrics_df, first_epoch=epoch_info.global_epoch_idx == 1 )
python
def post(self, action, data=None, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='POST', data=data, headers=headers)
python
def _validate_input_column(self, column): """Make sure a passed column is our column. """ if column != self.column and column.unspecialize() != self.column: raise ValueError("Can't load unknown column %s" % column)
java
public ResultByTime withGroups(Group... groups) { if (this.groups == null) { setGroups(new java.util.ArrayList<Group>(groups.length)); } for (Group ele : groups) { this.groups.add(ele); } return this; }
java
public List<GitlabTag> getTags(GitlabProject project) { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabTag.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabTag[].class); }
java
public RewriteResult match(String path) { for (CmsRewriteAlias alias : m_aliases) { try { Pattern pattern = Pattern.compile(alias.getPatternString()); Matcher matcher = pattern.matcher(path); if (matcher.matches()) { String ...
java
public static String getDateTimeStr(Date d) { if (d == null) return ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); // 20140315 test will problem +0000 return sdf.format(d); }
java
public static Boolean and(Boolean left, Boolean right) { return left && Boolean.TRUE.equals(right); }
java
public List<TiffObject> getImageIfds() { List<TiffObject> l = new ArrayList<TiffObject>(); IFD oifd = this.firstIFD; while (oifd != null) { if (oifd.isImage()) { if (oifd.hasSubIFD()) { try { long length = oifd.getMetadata().get("ImageLength").getFirstNumericValue(); ...
python
def export(self, nidm_version, export_dir): """ Create prov entities and activities. """ if nidm_version['num'] in ["1.0.0", "1.1.0"]: self.label = self.label.replace("Supra-Threshold", "Significant") # FIXME deal with multiple contrasts atts = ( ...
java
@Override public SmbResource get ( String url ) throws CIFSException { try { return new SmbFile(url, this); } catch ( MalformedURLException e ) { throw new CIFSException("Invalid URL " + url, e); } }
python
def get_relationship_search_session_for_family(self, family_id=None, proxy=None): """Gets the ``OsidSession`` associated with the relationship search service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the family arg: proxy (osid.proxy.Proxy): a proxy return: ...
python
def linkify_es_by_h(self, hosts): """Add each escalation object into host.escalation attribute :param hosts: host list, used to look for a specific host :type hosts: alignak.objects.host.Hosts :return: None """ for escal in self: # If no host, no hope of havi...
python
def update(self, callback_method=values.unset, callback_url=values.unset, friendly_name=values.unset): """ Update the TriggerInstance :param unicode callback_method: The HTTP method to use to call callback_url :param unicode callback_url: The URL we call when the trigger ...
java
public void setUmbel(String umbel) { if(umbel != null) { umbel = umbel.trim(); } this.umbel = umbel; }
python
def main(): """ NAME plot_magmap.py DESCRIPTION makes a color contour map of desired field model SYNTAX plot_magmap.py [command line options] OPTIONS -h prints help and quits -f FILE specify field model file with format: l m g h -fmt [pdf,eps,svg,...
python
def get_args(): """ Get and parse arguments. """ import argparse parser = argparse.ArgumentParser( description="Swift Navigation SBP Example.") parser.add_argument( "-s", "--serial-port", default=[DEFAULT_SERIAL_PORT], nargs=1, help="specify the se...
python
def submit_vasp_directory(self, rootdir, authors, projects=None, references='', remarks=None, master_data=None, master_history=None, created_at=None, ncpus=None): """ Assimilates all vasp run directories beneath a ...
python
def _check_for_cycle(self, variable, period): """ Raise an exception in the case of a circular definition, where evaluating a variable for a given period loops around to evaluating the same variable/period pair. Also guards, as a heuristic, against "quasicircles", where the evaluation of...
python
def has_plugin(self, name=None, plugin_type=None): """ Check if the manager has a plugin / plugin(s), either by its name, type, or simply checking if the manager has any plugins registered in it. Utilizing the name argument will check if a plugin with that name exists in the manager. ...
java
public static IntStream buildRandomIntStream(int streamSize, int inclusiveLowerBound, int exclusiveUpperBound) { return buildRandomIntStream(streamSize, new Random(), inclusiveLowerBound, exclusiveUpperBound); }
python
def check_schedule(self, node, duration=0): """Maybe schedule new items on the node If there are any globally pending nodes left then this will check if the given node should be given any more tests. The ``duration`` of the last test is optionally used as a heuristic to influen...
java
public void setTable(final Table table) { if (table != _tableRef.get()) { _tableRef.set(table); if (table == null) { _comboBox.setEmptyModel(); } else { _comboBox.setModel(table); } } }
java
public static void respondAsHtmlUsingTemplate(HttpServletResponse resp, String resourcePageTemplate) throws IOException { respondAsHtmlUsingTemplateWithHttpStatus(resp, resourcePageTemplate, HttpStatus.SC_OK); }
python
def get_max_url_file_name_length(savepath): """ Determines the max length for any max... parts. :param str savepath: absolute savepath to work on :return: max. allowed number of chars for any of the max... parts """ number_occurrences = savepath.count('%max_url_file_name...
python
def osm_net_download(lat_min=None, lng_min=None, lat_max=None, lng_max=None, network_type='walk', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): """ Download OSM ways and nodes within a bounding box from the ...
python
def returnToMatches(allowed_return_to_urls, return_to): """Is the return_to URL under one of the supplied allowed return_to URLs? @since: 2.1.0 """ for allowed_return_to in allowed_return_to_urls: # A return_to pattern works the same as a realm, except that # it's not allowed to us...
python
def run(self, fastafile, params=None, tmp=None): """ Run the tool and predict motifs from a FASTA file. Parameters ---------- fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools require...
java
public void marshall(TimeBasedLinear timeBasedLinear, ProtocolMarshaller protocolMarshaller) { if (timeBasedLinear == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(timeBasedLinear.getLinearPercentag...
java
protected String promptForText(com.ibm.ws.security.audit.reader.utils.ConsoleWrapper stdin, PrintStream stdout) { return promptForText(stdin, stdout, "encode.enterText", "encode.reenterText", "encode.readError", "encode.entriesDidNotMatch"); }
python
def on_nick(self, connection, event): """ Someone changed their nickname - send the nicknames list to the WebSocket. """ old_nickname = self.get_nickname(event) old_color = self.nicknames.pop(old_nickname) new_nickname = event.target() message = "is now kn...
java
@SuppressWarnings("unchecked") public void setExcerptProviderClass(String className) { try { Class<?> clazz = ClassLoading.forName(className, this); if (ExcerptProvider.class.isAssignableFrom(clazz)) { excerptProviderClass = (Class<? extends ExcerptProvider>)claz...
python
def who_likes(obj): """ Usage: {% who_likes obj as var %} """ return Like.objects.filter( receiver_content_type=ContentType.objects.get_for_model(obj), receiver_object_id=obj.pk )
java
public boolean setNodeText(Document domDocument, Node n, String value) { if (n == null) return false; Node nc = null; while ((nc = n.getFirstChild()) != null) { n.removeChild(nc); } n.appendChild(domDocument.createTextNode(value)); return t...
java
private static boolean validateLocalFileRecord(FileChannel channel, long startLocRecord, long compressedSize) throws IOException { ByteBuffer lfhBuffer = getByteBuffer(LOCLEN); read(lfhBuffer, channel, startLocRecord); if (lfhBuffer.limit() < LOCLEN || getUnsignedInt(lfhBuffer, 0) != LOCSIG) { ...
python
def cpp_app_builder(build_context, target): """Pack a C++ binary as a Docker image with its runtime dependencies. TODO(itamar): Dynamically analyze the binary and copy shared objects from its buildenv image to the runtime image, unless they're installed. """ yprint(build_context.conf, 'Build CppApp...
java
@SuppressWarnings({"ThrowableInstanceNeverThrown"}) public static void validateVoid(Method method, List<Throwable> errors) { if (method.getReturnType() != Void.TYPE) { errors.add(new Exception("Method " + method.getName() + "() should be void")); } }
java
protected void closeStartTag() throws SAXException { try { // finish processing attributes, time to fire off the start element event if (m_tracer != null) super.fireStartElem(m_elemContext.m_elementName); int nAttrs = m_attr...
java
public List<TupleTwo<TreeNode, TreeNode>> flattenNodes() { List<TupleTwo<TreeNode, TreeNode>> list = new ArrayList<>(); collectNodes(root, null, list); return list; }
python
def _infer_embedded_object(value): """ Infer CIMProperty/CIMParameter.embedded_object from the CIM value. """ if value is None: # The default behavior is to assume that a value of None is not # an embedded object. If the user wants that, they must specify # the embedded_object p...
python
def setup( hosts, default_keyspace, consistency=ConsistencyLevel.ONE, lazy_connect=False, retry_connect=False, **kwargs): """ Records the hosts and connects to one of them :param hosts: list of hosts, see http://datastax.github.io/python-driver/api/cassandra/...
java
public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase( String privKeyRelativePath, String passphrase) { this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath); this.sshMeta.setPrivKeyUsePassphrase(true); this.sshMeta.setPassphrase(passphrase); this.sshMeta.setS...
java
public Expression getAttributeUndefinedValue(Factory factory) { if (attrUndefinedValue == null) return factory.TRUE(); return factory.createLiteral(attrUndefinedValue, factory.TRUE()); }
python
def main(): """ Generates code for name_to_rgb dict, assuming an rgb.txt file available (in X11 format).""" import re with open('rgb.txt') as fp: line = fp.readline() while line: reg = re.match(r'\s*(\d+)\s*(\d+)\s*(\d+)\s*(\w.*\w).*', line) if reg: r ...
java
public void register(String... packageNames) { Collection<Class<? extends Controller>> classes = getControllerClasses(packageNames); if (classes.isEmpty()) { log.warn("No annotated controllers found in package(s) '{}'", Arrays.toString(packageNames)); return; } l...
python
def get_proficiency_search_session_for_objective_bank(self, objective_bank_id, proxy): """Gets the ``OsidSession`` associated with the proficiency search service for the given objective bank. :param objective_bank_id: the ``Id`` of the ``ObjectiveBank`` :type objective_bank_id: ``osid.id.Id`` ...
java
@Override public void start() throws Exception { synchronized (lock) { if (client == null) { client = new RestClusterClient<>(clientConfiguration, "RemoteExecutor"); client.setPrintStatusDuringExecution(isPrintingStatusDuringExecution()); } else { throw new IllegalStateException("The remote exec...
java
public boolean add(Object o) { if (o instanceof List) { List list = (List) o; list.setIndentationLeft(list.getIndentationLeft() + indentationLeft); list.setIndentationRight(indentationRight); return super.add(list); } else if (o instanceof Image) {...
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { current_hostname_responses result = (current_hostname_responses) service.get_payload_formatter().string_to_resource(current_hostname_responses.class, response); if(result.errorcode != 0) { if (res...
python
def guard_retract(worksheet): """Return whether the transition retract can be performed or not to the worksheet passed in. Since the retract transition from worksheet is a shortcut to retract transitions from all analyses the worksheet contains, this guard only returns True if retract transition is allo...
python
def best_four_point_to_buy(self): """ 判斷是否為四大買點 :rtype: str or False """ result = [] if self.check_mins_bias_ratio() and \ (self.best_buy_1() or self.best_buy_2() or self.best_buy_3() or \ self.best_buy_4()): if self.best_buy_1(): ...
java
private boolean isEclipseMap(final URI mapFile) throws DITAOTException { final DocumentBuilder builder = getDocumentBuilder(); Document doc; try { doc = builder.parse(mapFile.toString()); } catch (final SAXException | IOException e) { throw new DITAOTException("Fa...
java
public Method getGetter(String column) { MappingItem methods = getMethodPair(column); return methods == null ? null : methods.getGetter(); }
python
def gt_bases(self): """Return the actual genotype bases, e.g. if VCF genotype is 0/1, could return ('A', 'T') """ result = [] for a in self.gt_alleles: if a is None: result.append(None) elif a == 0: result.append(self.site.R...
python
def load_geonames(filepath='http://download.geonames.org/export/dump/cities1000.zip'): """Clean the table of city metadata from download.geoname.org/export/dump/{filename} Reference: http://download.geonames.org/export/dump/readme.txt 'cities1000.txt' and 'allCountries.txt' have the following tab-se...
python
def merge_path_subvideo(path_subvideos, callback): """ Merge subtitles into videos. :param path_subvideos: a dict with paths as key and a list of lists of videos and subtitles :param callback: Instance of ProgressCallback :return: tuple with list of videos and list of subtitles (videos have matched ...
python
def search_star(star): ''' It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun ''' base_url = "http://star-api.herokuapp.com/api/v1/stars/" if not isinstance(star, str): raise Value...
java
public static SdkInstaller newInstaller( Path managedSdkDirectory, Version version, OsInfo osInfo, String userAgentString, boolean usageReporting) { DownloaderFactory downloaderFactory = new DownloaderFactory(userAgentString); ExtractorFactory extractorFactory = new ExtractorFactor...
python
def radial_average(self, qrange=None, pixel=False, returnmask=False, errorpropagation=3, abscissa_errorpropagation=3, raw_result=False) -> Curve: """Do a radial averaging Inputs: qrange: the q-range. If None, auto-determine. If 'linear', auto-de...
python
def grains(): ''' Get grains for proxy minion .. code-block: bash salt '*' onyx.cmd grains ''' if not DETAILS['grains_cache']: ret = system_info() log.debug(ret) DETAILS['grains_cache'].update(ret) return {'onyx': DETAILS['grains_cache']}
python
def grad_to_image(gradient): """Convert gradients of image obtained using `get_image_grad` into image. This shows parts of the image that is most strongly activating the output neurons.""" gradient = gradient - gradient.min() gradient /= gradient.max() gradient = np.uint8(gradient * 255).transpo...
python
def set_unbind(self): """ Unsets key bindings. """ self.unbind('<Button-1>') self.unbind('<Button-3>') self.unbind('<Up>') self.unbind('<Down>') self.unbind('<Shift-Up>') self.unbind('<Shift-Down>') self.unbind('<Control-Up>') self....
java
public static <REQ extends MessageBody> ByteBuf serializeRequest( final ByteBufAllocator alloc, final long requestId, final REQ request) { Preconditions.checkNotNull(request); return writePayload(alloc, requestId, MessageType.REQUEST, request.serialize()); }
java
public List<VaultUsageInner> listByVaults(String resourceGroupName, String vaultName) { return listByVaultsWithServiceResponseAsync(resourceGroupName, vaultName).toBlocking().single().body(); }
python
def refresh(self, datasource_names, merge_flag, refreshAll): """ Fetches metadata for the specified datasources and merges to the Superset database """ session = db.session ds_list = ( session.query(DruidDatasource) .filter(DruidDatasource.cluster_...
python
def acquire_restore(lock, state): """Acquire a lock and restore its state.""" if hasattr(lock, '_acquire_restore'): lock._acquire_restore(state) elif hasattr(lock, 'acquire'): lock.acquire() else: raise TypeError('expecting Lock/RLock')
python
def load_balancers_list(resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 List all load balancers within a resource group. :param resource_group: The resource group name to list load balancers within. CLI Example: .. code-block:: bash salt-call azurearm_network.load_...
python
def support_autoupload_enable(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras") autoupload = ET.SubElement(support, "autoupload") enable = ET.SubElement(autoupload...
python
def get_binary_path(executable): """Gets the software name and returns the path of the binary.""" if sys.platform == 'win32': if executable == 'start': return executable executable = executable + '.exe' if executable in os.listdir('.'): binary = os.path.join(os.ge...
python
def update_stage(self, stage, executable=None, force=False, name=None, unset_name=False, folder=None, unset_folder=False, stage_input=None, instance_type=None, edit_version=None, **kwargs): ''' :param stage: A number for the stage index (for the nth stage, start...
java
public BatchUpdatePhoneNumberRequest withUpdatePhoneNumberRequestItems(UpdatePhoneNumberRequestItem... updatePhoneNumberRequestItems) { if (this.updatePhoneNumberRequestItems == null) { setUpdatePhoneNumberRequestItems(new java.util.ArrayList<UpdatePhoneNumberRequestItem>(updatePhoneNumberRequestIte...
java
private void printClassList(PrintStream out, Iterable<EntityIdValue> classes) { out.print(",\""); boolean first = true; for (EntityIdValue superClass : classes) { if (first) { first = false; } else { out.print("@"); } // makeshift escaping for Miga: out.print(getClassLabel(superClass).repla...
java
public static void copyFetches(Fetch<?, ?> from, Fetch<?, ?> to) { for (Fetch<?, ?> f : from.getFetches()) { Fetch<?, ?> toFetch = to.fetch(f.getAttribute().getName()); // recursively copy fetches copyFetches(f, toFetch); } }
python
def set_rate_BC(self, pores, values): r""" Apply constant rate boundary conditons to the specified pore locations. This is similar to a Neumann boundary condition, but is slightly different since it's the conductance multiplied by the gradient, while Neumann conditions specify ju...
java
private void cleanEmptyParentDirectory(Path path) throws IOException { Path normPath = path.normalize(); if(normPath.equals(Paths.get(getDirectory()).normalize()) || normPath.equals(Paths.get(System.getProperty("java.io.tmpdir")).normalize())) { //stop if we reach the output or temporary directory ...
java
public static boolean isDotQuadIP ( String hostname ) { if ( Character.isDigit(hostname.charAt(0)) ) { int i, len, dots; char[] data; i = dots = 0; /* quick IP address validation */ len = hostname.length(); data = hostname.toCharArray(); w...
python
def product_request(self, product, subjects): """Executes a request for a single product for some subjects, and returns the products. :param class product: A product type for the request. :param list subjects: A list of subjects or Params instances for the request. :returns: A list of the requested pro...
python
def get_block_by_number(self, block_number, full_transactions=True): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbynumber """ if isinstance(block_number, numbers.Number): block_number_as_hex = hex(block_number) else: block_number_as_hex ...
java
public static MethodInvocation start(String objectName, String methodName, int lineNumber) { bigMessage("Starting profiling... " + objectName + "#" + methodName + " (" + lineNumber + ")"); if (profiling()) { logger.error("Profiling was already started for '{}'", callstack.getFirst().getCls()...
java
public void analyzeExecuteArg(Method executeMethod, ExecuteArgBox box) { List<Class<?>> pathParamTypeList = null; // lazy loaded Parameter formParam = null; final Parameter[] parameters = executeMethod.getParameters(); if (parameters.length > 0) { boolean formEnd = false; ...
python
def prepare_query_params(**kwargs): """ Prepares given parameters to be used in querystring. """ return [ (sub_key, sub_value) for key, value in kwargs.items() for sub_key, sub_value in expand(value, key) if sub_value is not None ]
python
def GetConnection(self, ConnectionObj): """ Get a Open and active connection Returns a PySQLConnectionManager if one is open else it will create a new one if the max active connections hasn't been hit. If all possible connections are used. Then None is returned. @param PySQLConnectionObj: PySQLConnectio...
python
def addcomment(self, invoice_increment_id, comment=None, email=False, include_comment=False): """ Add comment to invoice or change its state :param invoice_increment_id: Invoice ID """ if comment is None: comment = "" return bool( self...
java
@POST @Consumes({"script/groovy"}) @Path("validate{name:.*}") public Response validateScript(@PathParam("name") String name, final InputStream script, @QueryParam("sources") List<String> sources, @QueryParam("file") List<String> files) { try { validateScript(name, script, createSo...
python
def on_help_menu_open(self, widget): """Open Help menu""" self.original_widget = urwid.Overlay(self.help_menu.main_window, self.original_widget, ('relative', self.left_margin), ...
python
def to_mongo(self, disjunction=True): """Create from current state a valid MongoDB query expression. :return: MongoDB query expression :rtype: dict """ q = {} # add all the main clauses to `q` clauses = [e.expr for e in self._main] if clauses: ...
java
public AwsSecurityFindingFilters withProcessName(StringFilter... processName) { if (this.processName == null) { setProcessName(new java.util.ArrayList<StringFilter>(processName.length)); } for (StringFilter ele : processName) { this.processName.add(ele); } ...
python
def is_parsable(url): """Check if the given URL is parsable (make sure it's a valid URL). If it is parsable, also cache it. Args: url (str): The URL to check. Returns: bool: True if parsable, False otherwise. """ try: parsed = urlparse(url)...