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();
}
return container;
} |
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 referringVariableNamedGraph = false;
if (sparqlUnit.isQuery()) {
Query q = sparqlUnit.getQuery();
DataSet dataSet = q.getDataSet();
if (dataSet != null) {
referredGraphs = dataSet.getDefaultGraphs();
referredGraphs.addAll(dataSet.getNamedGraphs());
} else {
referredGraphs = new HashSet<IRI>();
}
GroupGraphPattern queryPattern = q.getQueryPattern();
if (queryPattern != null) {
Set<GraphPattern> graphPatterns = queryPattern.getGraphPatterns();
for (GraphPattern graphPattern : graphPatterns) {
}
}
referringVariableNamedGraph = q.referringVariableNamedGraph();
referringVariableNamedGraph = referringVariableNamedGraph(q);
} else {
Update u = sparqlUnit.getUpdate();
referredGraphs = u.getReferredGraphs(defaultGraph, graphStore);
}
if (referredGraphs.isEmpty()) {
if (referringVariableNamedGraph) {
return null;
}
referredGraphs.add(defaultGraph);
}
return referredGraphs;
} |
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 (SQLException e) {
throw new RuntimeException(e.getMessage(), e);
}
} |
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, FilteringWordCountMapper.class,
Text.class, IntWritable.class, WordCountReducer.class, Text.class, IntWritable.class, TextOutputFormat.class);
wordCount.waitForCompletion(true);
return 0;
} |
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(UserScopeDescriptor.NAME) != null) {
return InMemoryPersister.ID;
}
return persisterSelector.getPersisterId(scopePath, configPersisterIds);
} |
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.calculateImpulse: normal must be a valid PVector";
assert !(normal.x == 0 && normal.y == 0) : "Physics.calculateImpulse: normal must be nonzero";
PVector numerator = PVector.sub(v2, v1); // calculate relative velocity
numerator.mult(-1 - elasticity); // factor by elasticity
float result = numerator.dot(normal); // find normal component
result /= normal.dot(normal); // normalize
result /= (1 / m1 + 1 / m2); // factor in mass
return PVector.mult(normal, result);
} |
1381837_0 | public static List<ComplexityThreshold> convertAbacusThresholdsToComplexityThresholds(String[] propertyThresholds) {
List<ComplexityThreshold> complexityThresholds = new ArrayList<ComplexityThreshold>();
String[] temp;
for (String propertyThreshold : propertyThresholds) {
temp = propertyThreshold.split(PARSING_SEPARATOR);
Double thresholdValue = null;
if (temp.length > 1) {
thresholdValue = Double.valueOf(temp[1]);
}
complexityThresholds.add(new ComplexityThreshold(temp[0], thresholdValue));
}
return complexityThresholds;
} |
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 = registrations.get(context);
if (methods == null) {
methods = new HashMap<Class<?>, Set<ObserverReference<?>>>();
registrations.put(context, methods);
}
Set<ObserverReference<?>> observers = methods.get(event);
if (observers == null) {
observers = new HashSet<ObserverReference<?>>();
methods.put(event, observers);
}
/*
final Returns returns = (Returns) event.getAnnotation(Returns.class);
if( returns!=null ) {
if( !returns.value().isAssignableFrom(method.getReturnType()) )
throw new RuntimeException( String.format("Method %s.%s does not return a value that is assignable to %s",method.getDeclaringClass().getName(),method.getName(),returns.value().getName()) );
if( !observers.isEmpty() ) {
final ObserverReference observer = observers.iterator().next();
throw new RuntimeException( String.format("Only one observer allowed for event types that return a value annotation. Previously registered observer is %s.%s", observer.method.getDeclaringClass().getName(), observer.method.getName()));
}
}
*/
observers.add(new ObserverReference(instance, method));
} |
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) {
// Extract downloaded package name.
Matcher matcher = COLLECTING_PACKAGE_PATTERN.matcher(line);
if (matcher.find()) {
packageName = extractPackageName(downloadedDependencies, matcher, packageName, expectingPackageFilePath, logger);
continue;
}
// Extract downloaded file, stored in Artifactory.
matcher = DOWNLOADED_FILE_PATTERN.matcher(line);
if (matcher.find()) {
extractDownloadedFileName(downloadedDependencies, matcher, packageName, expectingPackageFilePath, logger);
continue;
}
// Extract already installed package name.
matcher = INSTALLED_PACKAGE_PATTERN.matcher(line);
if (matcher.find()) {
extractAlreadyInstalledPackage(downloadedDependencies, matcher, logger);
}
}
// If there is a package we are still waiting for its path, save it with empty path.
if (expectingPackageFilePath.isTrue()) {
downloadedDependencies.put(StringUtils.lowerCase(packageName), "");
}
return downloadedDependencies;
} |
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()));
e.setUseFactory(false);
return (PrintStream) e.create(
new Class[]{OutputStream.class, boolean.class, String.class},
new Object[]{out, false, charset.name()}
);
} |
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 newContext;
} |
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);
statement.setSecurityTotal(tickerDao.getTotalValueForCustomer(customer.getId()));
statement.setStocks(tickerDao.getStocksForCustomer(customer.getId()));
return statement;
}
} |
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.containsKey(k)) {
ret.put(k, new ArrayList<V>());
}
ret.get(k).add(v);
}
}
return ret;
} |
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.set(keyValue, pe, prototype.getTtl());
} catch (Exception e) {
logger.error("exception when looking up pe for key:" + keyValue, e);
}
return pe;
} |
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
} catch (Exception e) {
return new Failure<>(e);
}
};
} |
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 requested, but value '%s' of type '%s' is not a number", value.toString(),value.getClass().getName()));
}
double diff = ((Number) value).doubleValue() - ((Number) this.lastValue).doubleValue();
double timeChangeInSeconds = ((double)(time - this.lastUpdate)) / 1000.0;
double rate;
if(timeChangeInSeconds == 0.0)
rate = Double.NaN;
else {
rate = diff / timeChangeInSeconds;
if(Math.abs(rate) < EPS) {
rate = 0.0;
}
}
// overflow guards. Note that these use Double because the Numbers passed in are converted to doubles.
if (Double.isNaN(rate) || rate == Double.POSITIVE_INFINITY || rate == Double.NEGATIVE_INFINITY) {
log.warn("Overflow in rate calculation: val=%f, last val=%f; time=%tc, last time=%tc", ((Number) value).doubleValue(), ((Number) this.lastValue).doubleValue(), time, this.lastUpdate);
this.lastUpdate = time;
this.lastValue = value;
return null; // no value at this time
}
// success. update last values before returning
this.lastUpdate = time;
this.lastValue = value;
return rate;
} |
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 (cause instanceof Error) {
throw ((Error) cause);
} else {
throw ((RuntimeException) cause);
}
} catch (Exception e) {
throw new IllegalStateException("This should never happen. Due to previously checked constraints (see extractConstructor()), no exception may actually be caught here.", e);
}
} |
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 Object[] { handler });
} catch (Exception e) {
IllegalArgumentException ia = new IllegalArgumentException(
"Could not create a new instance of the class " +
pc.getName());
ia.initCause(e);
throw ia;
}
} |
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);
Concurrency.waitExecutor(executor, timeoutSeconds, TimeUnit.SECONDS, logger, "Could not ssh into node " + ip);
try {
SshUtil ssh = Concurrency.checkAndGetFromFuture(future);
if (ssh != null) {
return ssh;
} else {
throw new SshNotConnected("Could not SSH into " + ip);
}
} catch (ExecutionException e) {
throw new SshNotConnected("Could not SSH into " + ip);
} catch (IllegalStateException e) {
throw new SshNotConnected("Could not SSH into " + ip);
}
} |
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_PRESENT) == 0;
boolean null2 = (h2 & MASK_PRESENT) == 0;
if (null1) {
if (null2) {
return 0;
} else {
return -1;
}
} else if (null2) {
return +1;
}
// sign
boolean plus1 = (h1 & MASK_PLUS) != 0;
boolean plus2 = (h2 & MASK_PLUS) != 0;
if (plus1 && plus2 == false) {
return +1;
} else if (plus1 == false && plus2) {
return -1;
}
// scale
int scale1 = WritableComparator.readVInt(b1, cursor1);
int scale2 = WritableComparator.readVInt(b2, cursor2);
cursor1 += WritableUtils.decodeVIntSize(b1[cursor1]);
cursor2 += WritableUtils.decodeVIntSize(b2[cursor2]);
// bytesCount
int bytesCount1 = WritableComparator.readVInt(b1, cursor1);
int bytesCount2 = WritableComparator.readVInt(b2, cursor2);
cursor1 += WritableUtils.decodeVIntSize(b1[cursor1]);
cursor2 += WritableUtils.decodeVIntSize(b2[cursor2]);
DecimalBuffer d1 = BUFFER_MAIN.get();
d1.set(plus1, scale1, b1, cursor1, bytesCount1);
DecimalBuffer d2 = BUFFER_SUB.get();
d2.set(plus2, scale2, b2, cursor2, bytesCount2);
return DecimalBuffer.compare(d1, d2);
} catch (IOException e) {
throw new IllegalStateException(e);
}
} |
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())
names.add(entry.getName());
}
ais.close();
return names;
} |
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(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
} |
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, bookieAddress, ledgerMetadata);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
} catch (ExecutionException e) {
if (e.getCause() != null
&& e.getCause().getClass()
.equals(BKException.BKNoSuchLedgerExistsOnMetadataServerException.class)) {
LOG.debug("Ledger: {} has been deleted", ledgerId);
return false;
} else {
LOG.error("Got exception while trying to read LedgerMeatadata of " + ledgerId, e);
throw new RuntimeException(e);
}
}
} |
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.find()) {
Section section = extractGeneratedSection(m, newlyGenerated);
Preconditions.checkArgument(!sections.containsKey(section.name),
"Section '%s' used more than once", section.name);
sections.put(section.name, section);
}
// Merge with the previously generated source
StringBuilder merged = new StringBuilder();
m = _sectionDelimiter.matcher(previouslyGenerated);
int currentStart = 0;
while (m.find()) {
merged.append(previouslyGenerated.substring(currentStart, m.start()));
Section existingSection = extractGeneratedSection(m, previouslyGenerated);
Section newSection = sections.remove(existingSection.name);
if (newSection == null) {
// Allow generated sections to be dropped in the template, but warn in case
// something odd's happening
System.err.println("Dropping previously generated section '" + m.group(1)
+ "' that's no longer generated by the template");
} else if (existingSection.disabled) {
// If the existing code disables this generation, add that disabled comment
merged.append(existingSection.contents);
} else {
// Otherwise pop in the newly generated code in the place of what was there before
merged.append(newSection.contents);
}
currentStart = m.end();
}
// Add generated sections that weren't present in the old output before the last
// non-generated code. It's a 50-50 shot, so warn when this happens
for (Section newSection : sections.values()) {
System.err.println("Adding previously missing generated section '"
+ newSection.name + "' before the last non-generated text");
merged.append(newSection.contents);
}
// Add any text past the last previously generated section
merged.append(previouslyGenerated.substring(currentStart));
return merged.toString();
} |
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> zonePossibles = s.getPossible();
HashSet<Integer> rowPossibles = s.getPossible();
HashSet<Integer> colPossibles = s.getPossible();
for(SDKSquare s2 : rsqrs)
rowPossibles.removeAll(s2.getPossible());
for(SDKSquare s2 : csqrs)
colPossibles.removeAll(s2.getPossible());
for(SDKSquare s2 : zsqrs)
zonePossibles.removeAll(s2.getPossible());
return rowPossibles.size() == 1 || colPossibles.size() == 1 || zonePossibles.size() == 1;
} |
1589946_11 | public static AttributeSearchResponse fromCatalogAPI(AttributeResponse result) {
AttributeSearchResponse attributeSearchResponse = new AttributeSearchResponse();
if (inputIsValid(result)) {
return attributeSearchResponse;
}
AttributeResponse.Attributes resultAttributes = result.getAttributes();
attributeSearchResponse.setIncludedResults(result.getIncludedResults().intValue());
AttributeSearchResponse.Attributes attributes = new AttributeSearchResponse.Attributes();
attributeSearchResponse.setAttributes(attributes);
for (AttributeType attributeType : resultAttributes.getAttribute()) {
attributes.getAttribute().add(attributeType);
}
return attributeSearchResponse;
} |
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<?>) model, context );
}
else if (instance instanceof Map)
{
traverseMap( (Map<?,?>) instance, selector, (MapHierarchicalModel<?>) model, context );
}
else
{
traversePojo( instance, selector, (MapHierarchicalModel<?>) model, context );
}
}
else
{
model.finished();
}
} |
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, then this is a collection bind:
final Collection<String> values = entry.getValue();
// We guard against expression-injection with a regex validator.
if (!validate(key))
continue;
Object value;
if (values.size() > 1) {
value = Lists.newArrayList(values);
} else {
// If there is only one value, bind as per normal
String rawValue = Iterables.getOnlyElement(values); //choose first (and only value)
//bind from collection?
if (rawValue.startsWith(COLLECTION_BIND_PREFIX)) {
final String[] binding = rawValue.substring(COLLECTION_BIND_PREFIX.length()).split("/");
if (binding.length != 2)
throw new InvalidBindingException(
"Collection sources must be bound in the form '[C/collection/hashcode'. "
+ "Was the request corrupt? Or did you try to bind something manually"
+ " with a key starting '[C/'? Was: " + rawValue);
final Collection<?> collection = cacheProvider.get().get(binding[0]);
value = search(collection, binding[1]);
} else
value = rawValue;
}
//apply the bound value to the page object property
try {
evaluator.write(key, o, value);
} catch (PropertyAccessException e) {
// Do some better error reporting if this is a real exception.
if (e.getCause() instanceof InvocationTargetException) {
addContextAndThrow(o, key, value, e.getCause());
}
// Log missing property.
if (log.isLoggable(Level.FINER)) {
log.finer("A property [" + key +"] could not be bound,"
+ " but not necessarily an error.");
}
} catch (Exception e) {
addContextAndThrow(o, key, value, e);
}
}
} |
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 Tile corners
phiAndLambda = orbit.lp2ell(new Point(p0, l0), meta);
final double phi_l0p0 = phiAndLambda[0];
final double lambda_l0p0 = phiAndLambda[1];
phiAndLambda = orbit.lp2ell(new Point(p0, lN), meta);
final double phi_lNp0 = phiAndLambda[0];
final double lambda_lNp0 = phiAndLambda[1];
phiAndLambda = orbit.lp2ell(new Point(pN, lN), meta);
final double phi_lNpN = phiAndLambda[0];
final double lambda_lNpN = phiAndLambda[1];
phiAndLambda = orbit.lp2ell(new Point(pN, l0), meta);
final double phi_l0pN = phiAndLambda[0];
final double lambda_l0pN = phiAndLambda[1];
//// Select DEM values based on rectangle outside l,p border ////
// phi
phiMin = Math.min(Math.min(Math.min(phi_l0p0, phi_lNp0), phi_lNpN), phi_l0pN);
phiMax = Math.max(Math.max(Math.max(phi_l0p0, phi_lNp0), phi_lNpN), phi_l0pN);
// lambda
lambdaMin = Math.min(Math.min(Math.min(lambda_l0p0, lambda_lNp0), lambda_lNpN), lambda_l0pN);
lambdaMax = Math.max(Math.max(Math.max(lambda_l0p0, lambda_lNp0), lambda_lNpN), lambda_l0pN);
// a little bit extra at edges to be sure
// redefine it: no checks whether there are previous declarations
defineExtraPhiLam();
// phi
phiMin -= phiExtra;
phiMax += phiExtra;
// lambda
lambdaMax += lambdaExtra;
lambdaMin -= lambdaExtra;
computeIndexCornersNest();
computeDemTileSize();
cornersComputed = true;
} |
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) {
throw new IllegalStateException("SerDe Exception deserializing",e);
}
} |
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 ...
System.out.println(node.toString());
return processStatements(node);
} |
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(secretKey, "invalid.secret");
assertNotNull(cred.getHash(), "invalid.null.hash");
assertTimestamp(cred.getTimestamp());
assertEquals(computeHash(secretKey, cred.getTimestamp(), cred.getNonce(), payLoad), cred.getHash(), "invalid.hash");
} |
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();
}
throw new IllegalArgumentException("Unable to resolve " + key.getClass().getName()
+ " messages when not using an ObjectMessageSource.");
} |
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 new NamedSelector(name, alias);
} |
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 que
// quitamos directamente los espacios para siguientes operaciones.
contact.setFirstName(contact.getFirstName().trim());
// Para comprobar duplicados de contactos por nombre, decidimos que
// quitamos directamente los espacios para siguientes operaciones.
contact.setFirstName(contact.getFirstName().trim());
if(checkDuplicate(contact)) {
throw new InvalidContactException();
}
String id = idGenerator.newId();
contact.setId(id);
addressBookMap.put(id, contact);
return id;
} |
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;
int chunkLength = 0;
for (byte b : bytes) {
if (chunkLength + utf8CharBytes(b) > maxChunkBytes) {
// add chunk to result
result.add(new String(bytes, chunkStartOffset, chunkLength, UTF8));
// init next chunk
chunkStartOffset += chunkLength;
chunkLength = 0;
}
// add byte to current chunk
chunkLength++;
}
if (chunkLength > 0) {
result.add(new String(bytes, chunkStartOffset, chunkLength, UTF8));
}
return result;
} |
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 module : modules.values()) {
List<DependencySpec> dependencies = module.getDependencySpecifications();
if (dependencies != null && !dependencies.isEmpty()) {
for (DependencySpec dependency : dependencies) {
for (EnunciateModule other : modules.values()) {
if (dependency.accept(other)) {
graph.addEdge(other.getName(), module.getName());
}
}
if (!dependency.isFulfilled()) {
throw new EnunciateException(String.format("Unfulfilled dependency %s of module %s.", dependency.toString(), module.getName()));
}
}
}
}
for (EnunciateModule module : modules.values()) {
if (module instanceof DependingModuleAwareModule) {
Set<DefaultEdge> edges = graph.outgoingEdgesOf(module.getName());
Set<String> dependingModules = new TreeSet<String>();
for (DefaultEdge edge : edges) {
dependingModules.add(graph.getEdgeTarget(edge));
}
((DependingModuleAwareModule) module).acknowledgeDependingModules(dependingModules);
}
if (module instanceof ApiRegistryAwareModule) {
((ApiRegistryAwareModule) module).setApiRegistry(this.apiRegistry);
}
}
CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(graph);
Set<String> modulesInACycle = cycleDetector.findCycles();
if (!modulesInACycle.isEmpty()) {
StringBuilder errorMessage = new StringBuilder("Module cycle detected: ");
java.util.Iterator<String> subcycle = cycleDetector.findCyclesContainingVertex(modulesInACycle.iterator().next()).iterator();
while (subcycle.hasNext()) {
String next = subcycle.next();
errorMessage.append(next);
if (subcycle.hasNext()) {
errorMessage.append(" --> ");
}
}
throw new EnunciateException(errorMessage.toString());
}
return graph;
} |
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(type)) {
return new JsonBoxerUnboxer();
}
else if ("bytes".equals(type)) {
return new BytesBoxerUnboxer();
}
return null;
} |
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(), sha1);
if (!containsCommit(repository, sha1)) {
log.warn(String.format("Commit %s unknown in repository %s", sha1, repository.getDirectory()));
return Arrays.asList(Status.UNKNOWN);
}
List<Status> statuses = new ArrayList<Status>();
for (BuildResult result: dao.getAll(repository, sha1)) {
statuses.add(result.getExitCode() == 0 ? Status.OK : Status.ERROR);
}
switch (getState(sha1)) {
case RUNNING:
statuses.add(Status.RUNNING);
break;
case PENDING:
statuses.add(Status.PENDING);
break;
case NONE:
if (statuses.isEmpty()) {
statuses.add(Status.NEW);
}
break;
}
return statuses;
} |
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();
// db.put(ServiceBasicAttributeNames.SERVICE_CREATED_ON
// .getAttributeName(), new Date());
serviceCollection.insert(db, WriteConcern.SAFE);
database.requestDone();
logger.info("inserted Service Endpoint record with ID: "
+ item.getEndpointID());
// EventDispatcher.notifyRecievers(new Event(EventTypes.SERVICE_ADD,
// item
// .toJSON()));
} catch (MongoException e) {
if (e instanceof DuplicateKey) {
throw new ExistingResourceException("Endpoint record with ID: "
+ item.getEndpointID() + " - already exists", e);
} else {
throw new PersistentStoreFailureException(e);
}
}
} |
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 list = (ScriptList) u.unmarshal(scriptDescriptor);
final List<ScriptContext> contexts = CollectionFactory.newList();
for (ScriptInfo si : list.getScriptInfos()) {
final ScriptContext context = createContext(si, null);
if (context != null) {
this.contexts.add(context);
context.init();
contexts.add(context);
}
}
return contexts;
} |
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 ArrayList<T>(values);
if (moveValues.isEmpty()) {
return result;
}
int beforeCount=0;
for (T moveValue : moveValues) {
int ix = result.indexOf(moveValue);
if (ix != -1) {
if (ix < index) {
beforeCount++;
}
@SuppressWarnings("unused")
T removed = result.remove(ix);
System.out.println("R: " + ix + " " + removed + " " + moveValue);
} else if (!allowAdd) {
throw new RuntimeException("Not allowed to add new values: " + moveValue);
}
}
System.out.println("V: " + values + " " + moveValues + " " + result);
System.out.println("IX: " + index + " AA: " + allowAdd);
int moveSize = moveValues.size();
int offset = Math.max(0, index-beforeCount);
System.out.println("MS: " + moveSize + " BC: " + beforeCount + " OF: " + offset);
System.out.println("OF: " + offset + " = " + index + "-" + beforeCount);
for (int i=0; i < moveSize; i++) {
System.out.println("A: " + (offset+1) + " " + moveValues.get(i));
result.add(offset+i, moveValues.get(i));
}
return result;
} |