language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
static List<ProjectDefinition> getTopDownParentProjects(ProjectDefinition project) { List<ProjectDefinition> result = new ArrayList<>(); ProjectDefinition p = project; while (p != null) { result.add(0, p); p = p.getParent(); } return result; }
python
def rt_time_log(logfile, startdate): """ Open and read reftek raw log-file. Function to open and read a log-file as written by a RefTek RT130 datalogger. The information within is then scanned for timing errors above the threshold. :type logfile: str :param logfile: The logfile to look in ...
python
def verificar_permissao(self, id_vlan, nome_equipamento, nome_interface): """Check if there is communication permission for VLAN to trunk. Run script 'configurador'. The "stdout" key value of response dictionary is 1(one) if VLAN has permission, or 0(zero), otherwise. :param i...
python
def _set_iroot_via_xroot(self, xroot): """Determine the index of the root cell. Given an expression vector, find the observation index that is closest to this vector. Parameters ---------- xroot : np.ndarray Vector that marks the root cell, the vector storin...
java
public HttpResponse decompress() throws IOException { String enc = header("Content-Encoding"); return (enc != null && enc.contains("gzip")) ? unzip() : this; }
python
async def readobj(self): """ Return a parsed Redis object or an exception when something wrong happened. """ assert self._parser is not None, "set_parser must be called" while True: obj = self._parser.gets() if obj is not False: # ...
java
public MessagePacker addPayload(byte[] src, int off, int len) throws IOException { if (buffer == null || buffer.size() - position < len || len > bufferFlushThreshold) { flush(); // call flush before add // Directly add the payload without using the buffer out...
python
def replace_lun(self, *lun_list): """Replaces the exiting LUNs to lun_list.""" lun_add = self._prepare_luns_add(lun_list) lun_remove = self._prepare_luns_remove(lun_list, False) return self.modify(lun_add=lun_add, lun_remove=lun_remove)
python
def save(self, filename=None): """ Saves the runtime configuration to disk. Parameters ---------- filename: str or None, default=None writeable path to configuration filename. If None, use default location and filename. """ if not filename: ...
java
private void handleJoinEvent(Node node) { GossipMember member = new GossipMember(MemberId.from(node.id().id()), node.address()); if (!members.containsKey(member.id())) { sendHeartbeat(member); } }
python
def cache_key(self): """ Key for the cache handling current site. """ return '%s:%s' % (super(EntryPublishedVectorBuilder, self).cache_key, Site.objects.get_current().pk)
python
def hash(value, arg): """ Returns a hex-digest of the passed in value for the hash algorithm given. """ arg = str(arg).lower() if sys.version_info >= (3,0): value = value.encode("utf-8") if not arg in get_available_hashes(): raise TemplateSyntaxError("The %s hash algorithm does n...
python
def get_url(cls, ticket): """ 通过ticket换取二维码地址 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542 :param ticket: 二维码 ticket 。可以通过 :func:`create` 获取到 :return: 返回的二维码地址 使用示例:: from wechatpy import WeChatClient client =...
java
@Override public Calendar reply(Calendar request) { Calendar reply = transform(Method.REPLY, request); reply.validate(); return reply; }
python
def getDeviceIterator(self, skip_on_error=False): """ Return an iterator over all USB devices currently plugged in, as USBDevice instances. skip_on_error (bool) If True, ignore devices which raise USBError. """ device_p_p = libusb1.libusb_device_p_p() ...
java
@Override public void addPackageDescription(Content packageContentTree) { if (!utils.getBody(packageElement).isEmpty()) { Content tree = configuration.allowTag(HtmlTag.SECTION) ? sectionTree : packageContentTree; addDeprecationInfo(tree); addInlineComment(packageElement, ...
python
def add_statements(self, pmid, stmts): """Add INDRA Statements to the incremental model indexed by PMID. Parameters ---------- pmid : str The PMID of the paper from which statements were extracted. stmts : list[indra.statements.Statement] A list of INDRA ...
java
public void marshall(SegmentGroup segmentGroup, ProtocolMarshaller protocolMarshaller) { if (segmentGroup == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(segmentGroup.getDimensions(), DIMENSIONS_BI...
python
def load_dxf(file_obj, **kwargs): """ Load a DXF file to a dictionary containing vertices and entities. Parameters ---------- file_obj: file or file- like object (has object.read method) Returns ---------- result: dict, keys are entities, vertices and metadata """ def inf...
python
def nullify(v): """Convert empty strings and strings with only spaces to None values. """ if isinstance(v, six.string_types): v = v.strip() if v is None or v == '': return None else: return v
java
protected AstNode parseCustomStatement( DdlTokenStream tokens, AstNode parentNode ) throws ParsingException { assert tokens != null; assert parentNode != null; // DEFAULT DOES NOTHING // Subclasses can implement additional parsing ret...
java
public void setInt(String name, int value) throws UnsupportedEncodingException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setInt", Integer.valueOf(value)); getBodyMap().put(name, Integer.valueOf(value)); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEna...
java
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response upload(MultipartBody multipart){ Attachment file = multipart.getAttachment("file"); if (file == null) { return Response.status(400).entity("Missing file part").type(MediaType.TEXT_PLAIN).build(); } InputSt...
java
static ResponseList<HelpResources.Language> createLanguageList(JSONArray list, HttpResponse res , Configuration conf) throws TwitterException { if (conf.isJSONStoreEnabled()) { TwitterObjectFactory.clearThreadLocalMap(); } try { int size = list.length(); ...
python
def decode_utf8(f): """Decode a utf-8 string encoded as described in MQTT Version 3.1.1 section 1.5.3 line 177. This is a 16-bit unsigned length followed by a utf-8 encoded string. Parameters ---------- f: file File-like object with read method. Raises ------ UnderflowDeco...
python
def main() -> None: """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument("directory", nargs="?", default=os.getcwd()) parser.add_argument("--reportevery", default=10000) arg...
python
def evaluate_rpn(rpn): """ Evaluates the RPN form produced my map2rpn. Returns: bool """ vals_stack = [] for item in rpn: if item in _ALL_OPS: # Apply the operator and push to the task. v2 = vals_stack.pop() if item in _UNARY_OPS: ...
java
@Trivial private void writeObject(ObjectOutputStream out) throws IOException { PutField fields = out.putFields(); fields.put(FAILURE, failure); fields.put(PARAMS, params); fields.put(REASON, reason); out.writeFields(); }
python
def filter_string(self, word): """Return a string like the input but containing only legal IPA segments Args: word (unicode): input string to be filtered Returns: unicode: string identical to `word` but with invalid IPA segments absent """ ...
python
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit): """Exports all collections to (JSON-) files.""" export_format = export_format.upper() if pretty: indent = 4 else: indent = 0 f = None if filename: try: f = open(fil...
java
public static Set<JAASSystem> getAllJAASSystems() { final Set<JAASSystem> ret = new HashSet<>(); final Cache<Long, JAASSystem> cache = InfinispanCache.get().<Long, JAASSystem>getCache(JAASSystem.IDCACHE); for (final Map.Entry<Long, JAASSystem> entry : cache.entrySet()) { ret.add(...
java
@Override @Nullable public Charset charsetForName (@Nonnull final String sCharsetName) { final String sRealCharsetName = sCharsetName.toUpperCase (Locale.US); for (final Charset aCharset : m_aCharsets) if (aCharset.name ().equals (sRealCharsetName)) return aCharset; for (final Charset aC...
java
private Object[] getValues(Map<String, Object> annotationAtts) { if (null == annotationAtts) { throw new DuraCloudRuntimeException("Arg annotationAtts is null."); } List<Object> values = new ArrayList<Object>(); for (String key : annotationAtts.keySet()) { Objec...
java
public String getDisplayValue(Object ob) { if( ob == null ) { return ""; } if( ob instanceof Translator ) { return getDisplayValue(Locale.getDefault(), ob); } return ob.toString(); }
python
def master_call(self, **kwargs): ''' Execute a wheel function through the master network interface (eauth). ''' load = kwargs load['cmd'] = 'wheel' interface = self.opts['interface'] if interface == '0.0.0.0': interface = '127.0.0.1' master_uri...
java
public static boolean containsOptionWithMatching(final List<?> options, final Object data) { if (options != null) { for (Object option : options) { if (option instanceof OptionGroup) { List<?> groupOptions = ((OptionGroup) option).getOptions(); if (groupOptions != null) { for (Object nestedOpti...
python
def extract_user_keywords_generator(twitter_lists_gen, lemmatizing="wordnet"): """ Based on the user-related lists I have downloaded, annotate the users. Inputs: - twitter_lists_gen: A python generator that yields a user Twitter id and a generator of Twitter lists. - lemmatizing: A string conta...
java
@Restricted(NoExternalUse.class) public boolean hasFreshToken(@Nonnull User user, @Nullable ApiTokenProperty.TokenInfoAndStats legacyStats) { if (legacyStats == null) { return false; } ApiTokenProperty apiTokenProperty = user.getProperty(ApiTokenProperty.class); ...
python
def hsps(self): """ Get all HSPs for all the alignments for all titles. @return: A generator yielding L{dark.hsp.HSP} instances. """ return (hsp for titleAlignments in self.values() for alignment in titleAlignments for hsp in alignment.hsps)
java
private void ssMintroSort(int PA, int first, int last, int depth) { final int STACK_SIZE = SS_MISORT_STACKSIZE; StackElement[] stack = new StackElement[STACK_SIZE]; int Td;// T ptr int a, b, c, d, e, f;// SA ptr int s, t; int ssize; int limit; int v, x = 0...
python
def get_junctions_string(self): """Get a string representation of the junctions. This is almost identical to a previous function. :return: string representation of junction :rtype: string """ self._initialize() return ';'.join([x.get_range_string() for x in self.junctions])
python
def subject(self): """The certificates subject as :py:class:`~django_ca.subject.Subject`.""" return Subject([(s.oid, s.value) for s in self.x509.subject])
python
def create_telnet_shell(shell, loop=None): """ Run a shell application with a telnet frontend :param application: An EmbedShell instance :param loop: The event loop :returns: Telnet server """ if loop is None: loop = asyncio.get_event_loop() def factory(reader, writer): ...
java
public final void addLayerListener(MapLayerListener listener) { if (this.listeners == null) { this.listeners = new ListenerCollection<>(); } this.listeners.add(MapLayerListener.class, listener); }
java
public static boolean stringInPatterns(String s, List<Pattern> patterns) { for (Pattern pattern : patterns) { if (pattern.matcher(s).matches()) { return true; } } return false; }
python
def m(name='', **kwargs): """ Print out memory usage at this point in time http://docs.python.org/2/library/resource.html http://stackoverflow.com/a/15448600/5006 http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended """ with Reflect.context(**kwargs) as r: ...
python
def _get_present_locations(match_traversals): """Return the set of locations and non-optional locations present in the given match traversals. When enumerating the possibilities for optional traversals, the resulting match traversals may have sections of the query omitted. These locations will not be i...
java
public Waiter<DescribeTrainingJobRequest> trainingJobCompletedOrStopped() { return new WaiterBuilder<DescribeTrainingJobRequest, DescribeTrainingJobResult>() .withSdkFunction(new DescribeTrainingJobFunction(client)) .withAcceptors(new TrainingJobCompletedOrStopped.IsCompletedMat...
java
public static BufferedReader asBufferedReader(String fileName) throws IOException { Validate.notBlank(fileName, "filename is blank"); return asBufferedReader(getPath(fileName)); }
java
@Override public void addTags(ExecutableElement method, Content methodDocTree) { writer.addTagsInfo(method, methodDocTree); }
python
def discrete(self): """ A sequence of connected vertices in space, corresponding to self.paths. Returns --------- discrete : (len(self.paths),) A sequence of (m*, dimension) float """ discrete = np.array([self.discretize_path(i) ...
python
def log(self, n=None, **kwargs): """ Run the repository log command Returns: str: output of log command (``git log -n <n> <--kwarg=value>``) """ kwargs['format'] = kwargs.pop('template', self.template) cmd = ['git', 'log'] if n: cmd.append...
java
@Override public void absolute(final int localPointer) { if (localPointer < 0 || localPointer >= rows.size()) { throw new IndexOutOfBoundsException("INVALID POINTER LOCATION: " + localPointer); } pointer = localPointer; currentRecord = new RowRecord(rows.get(point...
java
public static void setDevelopmentMode(boolean enable) { if (TraceComponent.isAnyTracingEnabled() && ejbTc.isDebugEnabled()) Tr.debug(ejbTc, "setDevelopmentMode : " + enable); svDevelopmentMode = enable; }
java
public int getNumberOfOutputGroupVertices() { int retVal = 0; final Iterator<ManagementGroupVertex> it = this.groupVertices.iterator(); while (it.hasNext()) { if (it.next().isOutputVertex()) { ++retVal; } } return retVal; }
java
public Set<String> postProcessingFields() { Set<String> fields = new LinkedHashSet<>(); must.forEach(condition -> fields.addAll(condition.postProcessingFields())); should.forEach(condition -> fields.addAll(condition.postProcessingFields())); return fields; }
python
def unit_poly_verts(theta): """Return vertices of polygon for subplot axes. This polygon is circumscribed by a unit circle centered at (0.5, 0.5) """ x0, y0, r = [0.5] * 3 verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] return verts
java
private int append(FA add) { int relocation; int idx; relocation = used; ensureCapacity(used + add.used); for (idx = 0; idx < add.used; idx++) { states[relocation + idx] = new State(add.states[idx], relocation); } used += add.used; ...
python
def has_path(nodes, A, B): r"""Test if nodes from a breadth_first_order search lead from A to B. Parameters ---------- nodes : array_like Nodes from breadth_first_oder_seatch A : array_like The set of educt states B : array_like The set of product states Returns...
java
public List<T> elementList() { if (m_cache != null) { return m_cache; } if (m_relativeOrdered) { List<T> objectList = new ArrayList<T>(); Iterator<CmsIdObjectElement<T>> itObjs = m_orderedObjectList.iterator(); while (itObjs.hasNext()) { ...
python
def do_get(self, uri): """Helps to make get requests Args: uri: URI of the resource Returns: Returns: Returns the resource data """ self.validate_resource_uri(uri) return self._connection.get(uri)
java
public static String getCanonicalSMILESForPolymer(PolymerNotation polymer) throws BuilderMoleculeException, HELM2HandledException, CTKSmilesException, CTKException, NotationException, ChemistryException { AbstractMolecule molecule = BuilderMolecule.buildMoleculefromSinglePolymer(polymer).getMolecule(); molecu...
java
@Override public boolean setPortletPreferences(List<IPortletPreference> portletPreferences) { if (portletPreferences == null) { final boolean modified = !this.portletPreferences.isEmpty(); this.portletPreferences.clear(); return modified; } final boolean ...
python
def get_hidden_members(self, user=None): """Get the members that you do not have permission to view. Returns: List of members hidden based on their permission preferences """ hidden_members = [] for member in self.members.all(): show = False if member.ca...
java
@Override public CommerceAddressRestriction findByC_C_Last(long classNameId, long classPK, OrderByComparator<CommerceAddressRestriction> orderByComparator) throws NoSuchAddressRestrictionException { CommerceAddressRestriction commerceAddressRestriction = fetchByC_C_Last(classNameId, classPK, orderByCompara...
python
def multi_split(txt, delims): """ split by multiple delimiters """ res = [txt] for delimChar in delims: txt, res = res, [] for word in txt: if len(word) > 1: res += word.split(delimChar) return res
java
private void obtainScaledEdge(@NonNull final TypedArray typedArray) { int defaultValue = Edge.VERTICAL.getValue(); Edge scaledEdge = Edge.fromValue( typedArray.getInt(R.styleable.SquareImageView_scaledEdge, defaultValue)); setScaledEdge(scaledEdge); }
java
public static void escapeAndWriteDelimitedColumn(String str, char delimiter, Writer writer) throws IOException { if (str == null) { escapeAndWriteDelimitedColumn("NULL", delimiter, writer); } else if (containsNone(str, SEARCH_CHARS) && str.indexOf(delimiter) < 0) { wr...
python
def _start_execution(self, args, stdin, stdout, stderr, env, cwd, temp_dir, cgroups, parent_setup_fn, child_setup_fn, parent_cleanup_fn): """Actually start the tool and the measurements. @param parent_setup_fn a function without parameters that is called in the parent process ...
java
public static route[] get(nitro_service service, options option) throws Exception{ route obj = new route(); route[] response = (route[])obj.get_resources(service,option); return response; }
java
public final void finishTransliteration(Replaceable text, Position index) { index.validate(text.length()); filteredTransliterate(text, index, false, true); }
python
def calculate_overlap(self): """Create the array that describes how junctions overlap""" overs = [] if not self.tx_obj1.range.overlaps(self.tx_obj2.range): return [] # if they dont overlap wont find anything for i in range(0,len(self.j1)): for j in range(0,len(self.j2)): if sel...
python
def focusOutEvent(self, event): """ The default 'focusOutEvent' implementation. """ widget = self.widget type(widget).focusOutEvent(widget, event) self.declaration.focus_lost()
java
public Observable<StorageAccountInfoInner> getStorageAccountAsync(String resourceGroupName, String accountName, String storageAccountName) { return getStorageAccountWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName).map(new Func1<ServiceResponse<StorageAccountInfoInner>, StorageAccount...
java
private void fillDetailMimetypes(CmsListItem item, String detailId) { CmsSearchManager searchManager = OpenCms.getSearchManager(); StringBuffer html = new StringBuffer(); String doctypeName = (String)item.get(LIST_COLUMN_NAME); CmsSearchDocumentType docType = searchManager.getDocumentT...
java
@Override public com.liferay.commerce.wish.list.model.CommerceWishList getCommerceWishListByUuidAndGroupId( String uuid, long groupId) throws com.liferay.portal.kernel.exception.PortalException { return _commerceWishListLocalService.getCommerceWishListByUuidAndGroupId(uuid, groupId); }
java
public boolean connectIfPossible( MonitoringPoint monitoringPoint ) { // check if the other point has this as related id if (ID == monitoringPoint.getRelatedID()) { pfafRelatedMonitoringPointsTable.put(monitoringPoint.getPfatstetterNumber().toString(), monitoringPoint); ...
python
def download(date_array, tag, sat_id, data_path, user=None, password=None): """ Download SuperDARN data from Virginia Tech organized for loading by pysat. """ import sys import os import pysftp import davitpy if user is None: user = os.environ['DBREADUSER'] if password...
python
def getall(self, table): """ Get all rows values for a table """ try: self._check_db() except Exception as e: self.err(e, "Can not connect to database") return if table not in self.db.tables: self.warning("The table " + tabl...
java
@Deprecated public static SelectColumn createExcludes(String[] cols, String... columns) { return new SelectColumn(Utility.append(cols, columns), true); }
java
@Deprecated public static <I extends Request, O extends Response> Function<Client<I, O>, LoggingClient<I, O>> newDecorator(LogLevel level) { return delegate -> new LoggingClient<>(delegate, level); }
python
def delete_service_certificate(kwargs=None, conn=None, call=None): ''' .. versionadded:: 2015.8.0 Delete a specific certificate associated with the service CLI Examples: .. code-block:: bash salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\ thum...
java
public static String concat(Object... params) { StringBuffer finalMessage = new StringBuffer(); for (Object object : params) { finalMessage.append(JKObjectUtil.toString(object, true)); } return finalMessage.toString(); }
java
public final String getJmsType() { if (getHdr2().getChoiceField(JsHdr2Access.JMSTYPE) == JsHdr2Access.IS_JMSTYPE_EMPTY) { return getDerivedJmsType(); } else { return (String) getHdr2().getField(JsHdr2Access.JMSTYPE_DATA); } }
python
def init_config(self, app): """Initialize config.""" app.config.setdefault( 'LOGGING_FS_LEVEL', 'DEBUG' if app.debug else 'WARNING' ) for k in dir(config): if k.startswith('LOGGING_FS'): app.config.setdefault(k, getattr(config, k)) ...
python
def skip_whitespace(self): """Consume input until a non-whitespace character is encountered. The non-whitespace character is then ungotten, and the number of whitespace characters consumed is returned. If the tokenizer is in multiline mode, then newlines are whitespace. @rtype...
java
public static Pair<AlluxioConfiguration, PathConfiguration> loadClusterAndPathDefaults( InetSocketAddress address, AlluxioConfiguration clusterConf, PathConfiguration pathConf) throws AlluxioStatusException { if (shouldLoadClusterConfiguration(clusterConf)) { GetConfigurationPResponse response = l...
python
def login(self, role, jwt, subscription_id=None, resource_group_name=None, vm_name=None, vmss_name=None, use_token=True, mount_point=DEFAULT_MOUNT_POINT): """Fetch a token. This endpoint takes a signed JSON Web Token (JWT) and a role name for some entity. It verifies the JWT signature ...
python
def __initialize_ui(self): """ Initializes the Widget ui. """ self.setAutoScroll(True) self.setSelectionMode(QAbstractItemView.ExtendedSelection) self.setIndentation(self.__tree_view_indentation) self.setDragDropMode(QAbstractItemView.DragOnly) self.setHe...
java
public static void trackTrustedMultifactorAuthenticationAttribute( final Authentication authn, final String attributeName) { val newAuthn = DefaultAuthenticationBuilder.newInstance(authn) .addAttribute(attributeName, Boolean.TRUE) .build(); LOGGER.debug("Updated ...
java
public static Grid getInstance(String configFile, String propertiesFile) throws InterruptedException { return getInstance(configFile == null ? null : new FileSystemResource(configFile), propertiesFile); }
python
def _determine_monetary_account_id(cls, monetary_account_id=None): """ :type monetary_account_id: int :rtype: int """ if monetary_account_id is None: return context.BunqContext.user_context().primary_monetary_account.id_ return monetary_account_id
java
protected boolean contains(CmsPublishJobInfoBean publishJob) { List<CmsPublishJobInfoBean> l = OpenCms.getMemoryMonitor().getAllCachedPublishJobs(); if (l != null) { for (int i = 0; i < l.size(); i++) { CmsPublishJobInfoBean b = l.get(i); if (b == publishJob)...
python
def _end_channel(self, channel): """ Soft end of ssh channel. End the writing thread as soon as the message queue is empty. """ self.stop_on_empty_queue[channel] = True # by joining the we wait until its loop finishes. # it won't loop forever since we've set self.stop_on...
python
def parse_cell(self, cell, coords, cell_mode=CellMode.cooked): """Parses a cell according to its cell.value_type.""" # pylint: disable=too-many-return-statements if cell_mode == CellMode.cooked: if cell.covered or cell.value_type is None or cell.value is None: return None vtype = cell.v...
python
def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) ...
java
@Override protected void closeJedisCommands(JedisCommands jedisCommands) { if (jedisCommands instanceof Jedis) { ((Jedis) jedisCommands).close(); } else throw new IllegalArgumentException("Argument is not of type [" + Jedis.class + "]!"); }
java
public static double updateDouble(double value, double range) { range = range == 0 ? 0.1 * value : range; double min = value - range; double max = value + range; return nextDouble(min, max); }
java
void removeHandler( Object handlerRegistration ) { // Through object's interface implementation if( handlerRegistration instanceof DirectHandlerInfo ) { DirectHandlerInfo info = (DirectHandlerInfo) handlerRegistration; info.source.removePropertyChangedHandler( info.registrationObject ); return; } ...
java
public double getSquaredDistance(final DBIDRef id1, final DBIDRef id2) { final int o1 = idmap.getOffset(id1), o2 = idmap.getOffset(id2); return kernel[o1][o1] + kernel[o2][o2] - 2 * kernel[o1][o2]; }