id
stringlengths
7
14
text
stringlengths
1
37.2k
1346655_17
public static Point offset(int amount, Point point) { return offset(new Point(amount, amount), point); }
1350993_0
public static synchronized SmoothieContainer getContainer() { if (container == null) { // This should really be done by a ServletContextListener when the webapp loads, but for now we are not modifying hudson-core, so bootstrap the container here. return new SmoothieContainerBootstrap().bootstrap(); ...
1354219_7
public static File zip(List<String> fileNames, String zipPath) { return zip(fileNames, zipPath, null); }
1358036_51
public Set<IRI> getReferredGraphs(String queryString, IRI defaultGraph) throws ParseException { Set<IRI> referredGraphs; JavaCCGeneratedSparqlPreParser parser = new JavaCCGeneratedSparqlPreParser(new StringReader(queryString)); SparqlUnit sparqlUnit; sparqlUnit = parser.parse(); boolean referringVar...
1361294_0
public List<Person> list() { try (Connection con = ds.getConnection()) { ArrayList<Person> persons = new ArrayList<Person>(); ResultSet rs = con.createStatement().executeQuery(QUERY); while (rs.next()) { persons.add(read(rs)); } return persons; } catch (SQLExc...
1365016_6
public EnumSet<Key> getKeysReleasedSince(final KeyboardState previous) { final EnumSet<Key> result = EnumSet.copyOf(previous._keysDown); result.removeAll(_keysDown); return result; }
1365306_97
public static LocalDateTimeValue from(LocalDateTime value) { LocalDateTimeValue result = new LocalDateTimeValue(); result.setValue(value); return result; }
1365699_2
@Override public int run(String[] args) throws Exception { Map<String,String> parsedArgs = parseArgs(args); Path inputPath = new Path(parsedArgs.get("--input")); Path outputPath = new Path(parsedArgs.get("--output")); Job wordCount = prepareJob(inputPath, outputPath, TextInputFormat.class, FilteringWordCountM...
1367811_46
public static boolean isAuthor(Job job) { User user = User.current(); return !(user == null || job == null || job.getCreatedBy() == null) && job.getCreatedBy().equals(user.getId()); }
1368680_45
@Override public String getPersisterId(final ScopePath scopePath, final Collection<String> configPersisterIds) { if (configPersisterIds.size() == 0) { throw new IllegalStateException("Didn't get any configuration persister!"); //$NON-NLS-1$ } if (developmentMode && scopePath != null && scopePath.findScopeByName(Us...
1379319_1
public static PVector calculateImpulse(PVector v1, PVector v2, float m1, float m2, float elasticity, PVector normal) { assert v1 != null : "Physics.calculateImpulse: v1 must be a valid PVector"; assert v2 != null : "Physics.calculateImpulse: v2 must be a valid PVector"; assert normal != null : "Physics.calculateI...
1381837_0
public static List<ComplexityThreshold> convertAbacusThresholdsToComplexityThresholds(String[] propertyThresholds) { List<ComplexityThreshold> complexityThresholds = new ArrayList<ComplexityThreshold>(); String[] temp; for (String propertyThreshold : propertyThresholds) { temp = propertyThreshold.split(PARS...
1381874_35
public static String getId(Object document) { return getAccessor(document).getId(document); }
1382471_0
public static boolean isProductized() { return productized; }
1387581_34
public static String getOperationName(TMessage message) { String ret=Character.toLowerCase(message.getName().charAt(0))+ message.getName().substring(1); ret = ret.replaceAll("Request", ""); ret = ret.replaceAll("Response", ""); ret = ret.replaceAll("Req", ""); ret = ret.replaceAll("Resp", ""); return(ret...
1390520_0
public void registerObserver(Context context, Object instance, Method method, Class event) { if (!isEnabled()) return; if( context instanceof Application ) throw new RuntimeException("You may not register event handlers on the Application context"); Map<Class<?>, Set<ObserverReference<?>>> methods...
1390800_7
static Map<String, String> parse(String installationLog, Log logger) { Map<String, String> downloadedDependencies = new HashMap<>(); String[] lines = installationLog.split("\\R"); MutableBoolean expectingPackageFilePath = new MutableBoolean(false); String packageName = ""; for (String line : lines)...
1391650_7
public static String consume(final InputStream stream, final Charset encoding) throws IOException { return maybeConsume(stream, encoding, 0); }
1397974_22
@Override public KType getLast() { assert size() > 0 : "The deque is empty."; return Intrinsics.<KType> cast(buffer[oneLeft(tail, buffer.length)]); }
1404216_67
public static PrintStream create(OutputStream out, Charset charset, Object sharedLock) { Enhancer e = new Enhancer(); e.setSuperclass(PrintStream.class); e.setCallback(new SynchronizedMethodInterceptor(sharedLock)); e.setNamingPolicy(new PrefixOverridingNamingPolicy(SynchronizedPrintStream.class.getName...
1404666_0
public void coveredByUnitTest() { System.out.println("Hello, world."); }
1406218_11
@Override public TransformationContext clone() { TransformationContext newContext; try { newContext = (TransformationContext) super.clone(); } catch (CloneNotSupportedException e) { // Should never happen throw new RuntimeException("Failed to clone object", e); } return newC...
1407946_8
public void setCustomWidthUnit(EnumWidthUnit enumWidthUnit) { comboBoxWidthUnit.setSelectedItem(enumWidthUnit); }
1415645_1
public Statement read() throws Exception, UnexpectedInputException, ParseException { Customer customer = customerReader.read(); if(customer == null) { return null; } else { Statement statement = new Statement(); statement.setCustomer(customer); stat...
1421658_18
public void afterPropertiesSet() throws Exception { this.connectSupport = new ConnectSupport(sessionStrategy); this.connectSupport.setUseAuthenticateUrl(true); if (this.applicationUrl != null) { this.connectSupport.setApplicationUrl(applicationUrl); } }
1421692_13
public static <K, V> Map<K, List<V>> groupBy(Collection<V> list, Closure<K, V> closure) { if (null == closure) { throw new IllegalArgumentException("closure must not be null!"); } Map<K, List<V>> ret = new HashMap<K, List<V>>(); if (null != list) { for (V v : list) { K k = closure.execute(v); if (!ret.con...
1443269_38
public BlockCache(BlurMetrics metrics, boolean directAllocation, long totalMemory) { this(metrics,directAllocation,totalMemory,_128M); }
1446919_9
public String checkName(String name) { build(); String rval = checkName(name, malesDB); if (rval == null) { rval = checkName(name, femalesDB); } return rval; }
1450115_60
public String toRelativeUrl() { StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder(); if (MiscUtils.isNonEmpty(path)) sb.append(path); else sb.append('/'); if (query != null) sb.append('?').append(query); return sb.toString(); }
1452945_0
public AbstractPE getPE(String keyValue) { AbstractPE pe = null; try { pe = (AbstractPE) lookupTable.get(keyValue); if (pe == null) { pe = (AbstractPE) prototype.clone(); pe.initInstance(); } // update the last update time on the entry lookupTable....
1458461_1
public void setPropertyFile(File file) { this.propertyFile = file; }
1459400_0
public void clear() throws IOException { rewound = false; diskObjectCount = 0; list.clear(); if (raFile != null) { raFile.seek(0); raFile.setLength(0); } }
1459953_8
public static <I, O> Function<I, Try<O>> of(ThrowingFunction<I, O> function) { return input -> { try { O result = function.apply(input); return new Success<>(result); } catch (RuntimeException e) { throw e; // we don't want to wrap runtime exceptions } cat...
1463490_1023
public String transform(Source xml, Source xslt) { return XMLUtils.transform(xml, xslt); }
1469749_197
public void setConfidence(int value) { this.confidence = value; }
1475915_4
public String translate(String text) { for (TagTranslator translator : tagTranslators) { text= translator.translate(text); } return text; }
1481910_4
@Override public OutputStream openBinary(JPackage pkg, String fileName) throws IOException { FileObject resource = filer.createResource(StandardLocation.SOURCE_OUTPUT, pkg.name(), fileName); return resource.openOutputStream(); }
1484463_8
@Override public Object process(Object value) { Long time = System.currentTimeMillis(); if (this.lastValue == null) { this.lastUpdate = time; this.lastValue = value; return null; // no value at this time } if (!(value instanceof Number)) { throw new IllegalArgumentException(String.format("Rate r...
1493029_0
public void loadResource(URL url) { try { // Is Local loadResource( new File( url.toURI() ), "" ); } catch (IllegalArgumentException iae) { // Is Remote loadRemoteResource( url ); } catch (URISyntaxException e) { throw new JclException( "URISyntaxException", e ); ...
1495584_7
public T execute() { try { return constructor.newInstance(constructionArguments); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); /* * Due to constraints on the constructor, cause can only be an * unchecked exception. */ if (caus...
1502367_17
public static List<Long> typeConvert(Iterable<String> list) { List<Long> result = new ArrayList<Long>(); for (String element : list) { if (StringUtils.isNotBlank(element)) { result.add(NumberUtils.toLong(element)); } } return result; }
1511246_13
@SuppressWarnings("unchecked") public <T> T createProxy(T obj, final InvocationHandler handler) { Class<?> c = obj.getClass(); Class<?> pc = getClassProxy(c); Constructor<?> cons; try { cons = pc.getConstructor(new Class<?>[] { InvocationHandler.class }); return (T) cons.newInstance(new ...
1516026_123
@Override public boolean call(final Entity entity, final Object oldValue, final Object newValue) { if (fieldHook.call(entity, oldValue, newValue)) { return true; } if (entity.getError(fieldDefinition.getName()) == null) { entity.addError(fieldDefinition, errorMessage); } return false...
1520524_34
@Override public synchronized AtomAtomMapping getFirstAtomMapping() { if (allAtomMCS.iterator().hasNext()) { return allAtomMCS.iterator().next(); } return new AtomAtomMapping(source, target); }
1526495_42
public SshUtil waitSsh(String ip, String user, String keyPath, int timeoutSeconds) throws SshNotConnected { SshWaiterCallable callable = new SshWaiterCallable(ip, user, keyPath); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<SshUtil> future = executor.submit(callable); Concurr...
1529680_0
String getJavaCommand() { if (configuration == null) { throw new IllegalStateException("setup not called"); } return configuration.getJavaHome() + File.separator + "bin" + File.separator + "java"; }
1535924_5
@Override public void stop( BundleContext bundleContext ) throws Exception { AccessManagerFactoryTracker managerFactoryTracker = getAccessManagerFactoryTracker(); if (null != managerFactoryTracker) { managerFactoryTracker.close(); } }
1545929_949
public static int compareBytes( byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { try { // head int cursor1 = s1; int cursor2 = s2; int h1 = b1[cursor1++] & 0xff; int h2 = b2[cursor2++] & 0xff; // nullity boolean null1 = (h1 & MASK_PRESE...
1548514_2
@Override public List<Function> getFunctions(RubyModule clazz) { // implemented as a fallback to Java through reified class, but maybe there's a better way to do this return new ClassDescriptor(toJavaClass(clazz)).methods; }
1549503_5
void shutdown(final JCacheManager jCacheManager) { synchronized (cacheManagers) { final ConcurrentMap<URI, JCacheManager> map = cacheManagers.get(jCacheManager.getClassLoader()); if(map != null && map.remove(jCacheManager.getURI()) != null) { jCacheManager.shutdown(); } } }
1551432_1
static public Set<String> getApacheNames(InputStream is) throws IOException, ArchiveException { Set<String> names = new HashSet<String>(); ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(is); ArchiveEntry entry; while ((entry = ais.getNextEntry()) != null) { if (!entry.isDirectory()) ...
1553760_291
@Override public String process(String uri) { String newUri = preprocessUri(uri); if (!newUri.equals(uri)) { newUri = prependWithBasePackage(newUri); if (SourceVersion.isName(newUri)) { if (isPotentialPackageName(newUri)) { return toPackagePage(newUri); } return toTypePage(newUri); } } return uri...
1554165_0
public HashMap<Enum, String> getDb() { return db; }
1555964_9
public boolean isBitSet(int bit) { long bitMask = Long.rotateLeft(1, bit); long result = this.bitMaskValue & bitMask; if (result != 0) { return true; } return false; }
1557148_32
public static Calendar getCalendar(String yyyy, String mm, String dd) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, Integer.valueOf(yyyy)); cal.set(Calendar.MONTH, Integer.valueOf(mm) - 1); cal.set(Calendar.DATE, Integer.valueOf(dd)); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(C...
1558503_0
public static Date create(int year, int month, int date) { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(year, month - 1, date); return cal.getTime(); }
1574061_514
public Object evaluate(Object object) { return evaluate(object, Object.class); }
1575956_121
public static boolean areEntriesOfLedgerStoredInTheBookie(long ledgerId, BookieId bookieAddress, LedgerManager ledgerManager) { try { LedgerMetadata ledgerMetadata = ledgerManager.readLedgerMetadata(ledgerId).get().getValue(); return areEntriesOfLedgerStoredInTheBookie(ledgerId, bookieAddres...
1577630_11
public M get(final ListNode<T> list) { if (null == list) { throw new IllegalArgumentException("null key"); } return (null == helper) ? null : helper.get(list); }
1579900_0
public int getPercentile (float value) { if (value < _min) { return 0; } else if (value > _max) { return 100; } else { return _percentile[toBucketIndex(value)]; } }
1579936_3
public String merge (String newlyGenerated, String previouslyGenerated) throws Exception { // Extract the generated section names from the output and make sure they're all matched Map<String, Section> sections = Maps.newLinkedHashMap(); Matcher m = _sectionDelimiter.matcher(newlyGenerated); while (m...
1581151_6
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final MacAddress that = (MacAddress) o; return Arrays.equals(array, that.array); }
1583138_2
public int getTotalPages() { return totalPages; }
1584558_0
public static boolean isHiddenSingle(SDKSquare s, SDKBoard board) { LinkedList<SDKSquare> zsqrs = board.getSquaresInZone(s); zsqrs.remove(s); LinkedList<SDKSquare> csqrs = board.getSquaresInCol(s.col); csqrs.remove(s); LinkedList<SDKSquare> rsqrs = board.getSquaresInRow(s.row); rsqrs.remove(s); HashSet<Integer> ...
1589946_11
public static AttributeSearchResponse fromCatalogAPI(AttributeResponse result) { AttributeSearchResponse attributeSearchResponse = new AttributeSearchResponse(); if (inputIsValid(result)) { return attributeSearchResponse; } AttributeResponse.Attributes resultAttributes = result.getAttributes(...
1592475_4
public void traverse( Object instance, Selector selector, HierarchicalModel<?> model, YogaRequestContext context ) throws IOException { if (instance != null) { if (instance instanceof Iterable) { traverseIterable( (Iterable<?>) instance, selector, (ListHierarchicalModel<?>) m...
1595052_4
@Override public boolean isSlave() { boolean slave = true; for (String name : masterSlaveJdbcManagerFactoryNames) { slave &= isSlave(name); } return slave; }
1597325_40
public void bind(Request request, Object o) { final Multimap<String, String> map = request.params(); //bind iteratively (last incoming param-value per key, gets bound) for (Map.Entry<String, Collection<String>> entry : map.asMap().entrySet()) { String key = entry.getKey(); // If there are multiple entry...
1603876_2
public FeatureFlags getFlag(String flagName) { urn (FeatureFlags) invokeStaticMethod("valueOf", new Object[] { flagName }, String.class); }
1604565_0
public Iterable<Vertex> getVertices() { Collection<Iterable<Vertex>> base = new LinkedList<Iterable<Vertex>>(); for (int pos = 0; pos < bases.length; pos++) { base.add(new MultiVertexIterable(pos)); } return new MultiIterable<Vertex>(base); }
1605107_158
@Deprecated public void computeGeoCorners(final SLCImage meta, final Orbit orbit, final Window tile) throws Exception { double[] phiAndLambda; final double l0 = tile.linelo; final double lN = tile.linehi; final double p0 = tile.pixlo; final double pN = tile.pixhi; // compute Phi, Lambda for T...
1608936_6
public static <T> int indexOf(T[] array, T element) { for ( int i = 0; i < array.length; i++ ) { if ( array[i].equals( element ) ) { return i; } } return -1; }
1613090_15
@Override public Object get(int fieldNum) { try { StructField fref = soi.getAllStructFieldRefs().get(fieldNum); return HCatRecordSerDe.serializeField( soi.getStructFieldData(wrappedObject, fref), fref.getFieldObjectInspector()); } catch (SerDeException e) { th...
1619254_27
public Degree min(Degree comp) { return new SimpleDegree( Math.min(this.getValue(), comp.getValue()) ); }
1619733_7
public Database parse( File file ) throws IOException { // Read the file into a single string ... String ddl = readFile(file); // Create the object that will parse the file ... DdlParsers parsers = new DdlParsers(); AstNode node = parsers.parse(ddl, file.getName()); // Now process the AST ... ...
1626780_5
public SubjectRef getOrCreateSubjectRef(String type, String name) throws SQLException { final SubjectRef ret = SubjectRef.unresolved(type, name); allocateSubjectRef(ret); return ret; }
1628050_3
public static void validate (APICredential cred, SecretKey secretKey, byte[]... payLoad) throws NoSuchAlgorithmException, InvalidKeyException { if (!VERSION.equals(cred.getVersion())) throw new IllegalArgumentException ("unsupported.version"); assertNotNull(payLoad, "invalid.payLoad"); assertNotNull...
1639726_10
public MimeMessage createMessage(String from, String to, String cc, String subject, SOAPMessage soapMessage) throws ConnectionException { return createMessage(from, to, cc, subject, soapMessage, createSession()); }
1642369_261
@Override public Object get(Object key) { if (key == null) { return null; } if (key instanceof String) { return new MessageCodeValue((String) key, NO_ARGUMENTS).getReturnValue(); } if (this.messageSource instanceof ObjectMessageSource) { return new ObjectMessageValue(key, NO_ARGUMENTS).getReturnValue(); } ...
1644461_572
protected NamedSelector parseNamedSelector( TokenStream tokens, TypeSystem typeSystem ) { SelectorName name = parseSelectorName(tokens, typeSystem); SelectorName alias = null; if (tokens.canConsume("AS")) alias = parseSelectorName(tokens, typeSystem); return n...
1644585_55
@Override public void describeTo(Description description) { description.appendText("a JSON object matching JSONpath \"" + jsonPath + "\""); if (matcher != null) { description.appendText(" with "); matcher.describeTo(description); } }
1645877_7
@Override public String getResourceName() { return resourceName; }
1658141_134
public String addContact(Contact contact) { // Nombre obligatorio teniendo en cuenta espacios antes y despues. if(contact.getFirstName() == null || contact.getFirstName().trim().length() < 1) { throw new InvalidContactException(); } // Para comprobar duplicados de contactos por nombre, decidimos...
1660918_16
public static boolean areEquivalent(Dependency l, Dependency r) { if (l == r) { return true; } if ((l == null) && (r == null)) { return true; } else if ((l == null) || (r == null)) { return false; } return areEquivalent(l.getCoordinate(), r.getCoordinate()); }
1666060_2
public double getAlpha() { return alpha; }
1670551_43
public void add(final NodeQuery query, final NodeBooleanClause.Occur occur) { super.addChild(query, occur); }
1672467_0
public static List<String> utf8byteSizeSplit(String s, int maxChunkBytes) { if (maxChunkBytes < 6) { throw new IllegalArgumentException("Max UTF-8 chunk size cannot be less than 6"); } byte[] bytes = s.getBytes(UTF8); List<String> result = new ArrayList<String>(); int chunkStartOffset = 0;...
1676303_13
@Override public final Activity unmarshall(final String s) { try { return mapper.readValue(s, ComplianceActivity.class).toActivity(); } catch (final IOException | UncheckedIOException e) { logger.warn("Failed to parse compliance activity: " + s, e); return null; } }
1688262_32
public static int toInt(Object o, int def) { if (!(o instanceof Integer)) { return def; } return (Integer) o; }
1691340_39
@Override public T findEntity(final Serializable id) throws EntityException { return findEntity(getEntityClass(), id); }
1707059_12
protected Graph<String, DefaultEdge> buildModuleGraph(Map<String, ? extends EnunciateModule> modules) { Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class); for (String moduleName : modules.keySet()) { graph.addVertex(moduleName); } for (EnunciateModule modul...
1710792_5
static BoxerUnboxer<?,? extends Writable> createOutputType(String type) { if ("text".equals(type)) { return new TextBoxerUnboxer(); } else if ("long".equals(type)) { return new LongBoxerUnboxer(); } else if ("double".equals(type)) { return new DoubleBoxerUnboxer(); } else if ("json".equals(typ...
1711412_0
public void setCompiler(Compiler compiler) { this.compiler = compiler; }
1711467_210
@Override public void process(Class clazz, EntityMetadata metadata) { if (LOG.isDebugEnabled()) LOG.debug("Processing @Entity(" + clazz.getName() + ") for Persistence Object."); populateMetadata(metadata, clazz, puProperties); }
1720284_21
@Override public List<Status> getStatus(Repository repository, String sha1) { if (repository == null) { throw new NullPointerException("Repository can't be null"); } if (sha1 == null) { throw new NullPointerException("SHA1 can't be null"); } log.info("Checking status for {} @ {}", repository.getDirectory(), s...
1724015_6
static String artifactToMvn(Artifact artifact) { return artifactToMvn(RepositoryUtils.toArtifact(artifact)); }
1742658_4
@Override public void resetMetaData() { super.resetMetaData(); textArea.setValue(null); }
1743159_2
@Override public void insert(ServiceObject item) throws ExistingResourceException, PersistentStoreFailureException { try { if (logger.isDebugEnabled()) { logger.debug("inserting: " + item.toDBObject()); } database.requestStart(); database.requestEnsureConnection(); DBObject db = item.toDBObject(); // ...
1743723_2
@Override public synchronized List<ScriptContext> load(File scriptDescriptor) throws Exception { Preconditions.checkNotNull(scriptDescriptor, "scriptDescriptor"); final JAXBContext c = JAXBContext.newInstance(ScriptInfo.class, ScriptList.class); final Unmarshaller u = c.createUnmarshaller(); final ScriptList l...
1757703_8
public static <T> List<T> moveValuesToIndex(List<? extends T> values, List<? extends T> moveValues, int index, boolean allowAdd) { int size = values.size(); if (index > size) { throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + values.size()); } List<T> result = new ArrayL...