language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void unsetLogHandler(String id, LogHandler ref) { if (id != null) { if (ref == null) { logHandlerServices.remove(id); } else { logHandlerServices.remove(id, ref); } } }
python
def multiplexer(f=None, nruns=1, nprocs=1, seeding=None, **args): """Evaluate a function for different parameters, optionally in parallel. Parameters ---------- f: function function f to evaluate, must take only kw arguments as inputs nruns: int number of evaluations of f for each...
java
public static service_dospolicy_binding[] get(nitro_service service, String name) throws Exception{ service_dospolicy_binding obj = new service_dospolicy_binding(); obj.set_name(name); service_dospolicy_binding response[] = (service_dospolicy_binding[]) obj.get_resources(service); return response; }
python
def extract_values(self, possible_solution, use_defaults=False): """Returns a tuple of the values that pertain to this constraint. It simply filters all values to by the variables this constraint uses. """ defaults = self._vardefaults if use_defaults else {} values = list(self._...
python
def record(viewWidget): """ Records the state for the inputed view widget into data. :param viewWidget | <XViewWidget> """ profile = XViewProfile() xprofile = ElementTree.Element('profile') xprofile.set('locked', nativestring(viewWidget.isLo...
python
def put_path(self, url, path): """Puts a resource already on disk into the disk cache. Args: url: The original url of the resource path: The resource already available on disk Raises: CacheError: If the file cannot be put in cache """ cache_p...
java
public final Integer getInt(final String pNm) throws ExceptionWithCode { if (this.ints != null && this.ints.keySet().contains(pNm)) { return this.ints.get(pNm); } if (this.idInts != null && this.idInts.keySet().contains(pNm)) { return this.idInts.get(pNm); } throw new ExceptionWithCode(E...
python
def atexit(self): """Stop profiling and print profile information to sys.stderr. This function is registered as an atexit hook. """ funcname = self.fn.__name__ filename = self.fn.__code__.co_filename lineno = self.fn.__code__.co_firstlineno print("") prin...
python
def GetEntries( self, parser_mediator, cookie_data=None, url=None, **kwargs): """Extracts event objects from the cookie. Args: parser_mediator (ParserMediator): parser mediator. cookie_data (str): cookie data. url (str): URL or path where the cookie got set. """ fields = cookie_...
java
private void addSuperBlockStart(int pc) { if (GenerateStackMap) { if (itsSuperBlockStarts == null) { itsSuperBlockStarts = new int[SuperBlockStartsSize]; } else if (itsSuperBlockStarts.length == itsSuperBlockStartsTop) { int[] tmp = new int[itsSuperBlockSt...
java
static DocumentFeatureGenerator createGenerator(Element generatorElement, FeatureGeneratorResourceProvider resourceManager) throws InvalidFormatException { String elementName = generatorElement.getTagName(); XmlFeatureGeneratorFactory generatorFactory = factories.get(elementName); if (generatorFact...
python
def eventgroups(ctx, sport): """ [bookie] List event groups for a sport :param str sport: Sports id """ sport = Sport(sport, peerplays_instance=ctx.peerplays) click.echo(pretty_print(sport.eventgroups, ctx=ctx))
java
public void visit(final WebAppErrorPage webAppErrorPage) { NullArgumentException.validateNotNull(webAppErrorPage, "Web app error page"); try { webContainer.registerErrorPage(webAppErrorPage.getError(), webAppErrorPage.getLocation(), httpContext); //CHECKSTYLE:OFF } catch (Exception ignore) {...
python
def init_argparser_source_registry( self, argparser, default=None, help=( 'comma separated list of registries to use for gathering ' 'JavaScript sources from the given Python packages' )): """ For setting up the source registry flag. """ ...
java
private void listTrackers() throws IOException { ClusterStatus fullStatus = jobSubmitClient.getClusterStatus(true); Collection<TaskTrackerStatus> trackers = fullStatus.getTaskTrackersDetails(); Set<String> activeTrackers = new HashSet<String>(fullStatus.getActiveTrackerNames()); ...
python
def filter_by_attrs(self, **kwargs): """Returns a ``Dataset`` with variables that match specific conditions. Can pass in ``key=value`` or ``key=callable``. A Dataset is returned containing only the variables for which all the filter tests pass. These tests are either ``key=value`` for ...
python
def keepvol_on_destroy(name, kwargs=None, call=None): ''' Do not delete all/specified EBS volumes upon instance termination CLI Example: .. code-block:: bash salt-cloud -a keepvol_on_destroy mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The keepvol...
python
def inclusion_tag(self, name, context_class=Context, takes_context=False): """ Replacement for Django's ``inclusion_tag`` which looks up device specific templates at render time. """ def tag_decorator(tag_func): @wraps(tag_func) def tag_wrapper(parser, to...
java
@Override public Integer getInteger(final String key, final Integer defaultValue) { try { String value = get(key); if (value == null) { return defaultValue; } return Integer.valueOf(value); } catch (NumberFormatException ex) { throw new ConversionException(ex); } }
python
def print_clusters(fastas, info, ANI): """ choose represenative genome and print cluster information *if ggKbase table is provided, use SCG info to choose best genome """ header = ['#cluster', 'num. genomes', 'rep.', 'genome', '#SCGs', '#SCG duplicates', \ 'genome size (bp)', 'fragm...
python
def update(self, byts): ''' Update all the hashes in the set with the given bytes. ''' self.size += len(byts) [h[1].update(byts) for h in self.hashes]
python
def _load_file(self): """Load all entries from json backing file """ if not os.path.exists(self.file): return {} with open(self.file, "r") as infile: data = json.load(infile) return data
java
public final List<SequenceLabel> getSequencesFromSpans(final String[] tokens, final Span[] seqSpans) { final List<SequenceLabel> sequences = new ArrayList<SequenceLabel>(); for (final Span seqSpan : seqSpans) { final String seqString = seqSpan.getCoveredText(tokens); final String seqType = seq...
python
def get_data_files(top): """Get data files""" data_files = [] ntrim = len(here + os.path.sep) for (d, _, filenames) in os.walk(top): data_files.append(( d[ntrim:], [os.path.join(d, f) for f in filenames] )) return data_files
python
def com_google_fonts_check_description_broken_links(description): """Does DESCRIPTION file contain broken links?""" from lxml.html import HTMLParser import defusedxml.lxml import requests doc = defusedxml.lxml.fromstring(description, parser=HTMLParser()) broken_links = [] for link in doc.xpath('//a/@href'...
python
def add_option(self, section, option, value=None): """ Creates an option for a section. If the section does not exist, it will create the section. """ # check if section exists; create if not if not self.config.has_section(section): message = self.add_section(...
python
def random(args): """ %prog random fasta 100 > random100.fasta Take number of records randomly from fasta """ from random import sample p = OptionParser(random.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastafile, N = args ...
java
public void parseAndSetParameter(final String value, final ModelNode operation, final XMLStreamReader reader) throws XMLStreamException { ModelNode paramVal = parse(value, reader); operation.get(getName()).set(paramVal); }
python
def _infer_fused_data_format(self, input_batch): """Infers the data format for the fused batch norm. It uses the axis option to infer this information. Specifically, the axis value (0, 1, 2) corresponds to data format NHWC and the axis value (0, 2, 3) to data format NCHW. Args: input_batch: ...
java
private FileStatus getFileStatus(FTPFile ftpFile, Path parentPath) { long length = ftpFile.getSize(); boolean isDir = ftpFile.isDirectory(); int blockReplication = 1; // Using default block size since there is no way in FTP client to know of // block sizes on server. The assumption could be less tha...
java
public IPv6AddressSection intersect(IPv6AddressSection other) throws SizeMismatchException { return intersect(this, other, getAddressCreator(), this::getSegment, other::getSegment); }
python
def add(self, docs, boost=None, fieldUpdates=None, commit=None, softCommit=False, commitWithin=None, waitFlush=None, waitSearcher=None, overwrite=None, handler='update'): """ Adds or updates documents. Requires ``docs``, which is a list of dictionaries. Each key is the field...
java
public static void setupTracingConfig() { List<String> descriptors = new ArrayList<>(); addDescriptor(descriptors, BigtableTableAdminGrpc.getServiceDescriptor()); addDescriptor(descriptors, BigtableGrpc.getServiceDescriptor()); Tracing.getExportComponent().getSampledSpanStore().registerSpanNamesForColl...
java
public static String display(Object object) { StringBuilder builder = new StringBuilder(); displayRecursive(object, builder, new Stack<>(), false); return builder.toString(); }
python
def list_domains(): ''' Return a list of the salt_id names of all available Vagrant VMs on this host without regard to the path where they are defined. CLI Example: .. code-block:: bash salt '*' vagrant.list_domains --log-level=info The log shows information about all known Vagrant e...
java
public double[] rotate(double[] vector) { DenseMatrix64F transformed = new DenseMatrix64F(1, vector.length); DenseMatrix64F original = DenseMatrix64F.wrap(1, vector.length, vector); CommonOps.mult(original, randomMatrix, transformed); return transformed.getData(); }
python
def get_config(): """ Gets the config from the os.environ. This is used to create the config dict for use by the ORM :return: str, dict """ db_type = os.environ['DB_TYPE'] db_host = os.environ['DB_HOST'] db_user = os.environ['DB_USER'] db_database = os.env...
java
public static JSONObject getJSONFromUrlViaPOST(String url, List<NameValuePair> params) { InputStream is = null; JSONObject jObj = null; String json = ""; // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClie...
java
public PagedList<ResourceMetricInner> listWorkerPoolInstanceMetricsNext(final String nextPageLink) { ServiceResponse<Page<ResourceMetricInner>> response = listWorkerPoolInstanceMetricsNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<ResourceMetricInner>(response.body()) { ...
python
def set_mrt(self, s, mrt: str): """ accepts a statement and adds a qualifer setting the mrt modifies s in place :param s: a WDBaseDataType statement :param mrt: one of {'close', 'broad', 'exact', 'related', 'narrow'} :return: s """ valid_mrts_abv = self.AB...
java
public static byte getDataTypeAsByte(@NonNull org.nd4j.linalg.api.buffer.DataType type) { switch (type) { case FLOAT: return DataType.FLOAT; case DOUBLE: return DataType.DOUBLE; case HALF: return DataType.HALF; case ...
python
def make_cache_key(custom_kbs_files=None): """Create cache key for kbs caches instances This function generates a unique key for a given set of arguments. The files dictionary is transformed like this: {'journal': '/var/journal.kb', 'books': '/var/books.kb'} to "journal=/var/journal.kb;books=/...
python
def get_ordering_field_columns(self): """ Returns an OrderedDict of ordering field column numbers and asc/desc """ # We must cope with more than one column having the same underlying # sort field, so we base things on column numbers. ordering = self._get_default_ordering...
java
public final Map<String, Set<HierarchicalProperty>> getPropStats() throws RepositoryException { String statname = WebDavConst.getStatusDescription(HTTPStatus.OK); if (propNames == null) { propStats.put(statname, resource.getProperties(namesOnly)); } else { ...
java
public <T extends ICalProperty> boolean removeProperty(T property) { return properties.remove(property.getClass(), property); }
java
public void passMessage( JunctionTreeClique sourceClique, JunctionTreeSeparator sep, JunctionTreeClique targetClique) { double[] sepPots = separatorStates[sep.getId()].getPotentials(); double[] oldSepPots = Arrays.copyOf(sepPots, sepPots.length); BayesVariable[] sepVars = sep.getValues().toArra...
python
def MakePmfFromCdf(cdf, name=None): """Makes a normalized Pmf from a Cdf object. Args: cdf: Cdf object name: string name for the new Pmf Returns: Pmf object """ if name is None: name = cdf.name pmf = Pmf(name=name) prev = 0.0 for val, prob in cdf.Items...
java
public AssessmentRun withUserAttributesForFindings(Attribute... userAttributesForFindings) { if (this.userAttributesForFindings == null) { setUserAttributesForFindings(new java.util.ArrayList<Attribute>(userAttributesForFindings.length)); } for (Attribute ele : userAttributesForFindi...
java
private MessageType getReadSchema(MessageType fileSchema, Path filePath) { RowTypeInfo fileTypeInfo = (RowTypeInfo) ParquetSchemaConverter.fromParquetType(fileSchema); List<Type> types = new ArrayList<>(); for (int i = 0; i < fieldNames.length; ++i) { String readFieldName = fieldNames[i]; TypeInformation<?>...
java
public static RequestConfig buildRequestConfig(PackageManagerProperties props) { return RequestConfig.custom() .setConnectTimeout(props.getHttpConnectTimeoutSec() * (int)DateUtils.MILLIS_PER_SECOND) .setSocketTimeout(props.getHttpSocketTimeoutSec() * (int)DateUtils.MILLIS_PER_SECOND) .build(...
python
def is_absolute(self): """Return True if xllcorner==yllcorner==0 indicating that points in question are absolute. """ # FIXME(Ole): It is unfortunate that decision about whether points # are absolute or not lies with the georeference object. Ross pointed this out. # More...
java
public static ConfigSourceName configSourceNamed(final String name) { checkNotNull(name); return new ConfigSourceName() { @Override public String toString() { return name; } @Override public String name() { r...
python
def projection(self, axis): """Sums all data along all other axes, then return Hist1D""" axis = self.get_axis_number(axis) projected_hist = np.sum(self.histogram, axis=self.other_axes(axis)) return Hist1d.from_histogram(projected_hist, bin_edges=self.bin_edges[axis])
python
def benchmark_forward(self): """Benchmark forward execution. """ self._setup() def f(): self._forward() self.mod_ext.synchronize(**self.ext_kwargs) f() # Ignore first self.forward_stat = self._calc_benchmark_stat(f)
python
def _getSuperFunc(self, s, func): """Return the the super function.""" return getattr(super(self.cls(), s), func.__name__)
java
public SDVariable sub(SDVariable x) { return sub(sameDiff.generateNewVarName(SubOp.OP_NAME,0),x); }
java
private void setField(Row row, Table schemaTable, Object embeddedObject, Attribute embeddedAttrib) { Field field = (Field) embeddedAttrib.getJavaMember(); FieldDef fieldDef = schemaTable.getField(((AbstractAttribute) embeddedAttrib).getJPAColumnName()); Object valueObj = PropertyAccessorHel...
python
def ask_folder(message=None, version=None, defaultLocation=None, dialogOptionFlags=None, location=None, clientName=None, windowTitle=None, actionButtonLabel=None, cancelButtonLabel=None, preferenceKey=None, popupExtension=None, eventProc=None, filterProc=None, wanted=None, multiple=None): """Original doc: Display a...
java
public List<ClassDoc> implementingclasses(ClassDoc cd) { List<ClassDoc> result = get(implementingclasses, cd); List<ClassDoc> subinterfaces = allSubs(cd, false); //If class x implements a subinterface of cd, then it follows //that class x implements cd. Iterator<ClassDoc> implem...
java
public MethodParamsType<T> methodParam(String ... values) { if (values != null) { for(String name: values) { childNode.createChild("method-param").text(name); } } return this; }
java
public static char[] addToCharArray(char[] a, char value) { if(a == null || a.length == 0) { return new char[] {value}; } char[] array = new char[a.length + 1]; array[a.length] = value; return array; }
python
def enable_windows_virtual_terminal_sequences(): """ Sets the appropriate flags to enable virtual terminal sequences in a Windows command prompt. Reference: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences """ try: from ctypes import windll, byref ...
python
def parse(url): """Parses a search URL.""" config = {} url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] if url.scheme in SCHEMES: config["ENGINE"] = SCHEMES[url.scheme] if url.scheme in USES_URL: config["URL"] = ur...
python
def get_time_estimator(total): """Given a total amount of items to compute, return a function that, if called every time an item is computed (or every step items are computed) will give a time estimation for how long it will take to compute the whole set of itmes. The function will return two values: th...
python
def _correctly_load_bbox(bbox, path, is_zipped=False): """ Helper method for loading old version of pickled BBox object :param bbox: BBox object which was incorrectly loaded with pickle :type bbox: sentinelhub.BBox :param path: Path to file where BBox object is stored :typ...
python
def resolver( expr, safe=DEFAULT_SAFE, tostr=DEFAULT_TOSTR, scope=DEFAULT_SCOPE, besteffort=DEFAULT_BESTEFFORT ): """Resolve input expression. This function is given such as template resolution function. For wrapping test for example. :param str expr: configuration expression to resolv...
java
public static void write(OutputStream out, boolean isCloseOut, byte[] content) throws IORuntimeException { try { out.write(content); } catch (IOException e) { throw new IORuntimeException(e); } finally { if (isCloseOut) { close(out); } } }
python
def conditional_entropy(data, precision, min_period, max_period, xbins=10, ybins=5, period_jobs=1): """ Returns the period of *data* by minimizing conditional entropy. See `link <http://arxiv.org/pdf/1306.6664v2.pdf>`_ [GDDMD] for details. **Parameters** data : array-like, ...
java
public static MarkedElement markup(IRenderingElement elem, String... classes) { assert elem != null; MarkedElement tagElem = new MarkedElement(elem); for (String cls : classes) tagElem.aggClass(cls); return tagElem; }
java
public static final Promise resolve() { return new Promise(CompletableFuture.completedFuture(new Tree((Tree) null, null, null))); }
python
def shutdown(self, collector, success): """Shutdown of the application.""" self.event.delegate(success) if collector is not None: collector.queue.put(None) collector.join() if not success: sys.exit(1)
java
Object invokeConstructor(Class<?>[] parameterTypes, Object[] parameters) throws InvocationException { try { Constructor<?> con = classType.getConstructor(parameterTypes); return con.newInstance(parameters); } catch (NoSuchMethodException e) { throw new InvocationExce...
python
def native(self): """ The native Python datatype representation of this value :return: An integer or None """ if self.contents is None: return None if self._native is None: extra_bits = int_from_bytes(self.contents[0:1]) ...
python
def triangle(self, x1, y1, x2, y2, x3, y3, color): """ See the Processing function triangle(): https://processing.org/reference/triangle_.html """ self.context.set_source_rgb(*color) self.context.move_to(self.tx(x1), self.ty(y1)) self.context.line_to(self.tx(x2), ...
python
def run_analysis(self, argv): """Run this analysis""" args = self._parser.parse_args(argv) if not HAVE_ST: raise RuntimeError( "Trying to run fermipy analysis, but don't have ST") workdir = os.path.dirname(args.config) _config_file = self._clone_conf...
python
def _output_work(self, work, root): """Saves the TEI XML document `root` at the path `work`.""" output_filename = os.path.join(self._output_dir, work) tree = etree.ElementTree(root) tree.write(output_filename, encoding='utf-8', pretty_print=True)
python
def has_permission(self, request, view): """ applies to social-link-list """ if request.method == 'POST': user = Profile.objects.only('id', 'username').get(username=view.kwargs['username']) return request.user.id == user.id return True
java
public static ObjectMapper configure(ObjectMapper objectMapper) { objectMapper.registerModule(INSTANCE); objectMapper.setHandlerInstantiator(new MongoJacksonHandlerInstantiator( new MongoAnnotationIntrospector(objectMapper.getDeserializationConfig()))); return objectMapper; }
java
public static List<CommerceWarehouseItem> findByCPI_CPIU(long CProductId, String CPInstanceUuid, int start, int end) { return getPersistence() .findByCPI_CPIU(CProductId, CPInstanceUuid, start, end); }
java
public boolean isContainedBy(PermissionScope s) { if (this==s) return true; for (PermissionScope c : containers) { if (c.isContainedBy(s)) return true; } return false; }
java
private List<Enum> getSelectableEnumsList(FormModel formModel, String formPropertyPath, Map context) { List<Enum> out = new ArrayList<Enum>(); Boolean nullable; if (context.containsKey(NULLABLE_KEY)) { nullable = (Boolean) context.get(NULLABLE_KEY); } else { nullable = this.nullable; } if (nullable...
python
def make_context(self, docker_file=None): """Determine the docker lines for this image""" kwargs = {"silent_build": self.harpoon.silent_build, "extra_context": self.commands.extra_context} if docker_file is None: docker_file = self.docker_file with ContextBuilder().make_conte...
python
def load(css_url=None, js_url=None, serve_local=False): """Load share.js resources. :param css_url: if set, will be used as css url. :param js_url: if set, will be used as js url. :param serve_local: if set to True, the local resource will be used. """ if serve_local or ...
java
public static List<String> findIndexNames(final String root) throws IOException, URISyntaxException { if (root == null) { return findIndexNames(); } logger.debug("Looking for indices in classpath under [{}].", root); final List<String> indexNames = new ArrayList<>(); ...
python
def cumulative_statistics(self): """ Access the cumulative_statistics :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatistics...
java
public static SymbolToken symbol(final String name, final int val) { if (name == null) { throw new NullPointerException(); } if (val <= 0) { throw new IllegalArgumentException("Symbol value must be positive: " + val); } return new SymbolToken() { public String getText() ...
python
def get_channel_property_names(self, channel_id=None): '''Get a list of property names for a given channel, or for all channels if channel_id is None Parameters ---------- channel_id: int The channel id for which the property names will be returned If None (defau...
python
def setup(self, config_file=None, aws_config=None, gpg_config=None, decrypt_gpg=True, decrypt_kms=True): """Make setup easier by providing a constructor method. Move to config_file File can be located with a filename only, relative path, or absolute path. If only name or r...
python
def convert_op(self, op): """ Converts NeuroML arithmetic/logical operators to python equivalents. @param op: NeuroML operator @type op: string @return: Python operator @rtype: string """ if op == '.gt.': return '>' elif op == '.ge....
java
@SuppressWarnings("unchecked") private boolean isMethodAlreadyInjectedAnnotationPresent(MethodNode methodNode) { AnnotationNode injectedTraceAnnotation = getAnnotation(INJECTED_TRACE_TYPE.getDescriptor(), methodNode.visibleAnnotations); AnnotationNode manualTraceAnnotation = getAnnotation(MANUAL_TRA...
python
def nics_skip(name, nics, ipv6): ''' Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>` ''' return nics_skipped(name, nics=nics, ipv6=ipv6)
python
def write(self, fptr): """Write a Component Mapping box to file. """ length = 8 + 4 * len(self.component_index) write_buffer = struct.pack('>I4s', length, b'cmap') fptr.write(write_buffer) for j in range(len(self.component_index)): write_buffer = struct.pack(...
java
private void setState(State state) { if (this.state != state) { this.state = state; LOGGER.debug("State changed: {}", state); changeListeners.forEach(l -> l.accept(state)); } }
java
private ConcurrentManaged<T> newManaged() { return ConcurrentManaged.newManaged(async, caller, managedOptions, setup, teardown); }
java
public void removeAllEntities(Family family) { boolean delayed = updating || familyManager.notifying(); entityManager.removeAllEntities(getEntitiesFor(family), delayed); }
java
public Effects slideToggle(Function... f) { return as(Effects).slideToggle(Speed.DEFAULT, f); }
java
public void setFrequencyCapBehavior(com.google.api.ads.admanager.axis.v201902.FrequencyCapBehavior frequencyCapBehavior) { this.frequencyCapBehavior = frequencyCapBehavior; }
python
def setSpeedDeviation(self, typeID, deviation): """setSpeedDeviation(string, double) -> None Sets the maximum speed deviation of vehicles of this type. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_SPEED_DEVIATION, typeID, deviation)
java
private int getCornersAverage() { int total = 0; for (int i : _foreground_values) { total += Utility.ConvertDp(i); } return total / _foreground_values.length; }
python
def rgb2rgba(rgb): """Take a row of RGB bytes, and convert to a row of RGBA bytes.""" rgba = [] for i in range(0, len(rgb), 3): rgba += rgb[i:i+3] rgba.append(255) return rgba