language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@RequestMapping(value = "configurations/{name}/update", method = RequestMethod.GET) public Form updateConfigurationForm(@PathVariable String name) { return configurationService.getConfiguration(name).asForm(); }
java
@SuppressWarnings("unchecked") @NotNull public <TYPE> TYPE create(@NotNull final String xml, @NotNull final JAXBContext jaxbContext) throws UnmarshalObjectException { Contract.requireArgNotNull("xml", xml); Contract.requireArgNotNull("jaxbContext", jaxbContext); return (TYPE) cr...
java
private boolean hasSettings(CmsObject cms, CmsResource resource) throws CmsException { if (!CmsResourceTypeXmlContent.isXmlContent(resource)) { return false; } CmsFormatterConfiguration formatters = getConfigData().getFormatters(m_cms, resource); boolean result = (formatter...
python
def _set_as_path(self, v, load=False): """ Setter method for as_path, mapped from YANG variable /rbridge_id/ip/as_path (container) If this variable is read-only (config: false) in the source YANG file, then _set_as_path is considered as a private method. Backends looking to populate this variable sh...
python
def getElementsWithAttrValues(self, attrName, values, root='root', useIndex=True): ''' getElementsWithAttrValues - Returns elements with an attribute matching one of several values. For a single name/value combination, see getElementsByAttr @param attrName <lowercase str> - A lowerc...
python
def future_exceptions(context, rrevent=None): """ Displays a list of all the future exceptions (extra info, cancellations and postponements) for a recurring event. If the recurring event is not specified it is assumed to be the current page. """ request = context['request'] if rrevent is No...
java
@Override public void deleteServerLease(final String recoveryIdentity) throws Exception { if (tc.isEntryEnabled()) Tr.entry(tc, "deleteServerLease", new Object[] { recoveryIdentity, this }); // Is a lease file (equivalent to a record in the DB table) available for deletion final...
python
def __generate_font_tuple(self): """ Generate a font tuple for tkinter widgets based on the user's entries. :return: font tuple (family_name, size, *options) """ if not self._family: return None font = [self._family, self._size] if self._bold:...
java
public static Map<String, String[]> readMap(String filename) throws IOException { return readMap(filename, DEFAULT_DELIMITER); }
java
public Enumeration<String> getElements() { AttributeNameEnumeration elements = new AttributeNameEnumeration(); elements.addElement(USAGES); return (elements.elements()); }
java
@Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); // Always true - error out only if the client is trying to set somethign else if (!autoCommit && (props.getProperty(COMMIT_THROW_EXCEPTION, "true").equalsIgnoreCase("true"))) { throw ...
java
private void logSession(Session session, TransportStrategy transportStrategy) { final String logmsg = "starting mail session (host: %s, port: %s, username: %s, authenticate: %s, transport: %s)"; Properties properties = session.getProperties(); logger.debug(String.format(logmsg, properties.get(transportStrategy...
java
@Override public void close() { synchronized (this.lock) { if (this.closed) { return; } this.closed = true; // Cancel all pending reads and unregister them. ArrayList<Request> toClose = new ArrayList<>(this.pendingRequests.values(...
python
def get_quality_report_string(self): """get a report on quality score distribution. currently prints to stdout""" if not self._quality_distro: self.analyze_quality() ostr = "" for type in sorted(self._quality_distro.keys()): total = sum([ord(x)*self._quality_distro[type][x] for x in self._q...
python
async def _set_persistent_menu(self): """ Define the persistent menu for all pages """ page = self.settings() if 'menu' in page: await self._send_to_messenger_profile(page, { 'persistent_menu': page['menu'], }) logger.info('S...
java
public static void zero( DMatrixSparseCSC A , int row0, int row1, int col0, int col1 ) { for (int col = col1-1; col >= col0; col--) { int numRemoved = 0; int idx0 = A.col_idx[col], idx1 = A.col_idx[col+1]; for (int i = idx0; i < idx1; i++) { int row = A.nz_ro...
python
def get_evidence(assay): """Given an activity, return an INDRA Evidence object. Parameters ---------- assay : dict an activity from the activities list returned by a query to the API Returns ------- ev : :py:class:`Evidence` an :py:class:`Evidence` object containing the kin...
java
public int compareTo(BigDecimal val) { // Quick path for equal scale and non-inflated case. if (scale == val.scale) { long xs = intCompact; long ys = val.intCompact; if (xs != INFLATED && ys != INFLATED) return xs != ys ? ((xs > ys) ? 1 : -1) : 0; ...
java
protected ExtensionHttpSessions getExtensionHttpSessions() { if(extensionHttpSessions==null){ extensionHttpSessions = Control.getSingleton().getExtensionLoader().getExtension(ExtensionHttpSessions.class); } return extensionHttpSessions; }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WAjaxControl ajaxControl = (WAjaxControl) component; XmlStringBuilder xml = renderContext.getWriter(); WComponent trigger = ajaxControl.getTrigger() == null ? ajaxControl : ajaxControl. getTrigger(); int d...
java
public void setDefaultAutoGeneratedContent(String type) { getXBlockExpression().getExpressions().clear(); if (Strings.isEmpty(type)) { setInnerDocumentation(getAutoGeneratedActionString()); } else { IExpressionBuilder expr = addExpression(); String defaultValue = expr.getDefaultValueForType(type); if ...
python
def get_structural_variant(self, variant): """Check if there are any overlapping sv clusters Search the sv variants with chrom start end_chrom end and sv_type Args: variant (dict): A variant dictionary Returns: variant (dict): A variant dictionary """ ...
python
def parse_altitude(cls, distance, unit): """ Parse altitude managing units conversion """ if distance is not None: distance = float(distance) CONVERTERS = { 'km': lambda d: d, 'm': lambda d: units.kilometers(meters=d), ...
java
public static final Path fromPosix(String posix) { String path = posix.replace("/", SEP); if (OperatingSystem.is(Windows) && path.startsWith("\\")) { path = "c:"+path; } return Paths.get(path); }
java
@RequestMapping(value = "entity/project/{project:.*}", method = RequestMethod.GET) public Project project(@PathVariable String project) { return structureService.findProjectByName(project).orElseThrow(() -> new ProjectNotFoundException(project)); }
python
def price_in_btc(self, minimum: float = 0, maximum: float = 2) -> str: """Generate random price in BTC. :param minimum: Minimum value of price. :param maximum: Maximum value of price. :return: Price in BTC. """ return '{} BTC'.format( self.random.uniform( ...
java
private void writeFieldInstBegin(OutputStream result) throws IOException { result.write(OPEN_GROUP); result.write(FIELD_INSTRUCTIONS); result.write(DELIMITER); }
python
def evaluate_extracted_tokens(gold_content, extr_content): """ Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-stand...
java
public void forEach(final IntConsumer action) { requireNonNull(action); final int size = _size; for (int i = 0; i < size; ++i) { action.accept(_data[i]); } }
java
public BooleanConditionBuilder not(ConditionBuilder... conditionBuilders) { if (not == null) { not = new ArrayList<>(conditionBuilders.length); } for (ConditionBuilder conditionBuilder : conditionBuilders) { not.add(conditionBuilder.build()); } return this...
python
def computePerturbedExpectation(self, u_n, A_n, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False): """Compute the expectation of an observable of phase space function A(x) for a single new state. Parameters ---------- u_n : np.ndarray, float,...
python
def set_server(self, server_pos, key, value): """Set the key to the value for the server_pos (position in the list).""" self.servers.set_server(server_pos, key, value)
java
public static String listToJson(List<?> list) { JSONArray array = new JSONArray(); if (Checker.isNotEmpty(list)) { array.addAll(list); } return formatJson(array.toString()); }
java
public static <T, C extends Collection<? super T>> C toCollection( Iterable<T> iterable, C collection) { Objects.requireNonNull(iterable, "The iterable is null"); Objects.requireNonNull(collection, "The collection is null"); return Iterators.toCollection(iterable.iterator(), col...
java
public static <V> PnkyPromise<V> immediatelyComplete() { final Pnky<V> pnky = create(); pnky.resolve(null); return pnky; }
java
private void printSuggestion( String arg, List<ConfigOption> co ) { List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co ); Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) ); System.err.println( "Parse error for argument \"" + arg + "\", did you mean " + sorte...
java
@Override public GetQueryLoggingConfigResult getQueryLoggingConfig(GetQueryLoggingConfigRequest request) { request = beforeClientExecution(request); return executeGetQueryLoggingConfig(request); }
python
def flatten(items): """ Yield items from any nested iterable. Used by ``QuadTree.flatten`` to one-dimensionalize a list of sublists. cf. http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ for x in items: if isinstance(x, Iterable): yie...
python
def center_visible_line(self, before_scroll_offset=False, after_scroll_offset=False): """ Like `first_visible_line`, but for the center visible line. """ return (self.first_visible_line(after_scroll_offset) + (self.last_visible_line(before_scro...
python
def get_nehrp_classes(self, sites): """ Site classification threshholds from Section 4 "Site correction coefficients" p. 205. Note that site classes E and F are not supported. """ classes = sorted(self.NEHRP_VS30_UPPER_BOUNDS.keys()) bounds = [self.NEHRP_VS30_UPP...
java
public void modifyIdentityProvider(final Map<String, Object> changedValues) { AddressTemplate template = IDENTITY_PROVIDER_TEMPLATE.replaceWildcards(federation, identityProvider); modify(template, identityProvider, changedValues); }
python
def main(): """Primary entry point; we supply '/', but the class brings '/metadata'""" app = apikit.APIFlask(name="Hello", version="0.0.1", repository="http://example.repo", description="Hello World App") # pylint: disable=unu...
python
def annotate(self, word): '''Annotate 'word' for syllabification, stress, weights, and vowels.''' info = [] # e.g., [ ('\'nak.su.`tus.ta', 'PUSU', 'HLHL', 'AUUA'), ] for syllabification, _ in syllabify(self.normalize(word), stress=True): stresses = '' weights = '' ...
python
def which(cmd): """ Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python") """ def is_exe(fp): return os.path.isfil...
java
@Override public void setSpaceACLs(final String spaceId, final Map<String, AclType> spaceACLs) throws ContentStoreException { execute(new Retriable() { @Override public Boolean retry() throws ContentStoreException { // The actual m...
java
public void process(File file) throws Exception { openLogFile(); int blockIndex = 0; int length = (int) file.length(); m_buffer = new byte[length]; FileInputStream is = new FileInputStream(file); try { int bytesRead = is.read(m_buffer); if (bytesRead != le...
java
public static <T extends Collection<String>> T findAll(String regex, CharSequence content, int group, T collection) { if (null == regex) { return collection; } return findAll(Pattern.compile(regex, Pattern.DOTALL), content, group, collection); }
java
public boolean preValidateInfoTopic(final InfoTopic infoTopic, final ContentSpec contentSpec, final Map<String, InfoTopic> infoTopics) { // Check if the app should be shutdown if (isShuttingDown.get()) { shutdown.set(true); return false; } boolean val...
python
def get_upvoted(self, *args, **kwargs): """Return a listing of the Submissions the user has upvoted. :returns: get_content generator of Submission items. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. As a ...
python
def execute(paramPath, executable='pParse.exe'): """Execute pParse with the specified parameter file. :param paramPath: location of the pParse parameter file :param executable: must specify the complete file path of the pParse.exe if its location is not in the ``PATH`` environment variable. :r...
python
def parse_subpackets(s): """See https://tools.ietf.org/html/rfc4880#section-5.2.3.1 for details.""" subpackets = [] total_size = s.readfmt('>H') data = s.read(total_size) s = util.Reader(io.BytesIO(data)) while True: try: first = s.readfmt('B') except EOFError: ...
python
def may_be_null_is_nullable(): """If may_be_null returns nullable or if NULL can be passed in. This can still be wrong if the specific typelib is older than the linked libgirepository. https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47 """ repo = GIRepository() repo.require("GLib", "2....
java
public void populateInfo(List<? extends Profile> profiles) { Map<String, Map<String, Object>> fieldMaps = CollectUtils.newHashMap(); for (Profile profile : profiles) { Map<String, Object> aoDimensions = CollectUtils.newHashMap(); for (Property property : profile.getProperties()) { String val...
python
def check_opr_category(self, opr, category): """ 检查权限是否在指定目录下 """ for path in self.routes: route = self.routes[path] if opr in route['oprs'] and route['category'] == category: return True return False
python
def Proxy(f): """A helper to create a proxy method in a class.""" def Wrapped(self, *args): return getattr(self, f)(*args) return Wrapped
java
Observable<ComapiResult<Void>> doAddParticipants(@NonNull final String token, @NonNull final String conversationId, @NonNull final List<Participant> participants) { return wrapObservable(service.addParticipants(AuthManager.addAuthPrefix(token), apiSpaceId, conversationId, participants).map(mapToComapiResult()),...
java
IonStruct getIonRepresentation() { synchronized (this) { IonStruct image = myImage; if (image == null) { // Start a new image from scratch myImage = image = makeIonRepresentation(myImageFactory); } return i...
java
private void setSchemas(SecorConfig config) { Map<String, String> schemaPerTopic = config.getORCMessageSchema(); for (Entry<String, String> entry : schemaPerTopic.entrySet()) { String topic = entry.getKey(); TypeDescription schema = TypeDescription.fromString(entry ...
python
def sub(cls, *mixins_and_dicts, **values): """Create and instantiate a sub-injector. Mixins and local value dicts can be passed in as arguments. Local values can also be passed in as keyword arguments. """ class SubInjector(cls): pass mixins = [ x for x in...
java
public SVGPath relativeLineTo(double x, double y) { return append(PATH_LINE_TO_RELATIVE).append(x).append(y); }
python
def process(self, formdata=None, obj=None, data=None, **kwargs): '''Wrap the process method to store the current object instance''' self._obj = obj super(CommonFormMixin, self).process(formdata, obj, data, **kwargs)
python
def rolldim(P, n=1): """ Roll the axes. Args: P (Poly) : Input polynomial. n (int) : The axis that after rolling becomes the 0th axis. Returns: (Poly) : Polynomial with new axis configuration. Examples: >>> x,y,z = variable(3) >>> P = x*x*x + y*y + z ...
java
public double getDouble(String name, double defaultValue) { String valueString = getTrimmed(name); if (valueString == null) return defaultValue; return Double.parseDouble(valueString); }
python
def integrate_data(xdata, ydata, xmin=None, xmax=None, autozero=0): """ Numerically integrates up the ydata using the trapezoid approximation. estimate the bin width (scaled by the specified amount). Returns (xdata, integrated ydata). autozero is the number of data points to use as an estimate of t...
python
def mark_good(self, server_addr): """Mark server address as good :param server_addr: (ip, port) tuple :type server_addr: :class:`tuple` """ self.list[server_addr].update({'quality': CMServerList.Good, 'timestamp': time()})
java
private static <V,F> Boolean hasCompatibleVisitMethod(V visitor, F fluent) { for (Method method : visitor.getClass().getMethods()) { if (!method.getName().equals(VISIT) || method.getParameterTypes().length != 1) { continue; } Class visitorType = method.getPara...
python
def _dedentlines(lines, tabsize=8, skip_first_line=False): """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines "lines" is a list of lines to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first...
java
static void addCommitStep(final OperationContext context, final ConfigurationPersistence configurationPersistence) { // This should only check that it's a server for the commit step. The logging.properties may need to be written // in ADMIN_ONLY mode if (context.getProcessType().isServer()) { ...
python
def run_step(context): """pypyr step saves current utc datetime to context. Args: context: pypyr.context.Context. Mandatory. The following context key is optional: - nowUtcIn. str. Datetime formatting expression. For full list of possible expressions, ...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'pagination') and self.pagination is not None: ...
java
public static EnumMap<InterceptorMethodKind, List<Method>> getEJBInterceptorMethods (Class<?> ejbClass , EnterpriseBean bean , LinkedList<Class<?>> lifoClasses , J2EEName name) throws EJBConfigurationE...
python
def result(self): """Gets the frozen statistics to serialize by Pickle.""" try: cpu_time = max(0, time.clock() - self._cpu_time_started) wall_time = max(0, time.time() - self._wall_time_started) except AttributeError: cpu_time = wall_time = 0.0 return ...
python
def MapItemsIterator(function, items): """Maps ItemsIterator via given function.""" return ItemsIterator( items=map(function, items), total_count=items.total_count)
python
def jsonarrindex(self, name, path, scalar, start=0, stop=-1): """ Returns the index of ``scalar`` in the JSON array under ``path`` at key ``name``. The search can be limited using the optional inclusive ``start`` and exclusive ``stop`` indices. """ return self.execute_com...
java
public byte[] encodeBytes(byte[] rgbValue) throws NoSuchAlgorithmException { rgbValue = this.encrypt(rgbValue); rgbValue = super.encodeBytes(rgbValue); // Base64 encoding return rgbValue; }
java
@Override public void notifyException(Throwable exception) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyException", new Object[] { this, exception }); // If an asynch consumer is registered we need to let them know something went wrong ...
java
public static TagAttributeInfo getIdAttribute(TagAttributeInfo a[]) { for (int i=0; i<a.length; i++) { if (a[i].getName().equals(ID)) { return a[i]; } } return null; // no such attribute }
java
public void activateOptions() { if (header) { getLocalHostname(); } if (layout != null && layout.getHeader() != null) { sendLayoutMessage(layout.getHeader()); } layoutHeaderChecked = true; }
python
def _constant_probability_density(self, X): """Probability density for the degenerate case of constant distribution. Note that the output of this method will be an array whose unique values are 0 and 1. More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution ...
python
def write_monitor_keyring(keyring, monitor_keyring, uid=-1, gid=-1): """create the monitor keyring file""" write_file(keyring, monitor_keyring, 0o600, None, uid, gid)
java
public static void doPostIntercept( InterceptorContext context, List/*< Interceptor >*/ interceptors ) throws InterceptorException { if ( interceptors != null ) { PostInvokeInterceptorChain chain = new PostInvokeInterceptorChain( context, interceptors ); chain.continu...
java
private void addEmbeddedProperties(ClassMetadata classMetadata, SinglePropertyMetadata propertyMetadata) { ClassMetadata nested = new ClassMetadata(); nested.setPersistentClass(propertyMetadata.getPropertyType()); visit(nested.getPersistentClass(), nested, new HashSet<String>()); for (Iterator<String> i = neste...
python
def set_sensors(self, sensors): """ Sets the 4 sensors with temperature in degree Celcius. :param sensors: list of 4 sensor temperatures corresponding to sensor 1 = I/0 controller inlet sensor 2 = I/0 controller outlet sensor 3 = NPE inlet sensor 4 = NPE outlet ...
java
private void registerLockScreenReceiver(Context context) { mLockScreenReceiver = new LockScreenReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION_TOGGLE_PLAYBACK); intentFilter.addAction(ACTION_NEXT_TRACK); intentFilter.addAction(ACTION_PREV...
python
def find_one(cls, pattern, string, flags=0): """JS-like match object. Use index number to get groups, if not match or no group, will return ''. Basic Usage:: >>> from torequests.utils import find_one >>> string = "abcd" >>> find_one("a.*", string) <toreq...
python
def user_agent(self): """ its a user agent string! """ version = "" project_root = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(project_root, 'VERSION')) as version_file: version = version_file.read().strip() return "Python Snow A...
java
@Override public long getLong(String fldName) throws RemoteException { try { fldName = fldName.toLowerCase(); // to ensure case-insensitivity return (Long) s.getVal(fldName).castTo(BIGINT).asJavaVal(); } catch (RuntimeException e) { rconn.rollback(); throw e; } }
java
public static Optional<Guid> getWorkUnitGuid(State state) throws IOException { if (state.contains(WORK_UNIT_GUID)) { return Optional.of(Guid.deserialize(state.getProp(WORK_UNIT_GUID))); } return Optional.absent(); }
java
public static Object fromRDF(Object input, RDFParser parser) throws JsonLdError { return fromRDF(input, new JsonLdOptions(""), parser); }
java
public static void exports(Media media, Collection<Media> levels, Media sheetsConfig, Media groupsConfig) { Check.notNull(media); Check.notNull(levels); Check.notNull(sheetsConfig); Check.notNull(groupsConfig); final CircuitsExtractor extractor = new CircuitsExtractor...
python
def sg_seek_streamer(self, index, force, value): """Ackowledge a streamer.""" force = bool(force) err = self.sensor_graph.acknowledge_streamer(index, value, force) return [err]
python
def list(self, **params): """ Retrieve all deals Returns all deals available to the user according to the parameters provided :calls: ``get /deals`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which r...
python
def custom_resource(self, name, restype, factclass, props): """ Domain custom resource. :param str name: Resource name. :param str restype: Resource type. :param str factclass: Resource factory class. :param dict props: Resource properties. :rtype: CustomResource """ r...
java
@Override public void setAdd(String setName, int ttlSeconds, String... message) { redisClient.sadd(setName, message); expire(setName, ttlSeconds); }
java
private static List<Future<List<DiscoveryIncomingMessage>>> sendDiscoveryRequests(DiscoveryOutgoingMessage pOutMsg, int pTimeout, LogHandler pLogHan...
java
public static ExprString toExprString(Expression expr) { if (expr instanceof ExprString) return (ExprString) expr; if (expr instanceof Literal) return expr.getFactory().createLitString(((Literal) expr).getString(), expr.getStart(), expr.getEnd()); return new CastString(expr); }
java
public boolean next() { if( indexes.length <= 1 || permutation >= total-1 ) return false; int N = indexes.length-2; int k = N; swap(k, counters[k]++); while( counters[k] == indexes.length ) { k -= 1; swap(k, counters[k]++); } swap(counters[k], k); //before while (k < indexes.length - 1) { ...
java
private static void addCtor(ClassWriter cw, String tieClassName, String parentClassName, String servantDescriptor) { MethodVisitor mv; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, INDENT + "adding method : <init> ()V"); // ----------------------...
java
public EEnum getIOBYoaOrent() { if (iobYoaOrentEEnum == null) { iobYoaOrentEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(40); } return iobYoaOrentEEnum; }
java
@Override public String lset(final byte[] key, final long index, final byte[] value) { checkIsInMultiOrPipeline(); client.lset(key, index, value); return client.getStatusCodeReply(); }