_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q17400
HtmlTable.byRowColumn
train
protected Locator byRowColumn(int rowIndex, int colIndex) { if (rowIndex < 1) { throw new IllegalArgumentException("Row index must be greater than 0."); } if (colIndex < 1) { throw new IllegalArgumentException("Column index must be greater than 0."); } String xpath = bodyTag.isPresent() ? "./tbody/tr[" + rowIndex + "]/td[" + colIndex + "]" : "./tr[" + rowIndex + "]/td[" + colIndex + "]"; return byInner(By.xpath(xpath)); }
java
{ "resource": "" }
q17401
CircularLossyQueue.push
train
public void push (final T newVal) { final int index = (int) (m_aCurrentIndex.incrementAndGet () % m_nMaxSize); m_aCircularArray[index].set (newVal); }
java
{ "resource": "" }
q17402
CircularLossyQueue.toArray
train
public T [] toArray (@Nonnull final T [] type) { if (type.length > m_nMaxSize) throw new IllegalArgumentException ("Size of array passed in cannot be greater than " + m_nMaxSize); final int curIndex = _getCurrentIndex (); for (int k = 0; k < type.length; k++) { final int index = _getIndex (curIndex - k); type[k] = m_aCircularArray[index].get (); } return type; }
java
{ "resource": "" }
q17403
ConverterHelper.getToConverter
train
public ToConverter getToConverter(Class toClass, Class domainClass) throws JTransfoException { ToConverter converter = withPreConverter(toClass); List<SyntheticField> domainFields = reflectionHelper.getSyntheticFields(domainClass); for (Field field : reflectionHelper.getFields(toClass)) { boolean isTransient = Modifier.isTransient(field.getModifiers()); List<NotMapped> notMapped = reflectionHelper.getAnnotationWithMeta(field, NotMapped.class); if (!isTransient && (0 == notMapped.size())) { List<MappedBy> mappedBies = reflectionHelper.getAnnotationWithMeta(field, MappedBy.class); if (mappedBies.size() > 1) { throw new JTransfoException("Field " + field.getName() + " on type " + field.getDeclaringClass().getName() + " MappedBy is ambiguous, check your meta-annotations."); } MappedBy mappedBy = null; if (1 == mappedBies.size()) { mappedBy = mappedBies.get(0); } boolean isStatic = (0 != (field.getModifiers() & Modifier.STATIC)); if (0 != mappedBies.size() || !isStatic) { buildConverters(field, domainFields, domainClass, converter, mappedBy); } } } addPostConverter(converter, toClass); return converter; }
java
{ "resource": "" }
q17404
ConverterHelper.withPath
train
String withPath(String[] path) { StringBuilder sb = new StringBuilder(); if (path.length > 0) { sb.append(" (with path "); for (int i = 0; i < path.length - 1; i++) { sb.append(path[i]); sb.append("."); } sb.append(path[path.length - 1]); sb.append(") "); } return sb.toString(); }
java
{ "resource": "" }
q17405
ConverterHelper.findField
train
SyntheticField[] findField(List<SyntheticField> domainFields, String fieldName, String[] path, Class<?> type, boolean readOnlyField) throws JTransfoException { List<SyntheticField> fields = domainFields; SyntheticField[] result = new SyntheticField[path.length + 1]; int index = 0; Class<?> currentType = type; for (; index < path.length; index++) { boolean found = false; for (SyntheticField field : fields) { if (field.getName().equals(path[index])) { found = true; result[index] = field; break; } } if (!found) { result[index] = new AccessorSyntheticField(reflectionHelper, currentType, path[index], readOnlyField); } currentType = result[index].getType(); fields = reflectionHelper.getSyntheticFields(currentType); } for (SyntheticField field : fields) { if (field.getName().equals(fieldName)) { result[index] = field; return result; } } result[index] = new AccessorSyntheticField(reflectionHelper, currentType, fieldName, readOnlyField); return result; }
java
{ "resource": "" }
q17406
ConverterHelper.getDefaultTypeConverter
train
TypeConverter getDefaultTypeConverter(Type toField, Type domainField) { for (TypeConverter typeConverter : typeConvertersInOrder) { if (typeConverter.canConvert(toField, domainField)) { return typeConverter; } } return new NoConversionTypeConverter(); // default to no type conversion }
java
{ "resource": "" }
q17407
ChallengeServerClient.sendAction
train
String sendAction(String action) throws ClientErrorException, ServerErrorException, OtherCommunicationException { try { String encodedPath = URLEncoder.encode(this.journeyId, "UTF-8"); String url = String.format("http://%s:%d/action/%s/%s", this.hostname, port, action, encodedPath); HttpResponse<String> response = Unirest.post(url) .header("Accept", this.acceptHeader) .header("Accept-Charset", "UTF-8") .asString(); ensureStatusOk(response); return response.getBody(); } catch (UnirestException | UnsupportedEncodingException e ) { throw new OtherCommunicationException("Could not perform POST request",e); } }
java
{ "resource": "" }
q17408
ChallengeServerClient.ensureStatusOk
train
private static void ensureStatusOk(HttpResponse<String> response) throws ClientErrorException, ServerErrorException, OtherCommunicationException { int responseStatus = response.getStatus(); if (isClientError(responseStatus)) { throw new ClientErrorException(response.getBody()); } else if (isServerError(responseStatus)) { throw new ServerErrorException(); } else if (isOtherErrorResponse(responseStatus)) { throw new OtherCommunicationException(); } }
java
{ "resource": "" }
q17409
Gmap3WicketToDoItems.newToDo
train
@Programmatic // for use by fixtures public Gmap3ToDoItem newToDo( final String description, final String userName) { final Gmap3ToDoItem toDoItem = repositoryService.instantiate(Gmap3ToDoItem.class); toDoItem.setDescription(description); toDoItem.setOwnedBy(userName); toDoItem.setLocation( new Location(51.5172+random(-0.05, +0.05), 0.1182 + random(-0.05, +0.05))); repositoryService.persistAndFlush(toDoItem); return toDoItem; }
java
{ "resource": "" }
q17410
DurationDatatype.computeDays
train
private static BigInteger computeDays(BigInteger months, int refYear, int refMonth) { switch (months.signum()) { case 0: return BigInteger.valueOf(0); case -1: return computeDays(months.negate(), refYear, refMonth).negate(); } // Complete cycle of Gregorian calendar is 400 years BigInteger[] tem = months.divideAndRemainder(BigInteger.valueOf(400*12)); --refMonth; // use 0 base to match Java int total = 0; for (int rem = tem[1].intValue(); rem > 0; rem--) { total += daysInMonth(refYear, refMonth); if (++refMonth == 12) { refMonth = 0; refYear++; } } // In the Gregorian calendar, there are 97 (= 100 + 4 - 1) leap years every 400 years. return tem[0].multiply(BigInteger.valueOf(365*400 + 97)).add(BigInteger.valueOf(total)); }
java
{ "resource": "" }
q17411
DurationDatatype.daysPlusSeconds
train
private static BigDecimal daysPlusSeconds(BigInteger days, BigDecimal seconds) { return seconds.add(new BigDecimal(days.multiply(BigInteger.valueOf(24*60*60)))); }
java
{ "resource": "" }
q17412
DurationDatatype.computeMonths
train
private static BigInteger computeMonths(Duration d) { return d.getYears().multiply(BigInteger.valueOf(12)).add(d.getMonths()); }
java
{ "resource": "" }
q17413
DurationDatatype.computeSeconds
train
private static BigDecimal computeSeconds(Duration d) { return d.getSeconds().add(new BigDecimal(d.getDays().multiply(BigInteger.valueOf(24)) .add(d.getHours()).multiply(BigInteger.valueOf(60)) .add(d.getMinutes()).multiply(BigInteger.valueOf(60)))); }
java
{ "resource": "" }
q17414
CopyResponseProcessor.process
train
@Override public Boolean process(final AciResponseInputStream aciResponse) { try { IOUtils.copy(aciResponse, outputStream); outputStream.flush(); return true; } catch(final IOException e) { throw new ProcessorException(e); } }
java
{ "resource": "" }
q17415
SipStackTool.initializeSipStack
train
public SipStack initializeSipStack(String transport, String myPort, Properties myProperties) throws Exception { /* * http://code.google.com/p/mobicents/issues/detail?id=3121 * Reset sipStack when calling initializeSipStack method */ tearDown(); try { sipStack = new SipStack(transport, Integer.valueOf(myPort), myProperties); logger.info("SipStack - "+sipStackName+" - created!"); } catch (Exception ex) { logger.info("Exception: " + ex.getClass().getName() + ": " + ex.getMessage()); throw ex; } initialized = true; return sipStack; }
java
{ "resource": "" }
q17416
FacadeEndpoint.newProxy
train
public T newProxy() { Object proxy = Proxy.newProxyInstance(classLoader, exportInterfaces, this); return clazz.cast(proxy); }
java
{ "resource": "" }
q17417
SAX.setInput
train
public static void setInput(Input input, InputSource inputSource) { input.setByteStream(inputSource.getByteStream()); input.setCharacterStream(inputSource.getCharacterStream()); input.setUri(inputSource.getSystemId()); input.setEncoding(inputSource.getEncoding()); }
java
{ "resource": "" }
q17418
ValidatingSAXParser.getXMLReader
train
public XMLReader getXMLReader() throws SAXException { XMLFilter filter = _Verifier.getVerifierFilter(); filter.setParent(_WrappedParser.getXMLReader()); return filter; }
java
{ "resource": "" }
q17419
ValidatingSAXParser.parse
train
public void parse(File f, DefaultHandler dh) throws SAXException, IOException { XMLReader reader = getXMLReader(); InputSource source = new InputSource(new FileInputStream(f)); reader.setContentHandler(dh); reader.parse(source); }
java
{ "resource": "" }
q17420
ValidatingSAXParser.parse
train
public void parse(InputSource source, DefaultHandler dh) throws SAXException, IOException { XMLReader reader = getXMLReader(); reader.setContentHandler(dh); reader.parse(source); }
java
{ "resource": "" }
q17421
Request.getAuditText
train
@Override public String getAuditText() { return String.format("id = %s, req = %s(%s)", getId(), getMethodName(), PresentationUtils.toDisplayableString(getParams())); }
java
{ "resource": "" }
q17422
XmlRpcHandler.newXMLReader
train
XMLReader newXMLReader() throws ParserConfigurationException, SAXException, FactoryConfigurationError { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = parserFactory.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); reader.setContentHandler(this); return reader; }
java
{ "resource": "" }
q17423
Uri.isValid
train
public static boolean isValid(String s) { try { new URI(UriEncoder.encode(s)); } catch (URISyntaxException e) { return false; } return true; }
java
{ "resource": "" }
q17424
Uri.isAbsolute
train
public static boolean isAbsolute(String uri) { int i = uri.indexOf(':'); if (i < 0) return false; while (--i >= 0) { switch (uri.charAt(i)) { case '#': case '/': case '?': return false; } } return true; }
java
{ "resource": "" }
q17425
HtmlValidationConfiguration.mustShowWindowForError
train
public boolean mustShowWindowForError(SAXParseException error) { for (Pattern curIgnorePattern : ignoreErrorsForWindow) { if (curIgnorePattern.matcher(error.getMessage()).find()) return false; } return true; }
java
{ "resource": "" }
q17426
Mode.getElementActionsExplicit
train
private ActionSet getElementActionsExplicit(String ns) { ActionSet actions = (ActionSet)elementMap.get(ns); if (actions==null) { // iterate namespace specifications. for (Enumeration e = nssElementMap.keys(); e.hasMoreElements() && actions==null;) { NamespaceSpecification nssI = (NamespaceSpecification)e.nextElement(); // If a namespace specification convers the current namespace URI then we get those actions. if (nssI.covers(ns)) { actions = (ActionSet)nssElementMap.get(nssI); } } // Store them in the element Map for faster access next time. if (actions!=null) { elementMap.put(ns, actions); } } // Look into the included modes if (actions == null && includedModes != null) { Iterator i = includedModes.iterator(); while (actions == null && i.hasNext()) { Mode includedMode = (Mode)i.next(); actions = includedMode.getElementActionsExplicit(ns); } if (actions != null) { actions = actions.changeCurrentMode(this); elementMap.put(ns, actions); } } // No actions specified, look into the base mode. if (actions == null && baseMode != null) { actions = baseMode.getElementActionsExplicit(ns); if (actions != null) { actions = actions.changeCurrentMode(this); elementMap.put(ns, actions); } } if (actions!=null && actions.getCancelNestedActions()) { actions = null; } return actions; }
java
{ "resource": "" }
q17427
Mode.getAttributeActionsExplicit
train
private AttributeActionSet getAttributeActionsExplicit(String ns) { AttributeActionSet actions = (AttributeActionSet)attributeMap.get(ns); if (actions==null) { // iterate namespace specifications. for (Enumeration e = nssAttributeMap.keys(); e.hasMoreElements() && actions==null;) { NamespaceSpecification nssI = (NamespaceSpecification)e.nextElement(); // If a namespace specification convers the current namespace URI then we get those actions. if (nssI.covers(ns)) { actions = (AttributeActionSet)nssAttributeMap.get(nssI); } } // Store them in the element Map for faster access next time. if (actions!=null) { attributeMap.put(ns, actions); } } // Look into the included modes if (actions == null && includedModes != null) { Iterator i = includedModes.iterator(); while (actions == null && i.hasNext()) { Mode includedMode = (Mode)i.next(); actions = includedMode.getAttributeActionsExplicit(ns); } if (actions != null) { attributeMap.put(ns, actions); } } if (actions == null && baseMode != null) { actions = baseMode.getAttributeActionsExplicit(ns); if (actions != null) attributeMap.put(ns, actions); } if (actions!=null && actions.getCancelNestedActions()) { actions = null; } return actions; }
java
{ "resource": "" }
q17428
Mode.bindElement
train
boolean bindElement(String ns, String wildcard, ActionSet actions) { NamespaceSpecification nss = new NamespaceSpecification(ns, wildcard); if (nssElementMap.get(nss) != null) return false; for (Enumeration e = nssElementMap.keys(); e.hasMoreElements();) { NamespaceSpecification nssI = (NamespaceSpecification)e.nextElement(); if (nss.compete(nssI)) { return false; } } nssElementMap.put(nss, actions); return true; }
java
{ "resource": "" }
q17429
Mode.bindAttribute
train
boolean bindAttribute(String ns, String wildcard, AttributeActionSet actions) { NamespaceSpecification nss = new NamespaceSpecification(ns, wildcard); if (nssAttributeMap.get(nss) != null) return false; for (Enumeration e = nssAttributeMap.keys(); e.hasMoreElements();) { NamespaceSpecification nssI = (NamespaceSpecification)e.nextElement(); if (nss.compete(nssI)) { return false; } } nssAttributeMap.put(nss, actions); return true; }
java
{ "resource": "" }
q17430
CollectionOfEntitiesAsLocatablesFactory.isInternetReachable
train
private static boolean isInternetReachable() { try { final URL url = new URL("http://www.google.com"); final HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection(); urlConnect.setConnectTimeout(1000); urlConnect.getContent(); urlConnect.disconnect(); } catch (UnknownHostException e) { return false; } catch (IOException e) { return false; } return true; }
java
{ "resource": "" }
q17431
DateBuilder.build
train
@Nonnull public Date build () { Calendar cal; if (m_aTZ != null && m_aLocale != null) cal = Calendar.getInstance (m_aTZ, m_aLocale); else if (m_aTZ != null) cal = Calendar.getInstance (m_aTZ, Locale.getDefault (Locale.Category.FORMAT)); else if (m_aLocale != null) cal = Calendar.getInstance (TimeZone.getDefault (), m_aLocale); else cal = PDTFactory.createCalendar (); cal.set (Calendar.YEAR, m_nYear); cal.set (Calendar.MONTH, m_nMonth - 1); cal.set (Calendar.DAY_OF_MONTH, m_nDay); cal.set (Calendar.HOUR_OF_DAY, m_nHour); cal.set (Calendar.MINUTE, m_nMinute); cal.set (Calendar.SECOND, m_nSecond); cal.set (Calendar.MILLISECOND, 0); return cal.getTime (); }
java
{ "resource": "" }
q17432
StringBasedAnnotationHandler.ph
train
protected String[] ph(String... strs) { String[] res = new String[strs.length]; for(int i = 0; i < res.length; i++){ res[i] = ph(strs[i]); } return res; }
java
{ "resource": "" }
q17433
AbstractRequestInterceptor.newParamConfig
train
public ParamConfigBuilder newParamConfig(Class<?> type, Type genericType){ return paramConfigBuilderFactory.newInstance(type, genericType); }
java
{ "resource": "" }
q17434
XmlUtils.getXmlScopes
train
public Map<Layout, Collection<XmlScope>> getXmlScopes() { List<File> layoutDirs = layoutsFinder.findLayoutDirs(); Collection<File> layoutFiles = collectionUtils.flatMap(layoutDirs, new CollectionUtils.Function<File, Collection<File>>() { @Override public Collection<File> apply(File file) { return collectionUtils.filter(Arrays.asList(file.listFiles()), new CollectionUtils.Function<File, Boolean>() { @Override public Boolean apply(File file) { return file.getName().endsWith(".xml"); } }); } }); Collection<Document> docs = collectionUtils.flatMapOpt(layoutFiles, new CollectionUtils.Function<File, Option<Document>>() { @Override public Option<Document> apply(File file) { return getDocumentFromFile(file); } }); return collectionUtils.toMap(collectionUtils.flatMapOpt(docs, new CollectionUtils.Function<Document, Option<Tuple<Layout, Collection<XmlScope>>>>() { @Override public Option<Tuple<Layout, Collection<XmlScope>>> apply(Document doc) { Option<String> optNameSpace = namespaceFinder.getNameSpace(doc); if (optNameSpace.isPresent()) { attrPattern = Pattern.compile(String.format(NAMESPACE_ATTRIBUTE_REG, optNameSpace.get())); Collection<XmlScope> scopes = getScopes(doc); return Option.of(Tuple.of(new Layout(doc.getDocumentURI()), scopes)); } else { return Option.absent(); } } })); }
java
{ "resource": "" }
q17435
GlobalQuartzScheduler.setGroupName
train
public void setGroupName (@Nonnull @Nonempty final String sGroupName) { ValueEnforcer.notEmpty (sGroupName, "GroupName"); m_sGroupName = sGroupName; }
java
{ "resource": "" }
q17436
GlobalQuartzScheduler.addJobListener
train
public void addJobListener (@Nonnull final IJobListener aJobListener) { ValueEnforcer.notNull (aJobListener, "JobListener"); try { m_aScheduler.getListenerManager ().addJobListener (aJobListener, EverythingMatcher.allJobs ()); } catch (final SchedulerException ex) { throw new IllegalStateException ("Failed to add job listener " + aJobListener.toString (), ex); } }
java
{ "resource": "" }
q17437
GlobalQuartzScheduler.scheduleJob
train
@Nonnull public TriggerKey scheduleJob (@Nonnull final String sJobName, @Nonnull final JDK8TriggerBuilder <? extends ITrigger> aTriggerBuilder, @Nonnull final Class <? extends IJob> aJobClass, @Nullable final Map <String, ? extends Object> aJobData) { ValueEnforcer.notNull (sJobName, "JobName"); ValueEnforcer.notNull (aTriggerBuilder, "TriggerBuilder"); ValueEnforcer.notNull (aJobClass, "JobClass"); // what to do final IJobDetail aJobDetail = JobBuilder.newJob (aJobClass).withIdentity (sJobName, m_sGroupName).build (); // add custom parameters aJobDetail.getJobDataMap ().putAllIn (aJobData); try { // Schedule now final ITrigger aTrigger = aTriggerBuilder.build (); m_aScheduler.scheduleJob (aJobDetail, aTrigger); final TriggerKey ret = aTrigger.getKey (); LOGGER.info ("Succesfully scheduled job '" + sJobName + "' with TriggerKey " + ret.toString () + " - starting at " + PDTFactory.createLocalDateTime (aTrigger.getStartTime ())); return ret; } catch (final SchedulerException ex) { throw new RuntimeException (ex); } }
java
{ "resource": "" }
q17438
GlobalQuartzScheduler.scheduleJobNowOnce
train
@Nonnull public TriggerKey scheduleJobNowOnce (@Nonnull final String sJobName, @Nonnull final Class <? extends IJob> aJobClass, @Nullable final Map <String, ? extends Object> aJobData) { return scheduleJob (sJobName, JDK8TriggerBuilder.newTrigger () .startNow () .withSchedule (SimpleScheduleBuilder.simpleSchedule () .withIntervalInMinutes (1) .withRepeatCount (0)), aJobClass, aJobData); }
java
{ "resource": "" }
q17439
GlobalQuartzScheduler.shutdown
train
public void shutdown () throws SchedulerException { try { // Shutdown but wait for jobs to complete m_aScheduler.shutdown (true); LOGGER.info ("Successfully shutdown GlobalQuartzScheduler"); } catch (final SchedulerException ex) { LOGGER.error ("Failed to shutdown GlobalQuartzScheduler", ex); throw ex; } }
java
{ "resource": "" }
q17440
DefaultContentResolver.setHttpClient
train
public void setHttpClient(HttpClient httpClient) { if (httpClient != defaultHttpClient && this.httpClient == defaultHttpClient) { defaultHttpClient.getConnectionManager().shutdown(); } this.httpClient = httpClient; }
java
{ "resource": "" }
q17441
XMLUtil.closeQuietly
train
public static void closeQuietly(XMLStreamWriter writer) { if (writer != null) { try { writer.close(); } catch (XMLStreamException e) { logger.warn("Error while closing", e); } } }
java
{ "resource": "" }
q17442
XMLUtil.closeQuietly
train
public static void closeQuietly(XMLStreamReader reader) { if (reader != null) { try { reader.close(); } catch (XMLStreamException e) { logger.warn("Error while closing", e); } } }
java
{ "resource": "" }
q17443
HttpUtil.get
train
public static InputStream get(HttpClient httpClient, URI requestURI) throws IOException { HttpEntity entity = doGet(httpClient, requestURI); if (entity == null) { return new ByteArrayInputStream(new byte[0]); } return entity.getContent(); }
java
{ "resource": "" }
q17444
DefaultContentHandler.baseDir
train
private File baseDir() throws IOException { if (baseDir == null) { baseDir = File.createTempFile("fcrepo-dto", null); if (!baseDir.delete()) { throw new IOException("Can't delete temp file " + baseDir); } if (!baseDir.mkdir()) { throw new IOException("Can't create temp dir " + baseDir); } } return baseDir; }
java
{ "resource": "" }
q17445
DefaultContentHandler.rmDir
train
private static void rmDir(File dir) { for (File file: dir.listFiles()) { if (file.isDirectory()) { rmDir(file); } else { if (!file.delete()) { logger.warn("Can't delete file " + file); } } } if (!dir.delete()) { logger.warn("Can't delete dir " + dir); } }
java
{ "resource": "" }
q17446
ContentHandlingDTOReader.setContentHandler
train
public void setContentHandler(ContentHandler contentHandler) { if (contentHandler == null) throw new NullPointerException(); if (contentHandler != defaultContentHandler && this.contentHandler == defaultContentHandler) { defaultContentHandler.close(); } }
java
{ "resource": "" }
q17447
ValidationMappingDescriptorImpl.getNamespaces
train
public List<String> getNamespaces() { List<String> namespaceList = new ArrayList<String>(); java.util.Map<String, String> attributes = model.getAttributes(); for (Entry<String, String> e : attributes.entrySet()) { final String name = e.getKey(); final String value = e.getValue(); if (value != null && value.startsWith("http://")) { namespaceList.add(name + "=" + value); } } return namespaceList; }
java
{ "resource": "" }
q17448
SingleSwapNeighbourhood.getRandomMove
train
@Override public SingleSwapMove getRandomMove(PermutationSolution solution, Random rnd) { int n = solution.size(); // check: move possible if(n < 2){ return null; } // pick two random, distinct positions to swap int i = rnd.nextInt(n); int j = rnd.nextInt(n-1); if(j >= i){ j++; } // generate swap move return new SingleSwapMove(i, j); }
java
{ "resource": "" }
q17449
PerformanceKoPeMeStatement.evaluate
train
public final void evaluate() throws IllegalAccessException, InvocationTargetException { if (simple) tr.startCollection(); fTestMethod.invoke(fTarget, params); if (simple) tr.stopCollection(); }
java
{ "resource": "" }
q17450
Telefonnummer.getInlandsnummer
train
public Telefonnummer getInlandsnummer() { if (getLaenderkennzahl().isPresent()) { String nummer = this.getCode().substring(3).trim(); if (StringUtils.startsWithAny(nummer, "1", "2", "3", "4", "5", "6", "7", "8", "9")) { nummer = "0" + nummer; } return new Telefonnummer(nummer); } else { return this; } }
java
{ "resource": "" }
q17451
Telefonnummer.getRufnummer
train
public Telefonnummer getRufnummer() { String inlandsnummer = RegExUtils.replaceAll(this.getInlandsnummer().toString(), "[ /]+", " "); return new Telefonnummer(StringUtils.substringAfter(inlandsnummer, " ").replaceAll(" ", "")); }
java
{ "resource": "" }
q17452
Telefonnummer.toDinString
train
public String toDinString() { Optional<String> laenderkennzahl = getLaenderkennzahl(); return laenderkennzahl.map(s -> s + " " + getVorwahl().substring(1) + " " + getRufnummer()).orElseGet( () -> getVorwahl() + " " + getRufnummer()); }
java
{ "resource": "" }
q17453
QueryString.toQueryString
train
public String toQueryString() { String result = null; List<String> parameters = new ArrayList<>(); for (Map.Entry<String, String> entry : entrySet()) { // We don't encode the key because it could legitimately contain // things like underscores, e.g. "_escaped_fragment_" would become: // "%5Fescaped%5Ffragment%5F" String key = entry.getKey(); String value; try { value = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Error encoding URL", e); } // Jetty class *appears* to need Java 8 //String value = UrlEncoded.encodeString(entry.getValue()); parameters.add(key + "=" + value); } if (parameters.size() > 0) { result = StringUtils.join(parameters, '&'); } return result; }
java
{ "resource": "" }
q17454
Prettyprint.compile
train
@Override public void compile(JQElement element, JSON attrs) { String text = SafeHtmlUtils.htmlEscape(element.text()); element.empty().append(prettifier.prettify(text)); }
java
{ "resource": "" }
q17455
OneElement.apply
train
@Override public E apply(Iterator<E> consumable) { dbc.precondition(consumable != null, "consuming a null iterator"); dbc.precondition(consumable.hasNext(), "no element to consume"); final E found = consumable.next(); dbc.state(!consumable.hasNext(), "found more than one element consuming the iterator"); return found; }
java
{ "resource": "" }
q17456
Pagination.page
train
public static <T> Pair<Integer, List<T>> page(long start, long howMany, Iterator<T> iterator) { final Pair<Long, List<T>> page = Pagination.LongPages.page(start, howMany, iterator); dbc.state(page.first() <= Integer.MAX_VALUE, "iterator size overflows an integer"); return Pair.of(page.first().intValue(), page.second()); }
java
{ "resource": "" }
q17457
Pagination.page
train
public static <T> Pair<Integer, List<T>> page(long start, long howMany, Iterable<T> iterable) { dbc.precondition(iterable != null, "cannot call page with a null iterable"); return Pagination.page(start, howMany, iterable.iterator()); }
java
{ "resource": "" }
q17458
Pagination.page
train
public static <T, C extends Collection<T>> Pair<Integer, C> page(long start, long howMany, Iterable<T> iterable, C collection) { dbc.precondition(iterable != null, "cannot call page with a null iterable"); return Pagination.page(start, howMany, iterable.iterator(), collection); }
java
{ "resource": "" }
q17459
Pagination.page
train
public static <T> Pair<Integer, List<T>> page(long start, long howMany, T[] array) { return Pagination.page(start, howMany, new ArrayIterator<T>(array)); }
java
{ "resource": "" }
q17460
Pagination.page
train
public static <T, C extends Collection<T>> Pair<Integer, C> page(long start, long howMany, T[] array, C collection) { return Pagination.page(start, howMany, new ArrayIterator<T>(array), collection); }
java
{ "resource": "" }
q17461
Pagination.page
train
public static <T> Pair<Integer, List<T>> page(long start, long howMany, Collection<T> collection) { return Pair.of(collection.size(), Consumers.all(Filtering.slice(start, howMany, collection))); }
java
{ "resource": "" }
q17462
Pagination.page
train
public static <T, C extends Collection<T>> Pair<Integer, C> page(long start, long howMany, Collection<T> in, C out) { return Pair.of(in.size(), Consumers.all(Filtering.slice(start, howMany, in), out)); }
java
{ "resource": "" }
q17463
Primzahl.after
train
public static Primzahl after(int zahl) { List<Primzahl> primzahlen = getPrimzahlen(); for (Primzahl p : primzahlen) { if (zahl < p.intValue()) { return p; } } for (int n = primzahlen.get(primzahlen.size() - 1).intValue() + 2; n <= zahl; n += 2) { if (!hasTeiler(n)) { primzahlen.add(new Primzahl(n)); } } int n = primzahlen.get(primzahlen.size() - 1).intValue() + 2; while (hasTeiler(n)) { n += 2; } Primzahl nextPrimzahl = new Primzahl(n); primzahlen.add(nextPrimzahl); return nextPrimzahl; }
java
{ "resource": "" }
q17464
Tracy.annotate
train
public static void annotate(String floatName, float floatValue) { TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { ctx.annotate(floatName, floatValue); } }
java
{ "resource": "" }
q17465
Tracy.annotate
train
public static void annotate(String doubleName, double doubleValue) { TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { ctx.annotate(doubleName, doubleValue); } }
java
{ "resource": "" }
q17466
Tracy.annotateRoot
train
public static void annotateRoot(String... keyValueSequence) { TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { ctx.annotateRoot(keyValueSequence); } }
java
{ "resource": "" }
q17467
Tracy.annotateRoot
train
public static void annotateRoot(String intName, int intValue) { TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { ctx.annotateRoot(intName, intValue); } }
java
{ "resource": "" }
q17468
Tracy.annotateRoot
train
public static void annotateRoot(String longName, long longValue) { TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { ctx.annotateRoot(longName, longValue); } }
java
{ "resource": "" }
q17469
Tracy.annotateRoot
train
public static void annotateRoot(String booleanName, boolean booleanValue) { TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { ctx.annotateRoot(booleanName, booleanValue); } }
java
{ "resource": "" }
q17470
Tracy.getEvents
train
public static List<TracyEvent> getEvents() { TracyThreadContext ctx = threadContext.get(); List<TracyEvent> events = EMPTY_TRACY_EVENT_LIST; if (isValidContext(ctx)) { events = ctx.getPoppedList(); } return events; }
java
{ "resource": "" }
q17471
Tracy.getEventsAsJson
train
public static List<String> getEventsAsJson() { List<String> list = Tracy.EMPTY_STRING_LIST; TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { list = new ArrayList<String>(20); for (TracyEvent event : ctx.getPoppedList()) { list.add(event.toJsonString()); } } return list; }
java
{ "resource": "" }
q17472
Tracy.getEventsAsJsonTracySegment
train
public static String getEventsAsJsonTracySegment() { // Assuming max 8 frames per segment. Typical Tracy JSON frame is ~250 // ( 250 * 8 = 2000). Rounding up to 2048 final int TRACY_SEGMENT_CHAR_SIZE = 2048; String jsonArrayString = null; int frameCounter = 0; TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx) && ctx.getPoppedList().size()>0) { StringBuilder sb = new StringBuilder(TRACY_SEGMENT_CHAR_SIZE); sb.append("{\"tracySegment\":["); for (TracyEvent event : ctx.getPoppedList()) { if (frameCounter > 0) { sb.append(","); } sb.append(event.toJsonString()); frameCounter++; } sb.append("]}"); jsonArrayString = sb.toString(); } return jsonArrayString; }
java
{ "resource": "" }
q17473
Tracy.mergeWorkerContext
train
public static void mergeWorkerContext(TracyThreadContext workerTracyThreadContext) { TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { ctx.mergeChildContext(workerTracyThreadContext); } }
java
{ "resource": "" }
q17474
Tracy.frameErrorWithoutPopping
train
public static void frameErrorWithoutPopping(String error) { TracyThreadContext ctx = threadContext.get(); if (isValidContext(ctx)) { ctx.annotateFrameError(error); } }
java
{ "resource": "" }
q17475
Searches.search
train
public static <E> List<E> search(Iterator<E> iterator, Predicate<E> predicate) { final Function<Iterator<E>, ArrayList<E>> consumer = new ConsumeIntoCollection<>(new ArrayListFactory<E>()); final FilteringIterator<E> filtered = new FilteringIterator<E>(iterator, predicate); return consumer.apply(filtered); }
java
{ "resource": "" }
q17476
Searches.search
train
public static <C extends Collection<E>, E> C search(Iterator<E> iterator, C collection, Predicate<E> predicate) { final Function<Iterator<E>, C> consumer = new ConsumeIntoCollection<>(new ConstantSupplier<C>(collection)); final FilteringIterator<E> filtered = new FilteringIterator<E>(iterator, predicate); return consumer.apply(filtered); }
java
{ "resource": "" }
q17477
Searches.search
train
public static <C extends Collection<E>, E> C search(Iterable<E> iterable, C collection, Predicate<E> predicate) { dbc.precondition(iterable != null, "cannot search a null iterable"); final Function<Iterator<E>, C> consumer = new ConsumeIntoCollection<>(new ConstantSupplier<C>(collection)); final FilteringIterator<E> filtered = new FilteringIterator<E>(iterable.iterator(), predicate); return consumer.apply(filtered); }
java
{ "resource": "" }
q17478
Searches.search
train
public static <C extends Collection<E>, E> C search(E[] array, Supplier<C> supplier, Predicate<E> predicate) { final Function<Iterator<E>, C> consumer = new ConsumeIntoCollection<>(supplier); final FilteringIterator<E> filtered = new FilteringIterator<E>(new ArrayIterator<E>(array), predicate); return consumer.apply(filtered); }
java
{ "resource": "" }
q17479
Searches.find
train
public static <E> List<E> find(Iterator<E> iterator, Predicate<E> predicate) { final Function<Iterator<E>, ArrayList<E>> consumer = new ConsumeIntoCollection<>(new ArrayListFactory<E>()); final FilteringIterator<E> filtered = new FilteringIterator<E>(iterator, predicate); final ArrayList<E> found = consumer.apply(filtered); dbc.precondition(!found.isEmpty(), "no element matched"); return found; }
java
{ "resource": "" }
q17480
KiekerMeasureUtil.measureBefore
train
public void measureBefore() { if (!CTRLINST.isMonitoringEnabled()) { return; } hostname = VMNAME; sessionId = SESSIONREGISTRY.recallThreadLocalSessionId(); traceId = CFREGISTRY.recallThreadLocalTraceId(); // entry point if (traceId == -1) { entrypoint = true; traceId = CFREGISTRY.getAndStoreUniqueThreadLocalTraceId(); CFREGISTRY.storeThreadLocalEOI(0); CFREGISTRY.storeThreadLocalESS(1); // next operation is ess + 1 eoi = 0; ess = 0; } else { entrypoint = false; eoi = CFREGISTRY.incrementAndRecallThreadLocalEOI(); // ess > 1 ess = CFREGISTRY.recallAndIncrementThreadLocalESS(); // ess >= 0 if ((eoi == -1) || (ess == -1)) { LOG.error("eoi and/or ess have invalid values:" + " eoi == " + eoi + " ess == " + ess); CTRLINST.terminateMonitoring(); } } tin = TIME.getTime(); }
java
{ "resource": "" }
q17481
ReverseSubsequenceMove.apply
train
@Override public void apply(PermutationSolution solution) { int start = from; int stop = to; int n = solution.size(); // reverse subsequence by performing a series of swaps // (works cyclically when start > stop) int reversedLength; if(start < stop){ reversedLength = stop-start+1; } else { reversedLength = n - (start-stop-1); } int numSwaps = reversedLength/2; for(int k=0; k<numSwaps; k++){ solution.swap(start, stop); start = (start+1) % n; stop = (stop-1+n) % n; } }
java
{ "resource": "" }
q17482
AccessValidator.access
train
public static <T> T access(T[] array, int n) { int max = array.length - 1; if ((n < 0) || (n > max)) { throw new InvalidValueException(n, "n", Range.between(0, max)); } return array[n]; }
java
{ "resource": "" }
q17483
dbc.precondition
train
public static void precondition(boolean assertion, String format, Object... params) { if (!assertion) { throw new IllegalArgumentException(String.format(format, params)); } }
java
{ "resource": "" }
q17484
dbc.state
train
public static void state(boolean assertion, String format, Object... params) { if (!assertion) { throw new IllegalStateException(String.format(format, params)); } }
java
{ "resource": "" }
q17485
GeldbetragSingletonSpi.getAmountFactory
train
@SuppressWarnings("unchecked") @Override public <T extends MonetaryAmount> MonetaryAmountFactory<T> getAmountFactory(Class<T> amountType) { if (Geldbetrag.class.equals(amountType)) { return (MonetaryAmountFactory<T>) new GeldbetragFactory(); } MonetaryAmountFactoryProviderSpi<T> f = MonetaryAmountFactoryProviderSpi.class.cast(factories.get(amountType)); if (Objects.nonNull(f)) { return f.createMonetaryAmountFactory(); } throw new MonetaryException("no MonetaryAmountFactory found for " + amountType); }
java
{ "resource": "" }
q17486
DefaultStylerFactory.debugStylers
train
private DebugStyler debugStylers(String... names) throws VectorPrintException { if (settings.getBooleanProperty(false, DEBUG)) { DebugStyler dst = new DebugStyler(); StylerFactoryHelper.initStylingObject(dst, writer, document, null, layerManager, settings); try { ParamAnnotationProcessorImpl.PAP.initParameters(dst); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) { throw new VectorPrintException(ex); } for (String n : names) { dst.getStyleSetup().add(n); styleSetup.put(n, SettingsBindingService.getInstance().getFactory().getBindingHelper().serializeValue(settings.getStringProperties(null, n))); } return dst; } return null; }
java
{ "resource": "" }
q17487
Optionals.mapAdapter
train
public static <K,V> MapAdapter<K,V> mapAdapter(final Map<K,V> map) { return key -> Optional.ofNullable(map.get(key)); }
java
{ "resource": "" }
q17488
Optionals.firstInList
train
public static <T> Optional<T> firstInList(List<T> list) { return list.isEmpty() ? Optional.empty() : Optional.ofNullable(list.get(0)); }
java
{ "resource": "" }
q17489
Optionals.getOpt
train
public static <K,V> Optional<V> getOpt(Map<K,V> map, K key) { return Optional.ofNullable(map.get(key)); }
java
{ "resource": "" }
q17490
GeldbetragFactory.setNumber
train
@Override public GeldbetragFactory setNumber(Number number) { this.number = number; this.context = getMonetaryContextOf(number); return this; }
java
{ "resource": "" }
q17491
EventHelper.onOpenDocument
train
@Override public final void onOpenDocument(PdfWriter writer, Document document) { super.onOpenDocument(writer, document); template = writer.getDirectContent().createTemplate(document.getPageSize().getWidth(), document.getPageSize().getHeight()); if (!getSettings().containsKey(PAGEFOOTERSTYLEKEY)) { getSettings().put(PAGEFOOTERSTYLEKEY, PAGEFOOTERSTYLE); } if (!getSettings().containsKey(PAGEFOOTERTABLEKEY)) { float tot = ItextHelper.ptsToMm(document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()); getSettings().put(PAGEFOOTERTABLEKEY, new StringBuilder("Table(columns=3,widths=") .append(Math.round(tot * getSettings().getFloatProperty(0.85f, "footerleftwidthpercentage"))).append('|') .append(Math.round(tot * getSettings().getFloatProperty(0.14f, "footermiddlewidthpercentage"))).append('|') .append(Math.round(tot * getSettings().getFloatProperty(0.01f, "footerrightwidthpercentage"))).append(')').toString() ); } }
java
{ "resource": "" }
q17492
EventHelper.printFailureHeader
train
protected void printFailureHeader(PdfTemplate template, float x, float y) { Font f = DebugHelper.debugFontLink(template, getSettings()); Chunk c = new Chunk(getSettings().getProperty("failures in report, see end of report", "failureheader"), f); ColumnText.showTextAligned(template, Element.ALIGN_LEFT, new Phrase(c), x, y, 0); }
java
{ "resource": "" }
q17493
EventHelper.renderFooter
train
protected void renderFooter(PdfWriter writer, Document document) throws DocumentException, VectorPrintException, InstantiationException, IllegalAccessException { if (!debugHereAfter && !failuresHereAfter) { PdfPTable footerTable = elementProducer.createElement(null, PdfPTable.class, getStylers(PAGEFOOTERTABLEKEY)); footerTable.addCell(createFooterCell(ValueHelper.createDate(new Date()))); String pageText = writer.getPageNumber() + getSettings().getProperty(" of ", UPTO); PdfPCell c = createFooterCell(pageText); c.setHorizontalAlignment(Element.ALIGN_RIGHT); footerTable.addCell(c); footerTable.addCell(createFooterCell(new Chunk())); footerTable.writeSelectedRows(0, -1, document.getPageSize().getLeft() + document.leftMargin(), document.getPageSize().getBottom(document.bottomMargin()), writer.getDirectContentUnder()); footerBottom = document.bottom() - footerTable.getTotalHeight(); } }
java
{ "resource": "" }
q17494
EventHelper.getTemplateImage
train
protected Image getTemplateImage(PdfTemplate template) throws BadElementException { if (templateImage == null) { templateImage = Image.getInstance(template); templateImage.setAbsolutePosition(0, 0); } return templateImage; }
java
{ "resource": "" }
q17495
StylerFactoryHelper.findForCssName
train
public static Collection<BaseStyler> findForCssName(String cssName, boolean required) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Collection<BaseStyler> stylers = new ArrayList<>(1); for (Class<?> c : ClassHelper.fromPackage(Font.class.getPackage())) { if (!Modifier.isAbstract(c.getModifiers())&&BaseStyler.class.isAssignableFrom(c)) { BaseStyler bs = (BaseStyler) c.newInstance(); if (bs.findForCssProperty(cssName) != null && !bs.findForCssProperty(cssName).isEmpty()) { stylers.add(bs); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(String.format("found %s supporting css property %s", cssName, bs.getClass().getName())); } } } } if (stylers.isEmpty()) { if (required) { throw new IllegalArgumentException(String.format("no styler supports css property %s", cssName)); } else { LOGGER.warning(String.format("no styler supports css property %s", cssName)); } } return stylers; }
java
{ "resource": "" }
q17496
Waehrung.of
train
public static Waehrung of(Currency currency) { String key = currency.getCurrencyCode(); return CACHE.computeIfAbsent(key, t -> new Waehrung(currency)); }
java
{ "resource": "" }
q17497
Waehrung.of
train
public static Waehrung of(CurrencyUnit currencyUnit) { if (currencyUnit instanceof Waehrung) { return (Waehrung) currencyUnit; } else { return of(currencyUnit.getCurrencyCode()); } }
java
{ "resource": "" }
q17498
Waehrung.validate
train
public static String validate(String code) { try { toCurrency(code); } catch (IllegalArgumentException ex) { throw new InvalidValueException(code, "currency"); } return code; }
java
{ "resource": "" }
q17499
Waehrung.getSymbol
train
public static String getSymbol(CurrencyUnit cu) { try { return Waehrung.of(cu).getSymbol(); } catch (IllegalArgumentException ex) { LOG.log(Level.WARNING, "Cannot get symbol for '" + cu + "':", ex); return cu.getCurrencyCode(); } }
java
{ "resource": "" }