language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def norm_to_uniform(im, scale=None): r""" Take an image with normally distributed greyscale values and converts it to a uniform (i.e. flat) distribution. It's also possible to specify the lower and upper limits of the uniform distribution. Parameters ---------- im : ND-image The im...
java
@Override public final void close(@NotNull Throwable e) { if (isProcessComplete()) return; processComplete = true; doClose(e); processCompletion.trySetException(e); afterProcess(e); }
python
def parse_stage_name(stage): """ Determine the name of a stage. The stage may be provided already as a name, as a Stage object, or as a callable with __name__ (e.g., function). :param str | pypiper.Stage | function stage: Object representing a stage, from which to obtain name. :return ...
python
def getThroughput(self, instId: int) -> float: """ Return the throughput of the specified instance. :param instId: the id of the protocol instance """ # We are using the instanceStarted time in the denominator instead of # a time interval. This is alright for now as all ...
python
def ply_ascii(elements, file_obj): """ Load data from an ASCII PLY file into an existing elements data structure. Parameters ------------ elements: OrderedDict object, populated from the file header. object will be modified to add data by this function. file_obj: open file object...
python
def _raise_or_extract(self, response): """ Raises an exception if the response indicates an API error. Otherwise returns the object at the 'data' key of the API response. """ try: data = response.json() except ValueError: raise JoeException("The ...
java
public static boolean isSymbolicLink(File file) throws IOException { // first try using Java 7 try { // use reflection here Class<?> filesClass = Class.forName("java.nio.file.Files"); Class<?> pathClass = Class.forName("java.nio.file.Path"); Object path = File.class.getMethod("toPath").i...
java
@SuppressWarnings("unchecked") public static boolean dispatchable(Object obj) { if (obj == null) { return false; } return obj instanceof PrettyLoggable || obj instanceof Map || obj instanceof Dictionary || obj instanceof Iterable || obj.getClass().isArray(); }
java
public int getWhatToShow(int opPos) { int axesType = getOp(opPos); int testType = getOp(opPos + 3); // System.out.println("testType: "+testType); switch (testType) { case OpCodes.NODETYPE_COMMENT : return DTMFilter.SHOW_COMMENT; case OpCodes.NODETYPE_TEXT : // return DTMFilter...
java
public static <T> Collector<T, ?, Optional<T>> onlyOne(Predicate<? super T> predicate) { return filtering(predicate, onlyOne()); }
python
def load_table(filename): """ Load a table from a given file. Supports csv, tab, tex, vo, vot, xml, fits, and hdf5. Parameters ---------- filename : str File to read Returns ------- table : Table Table of data. """ supported = get_table_formats() fmt =...
python
def log_into(self, target, before_priv_drop=True): """Simple file or UDP logging. .. note:: This doesn't require any Logger plugin and can be used if no log routing is required. :param str|unicode target: Filepath or UDP address. :param bool before_priv_drop: Whether to lo...
python
def file_crc32(filename, chunksize=_CHUNKSIZE): """ calculate the CRC32 of the contents of filename """ check = 0 with open(filename, 'rb') as fd: for data in iter(lambda: fd.read(chunksize), ""): check = crc32(data, check) return check
python
def is_interior(self, node): # TODO: check docstring """Returns True if node is interior to the route, i.e., not adjascent to depot Parameters ---------- nodes : type Desc Returns ------- bool True if node is i...
java
public String getDirectConnectionCipherSuite() { if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){ checkRequestObjectInUse(); } Class<? extends IRequest> requestClass = _request.getClass(); String cipherSuite = null; if(checkAssignableFromIRequestImpl(requestClass...
python
def get_qcontent(value): """qcontent = qtext / quoted-pair We allow anything except the DQUOTE character, but if we find any ASCII other than the RFC defined printable ASCII an NonPrintableDefect is added to the token's defects list. Any quoted pairs are converted to their unquoted values, so what...
java
public ProxyDataSourceBuilder autoRetrieveGeneratedKeys(boolean autoClose, ResultSetProxyLogicFactory factory) { this.autoRetrieveGeneratedKeys = true; this.autoCloseGeneratedKeys = autoClose; this.generatedKeysProxyLogicFactory = factory; return this; }
python
def be_array_from_bytes(fmt, data): """ Reads an array from bytestring with big-endian data. """ arr = array.array(str(fmt), data) return fix_byteorder(arr)
java
private void initializeProjective3(FastQueue<AssociatedTriple> associated , FastQueue<AssociatedTripleIndex> associatedIdx , int totalViews, View viewA , View viewB , View viewC , int idxViewB , int idxViewC ) { ransac.process(associated.toList()); List<AssociatedTri...
python
def join(self, path): """ Similar to :func:`os.path.join` but returns a storage object instead. :param str path: path to join on to this object's URI :returns: a storage object :rtype: BaseURI """ return self.parse_uri(urlparse(os.path.join(str(self), path)), st...
java
private void removeCacheByUpdateConditon(Executor executor, MappedStatement mt, String mapperNameSpace, Object[] args) { try { Object parameterObject = args[1]; if(parameterObject != null && parameterObject.getClass().getName().equals(TK_MAPPER_EXAMPLE_CLASS_NAME)){ //清除group下所有缓存 removeCa...
python
def toParallelTargets(suite, targets): """ Produce a list of targets which should be tested in parallel. For the most part this will be a list of test modules. The exception is when a dotted name representing something more granular than a module was input (like an individal test case or test meth...
java
public Dialog positiveActionBackground(int id){ return positiveActionBackground(id == 0 ? null : getContext().getResources().getDrawable(id)); }
python
def load(self, path): """Load the pickled model weights.""" with io.open(path, 'rb') as fin: self.weights = pickle.load(fin)
java
private void snapshotConfig() { synchronized (configManager) { maximum = configManager.getPoolMaximum(poolInfo, getType()); minimum = configManager.getPoolMinimum(poolInfo, getType()); weight = configManager.getWeight(poolInfo); priority = configManager.getPriority(poolInfo); preemptab...
python
def get_config_entry(config, url): """ Look through config and try to find best matching entry for 'url' config - result of read_config() or read_global_config() url - artifactory url to search the config for """ if not config: return None # First, try to search for the best match ...
python
def _validate_aud(claims, audience=None): """Validates that the 'aud' claim is valid. The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing ...
python
def global_hook(handler): """add a callback to run in every switch between coroutines :param handler: the callback function, must be a function taking 2 arguments: - the greenlet being switched from - the greenlet being switched to be aware that only a weak reference to this f...
java
public EList<JvmTypeConstraint> getConstraints() { if (constraints == null) { constraints = new EObjectContainmentWithInverseEList<JvmTypeConstraint>(JvmTypeConstraint.class, this, TypesPackage.JVM_WILDCARD_TYPE_REFERENCE__CONSTRAINTS, TypesPackage.JVM_TYPE_CONSTRAINT__OWNER); } return constraints; }
python
def posthoc_tamhane(a, val_col=None, group_col=None, welch=True, sort=False): '''Tamhane's T2 all-pairs comparison test for normally distributed data with unequal variances. Tamhane's T2 test can be performed for all-pairs comparisons in an one-factorial layout with normally distributed residuals but u...
java
public static <R> DoubleFunction<R> doubleFunction(CheckedDoubleFunction<R> function) { return doubleFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
python
def create_group(self, name): """ Create group :param name: Group name """ parameters = { 'name': name } url = self.TEAM_GROUPS_URL connection = Connection(self.token) connection.set_url(self.production, url) connection.add_pa...
python
def rename(self, src_basename, dest_basename, datadir="outdir"): """ Rename a file located in datadir. src_basename and dest_basename are the basename of the source file and of the destination file, respectively. """ directory = { "indir": self.indir, ...
python
def is_valid(doi): """ Check that a given DOI is a valid canonical DOI. :param doi: The DOI to be checked. :returns: Boolean indicating whether the DOI is valid or not. >>> is_valid('10.1209/0295-5075/111/40005') True >>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7') ...
python
def __parse_fc_data(fc_data): """Parse the forecast data from the xml section.""" from buienradar.buienradar import condition_from_code fc = [] for daycnt in range(1, 6): daysection = __BRDAYFC % daycnt if daysection in fc_data: tmpsect = fc_data[daysection] fcdat...
java
@Override public void start() { super.start(); setResolution(config.getOutput()); addDeviceKeyboard(); addDeviceMouse(); graphics.setGraphic(new ImageBufferHeadless(width, height, Transparency.BITMASK)); ready = true; }
python
def write(self, vals): """ Overrides orm write method. @param self: The object pointer @param vals: dictionary of fields value. """ product_obj = self.env['product.product'] h_room_obj = self.env['hotel.room'] folio_room_line_obj = self.env['folio.room.lin...
java
public void modifed(ServiceReference<ResourceFactory> ref) { String[] newInterfaces = getServiceInterfaces(ref); if (!Arrays.equals(interfaces, newInterfaces)) { unregister(); register(ref, newInterfaces); } else { registration.setProperties(getServiceProperti...
python
def destroy_oaipmh_set(mapper, connection, community): """Signal for creating OAI-PMH sets during community creation.""" from invenio_oaiserver.models import OAISet with db.session.begin_nested(): oaiset = OAISet.query.filter_by( spec=community.oaiset_spec).one_or_none() if oaise...
python
def comparable(self): """str: comparable representation of the path specification.""" string_parts = [] if self.location is not None: string_parts.append('location: {0:s}'.format(self.location)) if self.store_index is not None: string_parts.append('store index: {0:d}'.format(self.store_inde...
java
public static void writeShortLittleEndian(ByteBuffer io, short value) { io.put((byte)(value & 0xFF)); io.put((byte)((value >> 8) & 0xFF)); }
python
def _initialize(self): """ Open from caffe weights """ self._graph = tf.Graph() with self._graph.as_default(): self._input_node = tf.placeholder(tf.float32, (self._batch_size, self._im_height, self._im_width, self._num_channels)) weights = self.build_alexnet_weights() ...
python
def _jmomentsurfaceMCIntegrand(vz,vR,vT,R,z,df,sigmaR1,gamma,sigmaz1,mvT,n,m,o): """Internal function that is the integrand for the vmomentsurface mass integration""" return df(R,vR*sigmaR1,vT*sigmaR1*gamma,z,vz*sigmaz1,use_physical=False, func=(lambda x,y,z: x**n*y**m*z**o))\ *numpy...
java
public ContainerDetail withEnvironment(KeyValuePair... environment) { if (this.environment == null) { setEnvironment(new java.util.ArrayList<KeyValuePair>(environment.length)); } for (KeyValuePair ele : environment) { this.environment.add(ele); } return th...
python
def interp(x, xp, *args, **kwargs): """Wrap interpolate_1d for deprecated interp.""" return interpolate_1d(x, xp, *args, **kwargs)
java
public WebElementFinder enabled(final Boolean theEnabled) { Fields fields = new Fields(this); fields.enabled = theEnabled; return new WebElementFinder(fields); }
java
public static ErrorCode validateProvidedServiceInstance(ProvidedServiceInstance serviceInstance) { ErrorCode retstr = isIdValid(serviceInstance.getProviderId()); if (retstr != ErrorCode.OK) { return retstr; } retstr = isNameValid(serviceInstance.getServiceName()); i...
java
public final void process(final File file) { if (file == null) { throw new IllegalArgumentException("Argument 'file' cannot be NULL"); } if (file.isFile()) { handler.handleFile(file); } else { processDir(file); } }
java
public static InterceptorFactory getInstance() { if (instance == null) { instance = new InterceptorFactory(); OjbConfigurator.getInstance().configure(instance); } return instance; }
python
def _fit_temporal(noise, mask, template, stimfunction_tr, tr_duration, spatial_sd, temporal_proportion, temporal_sd, noise_dict, fit_thresh, ...
python
def delete(self, name, kind=None): """Removes an input from the collection. :param `kind`: The kind of input: - "ad": Active Directory - "monitor": Files and directories - "registry": Windows Registry - "script": Scripts - "splunktcp": TC...
java
@Override public NumberType getNumberType() throws IOException { JrsValue n = currentNumericNode(); return (n == null) ? null : n.numberType(); }
java
protected void update(CmsUUID structureId, String rootPath, int type, CmsResourceState resState) { if (CmsResource.isTemporaryFileName(rootPath)) { return; } m_pathCache.replace(structureId, rootPath); if (isSitemapConfiguration(rootPath, type)) { m_workQu...
java
@SuppressWarnings("unchecked") @Override public String convertToDocument(StreamMessage message) { if (this.mapper == null) { this.mapper = new ObjectMapper(); } String jsonStr = message.getField(this.field).toString(); Map<String, Object> jsonMap = null; ...
python
def write(self, filename, content, overwrite=False): ''' Write content to a file. :param str filename: The storage root-relative filename :param content: The content to write in the file :param bool overwrite: Whether to wllow overwrite or not :raises FileExists: If the ...
python
def load_cobra_model(path, notifications): """Load a COBRA model with meta information from an SBML document.""" doc = libsbml.readSBML(path) fbc = doc.getPlugin("fbc") sbml_ver = doc.getLevel(), doc.getVersion(), fbc if fbc is None else \ fbc.getVersion() with catch_warnings(record=True) as...
java
public void useXopAttachmentServiceWithWebClient() throws Exception { final String serviceURI = "http://localhost:" + port + "/services/attachments/xop"; JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean(); factoryBean.setAddress(serviceURI); factoryBean.setProper...
java
private void registerCleanupTimer(W window) { long cleanupTime = cleanupTime(window); if (cleanupTime == Long.MAX_VALUE) { // don't set a GC timer for "end of time" return; } if (windowAssigner.isEventTime()) { triggerContext.registerEventTimeTimer(cleanupTime); } else { triggerContext.registerPr...
python
def get_point_source_fluxes(self, id, energies, tag=None): """ Get the fluxes from the id-th point source :param id: id of the source :param energies: energies at which you need the flux :param tag: a tuple (integration variable, a, b) specifying the integration to perform. If t...
python
def get_node(self, path): """ Returns node from within this particular ``DirNode``, so it is now allowed to fetch, i.e. node located at 'docs/api/index.rst' from node 'docs'. In order to access deeper nodes one must fetch nodes between them first - this would work:: d...
python
def _BuildScanTreeNode(self, path_filter_table, ignore_list): """Builds a scan tree node. Args: path_filter_table: a path filter table object (instance of _PathFilterTable). ignore_list: a list of path segment indexes to ignore, where 0 is the index of th...
java
public QueryResult printQuery( Session session, String jcrSql2, long expectedNumberOfResults, Map<String, String> variables ) throws RepositoryException { return printQuery(session, jcrSql2, Query.JCR_SQL2, ...
python
def get_vtt_files(inputfile): """Return a list of vtt files.""" vtts = [] for f in inputfile: filename = f.split('.') filename = '.'.join(filename[0:-1]) vtt = glob(filename + '*.vtt') if len(vtt) > 0: vtts.append({'vtt': vtt[0], 'video': f}) if len(vtts) ==...
python
def set_window_size(self, window, w, h, flags=0): """ Change the window size. :param wid: the window to resize :param w: the new desired width :param h: the new desired height :param flags: if 0, use pixels for units. If SIZE_USEHINTS, then the units will be ...
python
def get_next_entity_to_export(self): """ Examines the archive_observationExport and archive_metadataExport tables, and builds either a :class:`meteorpi_db.ObservationExportTask` or a :class:`meteorpi_db.MetadataExportTask` as appropriate. These task objects can be used to retrieve the un...
python
def param (self, param, kwargs, default_value=False): """gets a param from kwargs, or uses a default_value. if found, it's removed from kwargs""" if param in kwargs: value= kwargs[param] del kwargs[param] else: value= default_value setattr (sel...
java
@Deprecated public static void frontConsume(HttpServletResponse resp, Map<String, String> reqData) throws IOException { String html = AcpService.createAutoFormHtml(SDKConfig.getConfig().getFrontRequestUrl(), reqData, "UTF-8"); resp.getWriter().write(html); }
python
def open(self, bus): """ Open a given i2c bus. :param bus: i2c bus number (e.g. 0 or 1) :type bus: int """ self.fd = os.open("/dev/i2c-{}".format(bus), os.O_RDWR) self.funcs = self._get_funcs()
java
public void marshall(InstanceAssociationOutputLocation instanceAssociationOutputLocation, ProtocolMarshaller protocolMarshaller) { if (instanceAssociationOutputLocation == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocol...
java
public IPromise<String> getDataSimple() { Promise result = new Promise(); result.complete("Data", null); return result; }
java
public boolean addSubsystemFileSourceFromModule(String subsystem, FeaturePack.Module module, ArtifactFileResolver artifactFileResolver) throws IOException { // the subsystem templates are included in module artifacts files for (ModuleParseResult.ArtifactName artifactName : module.getModuleParseResult()....
java
public static String fixCase(String s) { if (s == null || s.length() == 0) { return s; } if ( Character.isUpperCase(s.charAt(0)) && (s.length() == 1 || Character.isLowerCase(s.charAt(1)))) { s = s.toLowerCase(); } return s; }
python
def prepare(self): self.body_html = markdown( codecs.open(self.abspath, 'r').read(), extras=['fenced-code-blocks', 'hilite', 'tables', 'metadata']) self.header = self.body_html.metadata """a blog post without tags causes an error ...""" if 'tags' in self.header:...
python
def _get_metadata_from_ndk_string(self, gcmt, ndk_string): """ Reads the GCMT metadata from line 2 of the ndk batch """ gcmt.identifier = ndk_string[:16] inversion_data = re.split('[A-Z:]+', ndk_string[17:61]) gcmt.metadata['BODY'] = [float(x) for x in inversion_data[1].s...
java
private byte[] crypt_raw(final byte password[], final byte salt[], final int log_rounds) { int rounds, i, j; final int cdata[] = bf_crypt_ciphertext.clone(); final int clen = cdata.length; byte ret[]; if ((log_rounds < 4) || (log_rounds > 31)) { ...
python
def add_missing_children(required_children, element_children): """Determine if there are elements not in the children that need to be included as blank elements in the form. """ element_tags = [element.tag for element in element_children] # Loop through the elements that should be in the form. f...
python
def text(self, max_nb_chars=200, ext_word_list=None): """ Generate a text string. Depending on the ``max_nb_chars, returns a string made of words, sentences, or paragraphs. :example 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' ...
python
def get_referenced_object_as_list( prev_obj, obj, dot_separated_name, desired_type=None): """ Same as get_referenced_object, but always returns a list. Args: prev_obj: see get_referenced_object obj: see get_referenced_object dot_separated_name: see get_referenced_object ...
python
def build_media(self): """ Build the media files. """ logger.debug("Building media directory") if self.verbosity > 1: self.stdout.write("Building media directory") if os.path.exists(self.media_root) and settings.MEDIA_URL: target_dir = path.join(se...
python
def get_child_for_path(self, path): """Get a child for a given path. Rather than repeated calls to get_child, children can be found by a derivation path. Paths look like: m/0/1'/10 Which is the same as self.get_child(0).get_child(-1).get_child(10) Or,...
python
def getPcn(dsz, Nv, dimN=2, dimC=1, crp=False, zm=False): """Construct the constraint set projection function for convolutional dictionary update problem. Parameters ---------- dsz : tuple Filter support size(s), specified using the same format as the `dsz` parameter of :func:`bcrop` ...
python
def add_slide(self, slide_layout): """ Return an (rId, slide) pair of a newly created blank slide that inherits appearance from *slide_layout*. """ partname = self._next_slide_partname slide_layout_part = slide_layout.part slide_part = SlidePart.new(partname, self...
java
private int updateNeighbour(Pathfindable mover, int dtx, int dty, Node current, int xp, int yp, int maxDepth) { int nextDepth = maxDepth; final double nextStepCost = current.getCost() + getMovementCost(mover, current.getX(), current.getY()); final Node neighbour = nodes[yp][xp]; if ...
python
def copy(self): """ Returns a copy of this object :return: A copy of self """ retfilters = Filters(self.filter_converter, self.datamodel) retfilters.filters = copy.copy(self.filters) retfilters.values = copy.copy(self.values) return retfilters
java
private String getDsDefStr(DsDef def) { return "DS:" + def.getDsName() + ":" + def.getDsType() + ":" + def.getHeartbeat() + ":" + formatDouble(def.getMinValue()) + ":" + formatDouble(def.getMaxValue()); }
python
def _plot_methods(self): """A dictionary with mappings from plot method to their summary""" ret = {} for attr in filter(lambda s: not s.startswith("_"), dir(self)): obj = getattr(self, attr) if isinstance(obj, PlotterInterface): ret[attr] = obj._summary ...
java
public ServiceFuture<ConnectionTypeInner> getAsync(String resourceGroupName, String automationAccountName, String connectionTypeName, final ServiceCallback<ConnectionTypeInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, automationAccountName, connectionTy...
python
def number_of_states(dtrajs, only_used = False): r"""returns the number of states in the given trajectories. Parameters ---------- dtraj : array_like or list of array_like Discretized trajectory or list of discretized trajectories only_used = False : boolean If False, will return ma...
python
def bar(self, width, percent=0): """Returns the completed progress bar. Positional arguments: width -- the width of the entire bar (including borders). Keyword arguments: percent -- the percentage to draw. """ width -= self._width_offset units = int(perc...
python
def get_thread_id(self): """Return thread id""" if self._id is None: for thread_id, obj in list(threading._active.items()): if obj is self: self._id = thread_id return self._id
python
def subscribe(self, callback, existing=True): """Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well. """ if callback in self.callbacks: return self.callbacks.append(callback) if not existing: ...
java
private void unregister(String path,ZKMBeanInfo bean) throws JMException { if(path==null) return; if (!bean.isHidden()) { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { mbs.unregisterMBean(makeObjectName(path, bean)); }...
python
def _remove_debug_handlers(self): """Remove any handlers with an attribute of debug_only that is True and remove the references to said handlers from any loggers that are referencing them. """ remove = list() for handler in self.config[self.HANDLERS]: if self...
python
def destroy(self, recursive): """ Removes all the state elements. :param recursive: Flag wether to destroy all state elements which are removed """ for in_key in list(self.input_data_ports.keys()): self.remove_input_data_port(in_key, force=True, destroy=recursive) f...
python
def cli(wio, get_debug, debug): ''' Change setting of device. \b DOES: The config command lets you change setting of device through upd. 1. Ensure your device is Configure Mode. 2. Change your computer network to Wio's AP. \b EXAMPLE: wio config --debug [on|off]...
python
def legacy_conv_act_layer(from_layer, name, num_filter, kernel=(1,1), pad=(0,0), \ stride=(1,1), act_type="relu", use_batchnorm=False): """ wrapper for a small Convolution group Parameters: ---------- from_layer : mx.symbol continue on which layer name : str base name of the...
python
def parse_date(self, value): """A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it """ if value is None: raise Exception("U...
python
def derivative(self, point): """Return the derivative in ``point``. The derivative of the gradient is often called the Hessian. Parameters ---------- point : `domain` `element-like` The point that the derivative should be taken in. Returns ------- ...
python
def _init_uninit_vars(self): """ Initialize all other trainable variables, i.e. those which are uninitialized """ uninit_vars = self.sess.run(tf.report_uninitialized_variables()) vars_list = list() for v in uninit_vars: var = v.decode("utf-8") vars_list.append(var...
python
def hash(hash_type, input_text): '''Hash input_text with the algorithm choice''' hash_funcs = {'MD5' : hashlib.md5, 'SHA1' : hashlib.sha1, 'SHA224' : hashlib.sha224, 'SHA256' : hashlib.sha256, 'SHA384' : hashlib.sha384, 'S...