language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def setReferenceVoltage(self, caldb, calv): """Sets the reference point to determine what outgoing voltage will produce what intensity, used to calculate the proper output amplitude of components :param caldb: calibration intensity in dbSPL :type caldb: float :param calv: calib...
python
def download_file(self, url, target, cwd=None): """ (internal) Download an ``url`` to a ``target``. """ if not url: return info('Downloading {} from {}'.format(self.name, url)) if cwd: target = join(cwd, target) parsed_url = urlparse(url)...
python
def update_variant_by_id(cls, variant_id, variant, **kwargs): """Update Variant Update attributes of Variant This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_variant_by_id(variant_id, va...
java
public void setColor(String red, String green, String blue, String alpha) { setColor(red, green, blue); setAlpha(alpha); }
python
def permissions(self): """ A list of strings describing `permissions`_ the user has granted your application. .. _permissions: http://developers.facebook.com/docs/reference/api/permissions/ """ records = self.graph.get('me/permissions')['data'] permissions = [] ...
python
def queue_send(self, frame, callback=None, recv_callback=None): """ Enqueue `frame` to the send buffer so that it is send on the next `do_async_send`. `callback` is an optional callable to call when the frame has been fully written. `recv_callback` is an optional callable to quic...
java
public PatchBuilder set(final String path, final Object value) { final String[] pathTokens = delimitedListToStringArray(path, PATH_DELIMITER); final String[] parentPathTokens = new String[pathTokens.length - 1]; arraycopy(pathTokens, 0, parentPathTokens, 0, parentPathTokens.length); final Map<String, Ob...
java
public void execute() throws MojoExecutionException, MojoFailureException { Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this); vc.put("helper", this); vc.put("ESC", "$"); if (null != sourceVersion) { getLog().info("sourceVersion=" + sourceVersion); ...
python
def memset(self, buffer, value, size): """set the memory in allocation to the value in value :param allocation: An OpenCL Buffer to fill :type allocation: pyopencl.Buffer :param value: The value to set the memory to :type value: a single 32-bit int :param size: The siz...
java
public IComplexOption getComplexOption(String key) { Object object = this.options.get(key); if (object instanceof IComplexOption) return (IComplexOption) object; return null; }
java
private R2Request<GenericRecord> buildWriteRequest(BufferedRecord<GenericRecord> record) { if (record == null) { return null; } R2Request<GenericRecord> request = new R2Request<>(); HttpOperation httpOperation = HttpUtils.toHttpOperation(record.getRecord()); // Set uri URI uri = HttpUtils...
java
private boolean includes(String identifier) { if (includes.isEmpty()) return !exclude(identifier); String includeMatch = null; String excludeMatch = null; for (String rule = identifier; rule != null; rule = enclosing(rule)) { if (excludes.contains(rule)) { excludeMatch = rule; } ...
java
protected Map<String, String> getElementAttributes() { // Preserve order of attributes Map<String, String> attrs = new HashMap<>(); if (this.getAlphabet() != null) { attrs.put("alphabet", this.getAlphabet().toString()); } if (this.getPh() != null) { attrs...
java
@SuppressWarnings("unchecked") private T getService(boolean throwException) { T svc = null; ReferenceTuple<T> current = null; ReferenceTuple<T> newTuple = null; do { // Get the current tuple current = tuple.get(); // We have both a context and a ...
java
@Deprecated public static Class<?> getCollectionFieldType(Field collectionField, int nestingLevel, Map<Integer, Integer> typeIndexesPerLevel) { return ResolvableType.forField(collectionField).getNested(nestingLevel, typeIndexesPerLevel).asCollection().resolveGeneric(); }
python
def get_enabled_regions(exec_type, json_spec, from_command_line, executable_builder_exeception): """ Return a list of regions in which the global executable (app or global workflow) will be enabled, based on the "regionalOption" in their JSON specification and/or --region CLI argument used with "dx buil...
java
private static double doubleValue(Object attributeValue) throws NumberFormatException { if (attributeValue instanceof Number) { return (((Number) attributeValue).doubleValue()); } else { return (Double.parseDouble(attributeValue.toString())); } }
java
void parseLazy( CssFormatter formatter ) { if( lazyImports != null ) { HashMap<String, Expression> vars = variables; formatter.addVariables( vars ); for( int i = 0; i < lazyImports.size(); i++ ) { LazyImport lazyImport = lazyImports.get( i ); S...
java
static StringMap injectContextData(@Nullable List<Property> properties, StringMap reusable) { if (properties == null || properties.isEmpty()) { return getContextAndTracingData(); } // Context data has precedence over configuration properties. putProperties(properties, reusable); // TODO(sebrig...
java
@SuppressWarnings("WeakerAccess") public TokenRequest token(@NonNull String authorizationCode, @NonNull String redirectUri) { Map<String, Object> parameters = ParameterBuilder.newBuilder() .setClientId(getClientId()) .setGrantType(GRANT_TYPE_AUTHORIZATION_CODE) ...
python
def month_view( request, year, month, template='swingtime/monthly_view.html', queryset=None ): ''' Render a tradional calendar grid view with temporal navigation variables. Context parameters: ``today`` the current datetime.datetime value ``calendar`` a list of...
java
protected BeanManagerImpl ambiguousBeanManager(String callerClassName, Set<BeanManagerImpl> managers) { throw BeanManagerLogger.LOG.ambiguousBeanManager(callerClassName); }
java
public ResponseMessageBuilder headersWithDescription(Map<String, Header> headers) { this.headers.putAll(nullToEmptyMap(headers)); return this; }
java
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextPane1 = new javax.swing.JTextPane(); setLayout(new java.awt.GridLayout(1, 0)); jTextPane1.setEditable(false); add(jText...
python
def __Script_Editor_Output_plainTextEdit_set_ui(self): """ Sets the **Script_Editor_Output_plainTextEdit** Widget. """ self.Script_Editor_Output_plainTextEdit.setReadOnly(True) self.Script_Editor_Output_plainTextEdit.highlighter = umbra.ui.highlighters.DefaultHighlighter( ...
python
def generate_links(self, nodes): """ Generate a list of links :param list nodes: A list of nodes from :py:meth:`generate_nodes` :return: list of links :rtype: list """ new_links = [] for link in self.links: # Expand port name if required ...
python
def search_for_book_in_misc(citation, kbs): """Searches for books in the misc_txt field if the citation is not recognized as anything like a journal, book, etc. """ citation_year = year_from_citation(citation) for citation_element in citation: LOGGER.debug(u"Searching for book title in: %s", cit...
python
def write(self, buf, *, start=0, end=None): """ Write the bytes from ``buf`` to the device. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buffer[start:end]``. This will not cause an allocation like ``buffer[start:end]`` will so it saves memory. ...
python
def string_to_double_precision_float(s: str) -> float: """ Double precision float in Fortran file will have form 'x.ydz' or 'x.yDz', this cannot be convert directly to float by Python ``float`` function, so I wrote this function to help conversion. For example, :param s: a string denoting a double prec...
python
def parse_url(self, url): """Parse an IIIF API URL path and each component. Will parse a URL or URL path that accords with either the parametrized or info request forms. Will raise an IIIFRequestError on failure. A wrapper for the split_url() and parse_parameters() methods. ...
java
private Map<String, String> convertToMap(Object expression) { if (expression instanceof Map) { return (Map<String, String>) expression; } return Stream.of(Optional.ofNullable(expression) .map(Object::toString) .orElse("") .split(",")) ...
java
public boolean isIPAddressInRange(IPAddress address) { if (ipSubnetMask == null) { return this.ipAddress.equals(address); } int result1 = address.getIPAddress() & ipSubnetMask.getIPAddress(); int result2 = ipAddress.getIPAddress() & ipSubnetMask.getIPAddress(); return result1 == result2; }
java
public static int setVolatile(int modifier, boolean b) { if (b) { return (modifier | VOLATILE) & (~SYNCHRONIZED & ~NATIVE & ~INTERFACE & ~ABSTRACT & ~STRICT); } else { return modifier & ~VOLATILE; } }
java
static String[] getRemoteTypeIds(Class<?> remoteInterface) { ArrayList<String> remoteTypes = new ArrayList<String>(); remoteTypes.add(getRemoteTypeId(remoteInterface)); Class<?>[] interfaces = remoteInterface.getInterfaces(); for (Class<?> remote : interfaces) { if (remote !...
java
public void setBorderPaint(final Paint PAINT) { if (null == borderPaint) { _borderPaint = PAINT; fireUpdateEvent(REDRAW_EVENT); } else { borderPaint.set(PAINT); } }
python
def change_python_path(pythonpath): '''Changes the pythonpath (clears all the previous pythonpath) @param pythonpath: string with paths separated by | ''' split = pythonpath.split('|') sys.path = [] for path in split: path = path.strip() if len(path) > 0: sys.path.a...
python
def get_config(path): """Load a config from disk :param path: target config :type path: unicode :return: :rtype: configparser.Config """ if configparser is None: return None # Check for env specific configs first if os.path.exists(os.path.join(ROOT, 'config', NAME, path)): ...
java
public final ListIntentsPagedResponse listIntents(String parent) { ListIntentsRequest request = ListIntentsRequest.newBuilder().setParent(parent).build(); return listIntents(request); }
java
protected LightweightTypeReference getTypeForName(Class<?> clazz, ITypeComputationState state) { JvmType type = findDeclaredType(clazz, state); ITypeReferenceOwner owner = state.getReferenceOwner(); if (type == null) { return owner.newUnknownTypeReference(clazz.getName()); } return owner.toLightweightTypeR...
java
public static PlotCanvas screeplot(PCA pca) { int n = pca.getVarianceProportion().length; double[] lowerBound = {0, 0.0}; double[] upperBound = {n + 1, 1.0}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false); canvas.setAxisLabels("Principal Component", "Proporti...
python
def set_repository_info(self, repo_url, branch, git_token, private_repo_username, private_repo_password): """ Call this method before attempting to setup continuous delivery to setup the source control settings :param repo_url: URL of the code repo :param branch: repo branch :par...
python
def remotes(self): """Return the names and URLs of the remotes""" from ambry.orm import Remote for r in self.database.session.query(Remote).all(): if not r.short_name: continue yield self.remote(r.short_name)
java
@Override public String encodeRedirectURL(String url) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "encodeRedirectURL: " + url); } return encodeURL(url); }
java
public Authentication verifyIdToken(String idToken) throws InvalidTokenException, TokenExpiredException { CacheProvider cp = cp(); Authentication authc = cp.get(idToken); if(null != authc) { if(!authc.isExpired()) { return authc; }else{ cp....
java
public ESigItem add(IESigType eSigType, String id, String text, String subGroupName, SignState signState, String data, String session) { ESigItem item = new ESigItem(eSigType, id); item.setText(text); item.setSubGroupName(subGroupName); item.setSignState(signState...
python
def _check_file(self, filename): """Process python file looking for indications of problems. :param filename: (str) Python source filename :return: (int) number of failures """ # If the user specifies an invalid severity use comment. log_threshold = Nit.SEVERITY.get(self._severity, Nit.COMMENT)...
java
private void setRecipients(Email email, MimeMessage mimeMsg) throws MessagingException, AddressException, UnsupportedEncodingException { for (Recipient recipient : email.getRecipients()) { mimeMsg.addRecipient(convert(recipient.getType()), toInternetAddress(recipient.getAddress())); } }
python
def get_namespace_by_keyword_pattern(self, keyword: str, pattern: str) -> Optional[Namespace]: """Get a namespace with a given keyword and pattern.""" filt = and_(Namespace.keyword == keyword, Namespace.pattern == pattern) return self.session.query(Namespace).filter(filt).one_or_none()
java
public String[] getNames() { String[] headers = new String[columns.getColumns().size()]; for (int i = 0; i < columns.getColumns().size(); i++) { headers[i] = columns.getColumns().get(i).getName(); } return headers; }
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "filter", scope = GetAllVersions.class) public JAXBElement<String> createGetAllVersionsFilter(String value) { return new JAXBElement<String>(_GetPropertiesFilter_QNAME, String.class, GetAllVersions.class, value); }
java
public List<EjbRelationType<RelationshipsType<T>>> getAllEjbRelation() { List<EjbRelationType<RelationshipsType<T>>> list = new ArrayList<EjbRelationType<RelationshipsType<T>>>(); List<Node> nodeList = childNode.get("ejb-relation"); for(Node node: nodeList) { EjbRelationType<Relation...
python
def terrain_data_encode(self, lat, lon, grid_spacing, gridbit, data): ''' Terrain data sent from GCS. The lat/lon and grid_spacing must be the same as a lat/lon from a TERRAIN_REQUEST lat : Latitude of SW corner of first grid (degree...
java
private static boolean memberContainerConstraints(final Triple triple) { return triple.getPredicate().equals(ACL.accessControl) || triple.getPredicate().equals(LDP.contains); }
java
@Override public void updatePortalCookie(HttpServletRequest request, HttpServletResponse response) { // Get the portal cookie object final IPortalCookie portalCookie = this.getOrCreatePortalCookie(request); // Create the browser cookie final Cookie cookie = this.conv...
python
def var_set(session, **kwargs): """ Sets the given variables or prints the current ones. "set answer=42" """ if not kwargs: for name, value in session.variables.items(): session.write_line("{0}={1}".format(name, value)) else: for name, valu...
java
public void set_timeout_millis(final Connection connection, final int millis) throws DevFailed { build_connection(connection); // Check if TACO device if (connection.url.protocol == TACO) { connection.taco_device.set_rpc_timeout(millis); return; } // Else TANGO device set_obj_timeout(connecti...
java
public static boolean isCompensationThrowing(PvmExecutionImpl execution, Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping) { if (CompensationBehavior.isCompensationThrowing(execution)) { ScopeImpl compensationThrowingActivity = execution.getActivity(); if (compensationThrowingActivity.isScope(...
python
def SUSSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the stochastic universal sampling algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) r = numpy.random.random()/float(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = num...
java
public void publish(LogRecord record) { // Silently ignore null records. if (record == null) { return; } Logger slf4jLogger = getSLF4JLogger(record); // this is a check to avoid calling the underlying logging system // with a null message. While it is legitim...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "multiSolidDomain", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "domainSet") public JAXBElement<MultiSolidDomainType> createMultiSolidDomain(MultiSolidDomainType value) { return new JAXBElement<MultiSolidDo...
java
public PactDslJsonArray valueFromProviderState(String expression, Object example) { generators.addGenerator(Category.BODY, rootPath + appendArrayIndex(0), new ProviderStateGenerator(expression)); body.put(example); return this; }
java
protected void moskitoDoPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doPut(req, res); }
java
public EClass getIfcMinuteInHour() { if (ifcMinuteInHourEClass == null) { ifcMinuteInHourEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(709); } return ifcMinuteInHourEClass; }
python
def from_file(cls, path, format='infer'): """Create an instance from a json or yaml file. Parameters ---------- path : str The path to the file to load. format : {'infer', 'json', 'yaml'}, optional The file format. By default the format is inferred from t...
python
def pop_event(self): ''' Pop the next queued event from the queue. :raise ValueError: If there is no event queued. ''' with self.lock: if not self.events: raise ValueError('no events queued') return self.events.popleft()
java
public void setName(final LinkerEnum name) throws BuildException { if (isReference()) { throw tooManyAttributes(); } final Linker linker = name.getLinker(); super.setProcessor(linker); }
python
def install_vagrant_plugin(plugin, use_sudo=False): """ install vagrant plugin """ cmd = 'vagrant plugin install %s' % plugin with settings(hide('running', 'stdout')): if use_sudo: if plugin not in sudo('vagrant plugin list'): sudo(cmd) else: if plug...
java
public static Class convertPrimitiveToWrapper(Class clazz) { if (clazz == null || !clazz.isPrimitive()) return clazz; return (Class) primativeToWrapperMap.get(clazz); }
python
def _compare_recursive(old, new): """Deep comparison between objects; assumes that `new` contains user defined parameters so only keys which exist in `new` will be compared. Returns `True` if they differ. Else, `False`. """ if isinstance(new, dict): for key in six.iterkeys(new): ...
java
public static BaseResult productModstatus(String accessToken, ProductStatus productStatus) { return productModstatus(accessToken, JsonUtil.toJSONString(productStatus)); }
java
private static void analyzeType(final Map<Class<?>, LinkedHashMap<String, Type>> generics, final Class<?> type, final Map<Class<?>, LinkedHashMap<String, Type>> knownGenerics, final List<Class<?>> ignoreClasses) ...
java
private void validateUniqueAttribute(AtlasEntityType entityType, Map<String, Object> attributes) throws AtlasBaseException { if (MapUtils.isEmpty(attributes)) { throw new AtlasBaseException(AtlasErrorCode.ATTRIBUTE_UNIQUE_INVALID, entityType.getTypeName(), ""); } for (String attribu...
java
@Override public GetApplicationPolicyResult getApplicationPolicy(GetApplicationPolicyRequest request) { request = beforeClientExecution(request); return executeGetApplicationPolicy(request); }
java
public static Field getDeclaredField(Object object, String fieldName) { Field field = null; Class<?> clazz = object.getClass(); for (; clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName); return field...
java
public static Post post(String uri, String content) { return post(uri, content.getBytes(), CONNECTION_TIMEOUT, READ_TIMEOUT); }
java
public boolean isLinked(ParaObject obj, String type2, String id2) { if (obj == null || obj.getId() == null || type2 == null || id2 == null) { return false; } String url = Utils.formatMessage("{0}/links/{1}/{2}", obj.getObjectURI(), type2, id2); Boolean result = getEntity(invokeGet(url, null), Boolean.class);...
java
@Override public boolean beforeSolve(ReconfigurationProblem p) throws SchedulerException { for (VM vm : source.getMapping().getAllVMs()) { int vmId = p.getVM(vm); int v = getVMAllocation(vmId); if (v < 0) { int prevUsage = rc.getConsumption(vm); ...
java
public static <T extends ImageGray<T>>T average(ImageInterleaved input , T output ) { ImageDataType type = input.getImageType().getDataType(); if( type == ImageDataType.U8) { return (T)ConvertImage.average((InterleavedU8)input,(GrayU8)output); } else if( type == ImageDataType.S8) { return (T)ConvertImage.av...
java
public void addDisplay(String displayID, Display2D display) throws ShanksException { Scenario2DPortrayal scenarioPortrayal = (Scenario2DPortrayal) this .getSimulation().getScenarioPortrayal(); HashMap<String, Display2D> displays = scenarioPortrayal.getDisplays(); if (...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.MMD__RG: return rg != null && !rg.isEmpty(); } return super.eIsSet(featureID); }
java
public synchronized Map<String, Argument> getPluginArguments() { if (PLUGIN_ARGUMENTS == null) { final List<Element> params = toList(Plugins.getPluginConfiguration().getElementsByTagName("param")); PLUGIN_ARGUMENTS = params.stream() .map(ArgumentParser::getArgument) ...
python
def _extract_time_loc(self, term): """Get the location from a term (CC or TERM)""" loc = term.find('location') if loc is None: loc_context = None else: loc_id = loc.attrib.get('id') loc_term = self.tree.find("*[@id='%s']" % loc_id) text = l...
python
def _index_verify(index_file, **extra_kwargs): """Populate the template and compare to documentation index file. Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``. Args: index_file (str): Filename to compare against. extra_kwargs (Dict[str, str]): Over-ride for templ...
java
@Override public synchronized String lindex(final String key, long index) throws WrongTypeException { if (!exists(key)) { return null; } checkType(key, "list"); if (index < 0) { index = listCache.get(key).size() + index; } try { return ...
java
public void setBootstrapActions(java.util.Collection<BootstrapActionConfig> bootstrapActions) { if (bootstrapActions == null) { this.bootstrapActions = null; return; } this.bootstrapActions = new com.amazonaws.internal.SdkInternalList<BootstrapActionConfig>(bootstrapActi...
java
@Override public void process(GrayF32 intensityImage, @Nullable QueueCorner localMin, @Nullable QueueCorner localMax) { if( localMin != null ) localMin.reset(); if( localMax != null ) localMax.reset(); // the defines the region that can be processed int endX = intensityImage.width - border; int endY ...
java
private void terminate() { if (this.container != null) { final Cache<String, Integer> cache = this.container .<String, Integer>getCache(InfinispanCache.COUNTERCACHE); Integer count = cache.get(InfinispanCache.COUNTERCACHE); if (count == null ||...
java
@Override public void unregister(ReadyListener listener) { for (ReadyRegistration rr : regs) { if (rr.listener == listener) { regs.remove(rr); rr.cancelTimeout(); break; } } }
python
def download_sync(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server synchronously. :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param call...
java
public static List<Method> getMethodsListWithAnnotation(final Class<?> cls, final Class<? extends Annotation> annotationCls, final boolean searchSupers, final boolean ignoreAccess) { Validate...
python
def vb_stop_vm(name=None, timeout=10000, **kwargs): ''' Tells Virtualbox to stop a VM. This is a blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of stopped VM ''...
java
public void informIfChanged(final EventDispatcher pDispatcher, final Directory pNewRootOrNull, final Path pFile, final boolean pIsCreated) { if (pDispatcher.hasListeners()) { if (pIsCreated) { ...
python
def GetViewCollection(self): """Get Views for Current List This is run in __init__ so you don't have to run it again. Access from self.views """ # Build Request soap_request = soap('GetViewCollection') soap_request.add_parameter('listName', self....
java
Object processEXPR( StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws org.xml.sax.SAXException { try { XPath expr = handler.createXPath(value, owner); return expr; } catch (TransformerExcept...
python
def parse_tags(self, element, trigger): """ Parse tags in an XML element :param element: The response [message] XML element :type element: etree._Element :return: A list of strings and Tag objects in the order they are parsed :rtype : list of (str or parser.tags.tag,Tag...
java
public void init(Rec record, RemoteTable tableRemote, Object syncObject) { super.init(record); this.setRemoteTable(tableRemote, syncObject); }
java
public List<Entity> query(Query query, FetchOptions options) { return datastore.prepare(query).asList(options); }
java
public Inventory newInstance(ClassLoader classLoader) { Iterator<Inventory> it = ServiceLoader.load(Inventory.class, classLoader).iterator(); if (!it.hasNext()) { return null; } else { return it.next(); } }
java
public Object nextToken() throws JSONException { char c; char q; StringBuilder sb; do { c = next(); } while (Character.isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped element"); case '<': throw syntaxError("Misplaced '<'"); case '>': return XML.GT; case '/': ...
java
@Nullable public static String getURLString (@Nullable final String sPath, @Nullable final String sQueryParams, @Nullable final String sAnchor) { final boolean bHasPath = StringHelper.hasText (sPath); final boolean bHasQueryParams = S...