_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q177800
AbstractAuthResource.verifyAccountNameStrength
test
public void verifyAccountNameStrength(String accountName) throws AuthenticationException { Matcher matcher = PATTERN.matcher(accountName); if (!matcher.matches()) { throw new AuthenticationException(accountName + " is not a valid email"); } }
java
{ "resource": "" }
q177801
AbstractAuthResource.verifyPasswordStrength
test
public void verifyPasswordStrength(String oldPassword, String newPassword, T user) throws AuthenticationException { List<Rule> rules = getPasswordRules(); PasswordValidator validator = new PasswordValidator(rules); PasswordData passwordData = new PasswordData(new Password(newPassword)); RuleResult result = validator.validate(passwordData); if (!result.isValid()) { StringBuilder messages = new StringBuilder(); for (String msg : validator.getMessages(result)) { messages.append(msg).append("\n"); } throw new AuthenticationException(messages.toString()); } }
java
{ "resource": "" }
q177802
SearchFactory.provide
test
@Override public SearchModel provide() { SearchModel searchModel = new SearchModel(); searchModel.setResponse(response); String method = getMethod(); if ("GET".equals(method)) { MultivaluedMap<String, String> queryParameters = getUriInfo().getQueryParameters(); for (Map.Entry<String, List<String>> param : queryParameters.entrySet()) { if (param.getValue().get(0) == null) continue; if ("_q".equalsIgnoreCase(param.getKey())) { searchModel.setQ(param.getValue().get(0)); } else if ("_limit".equalsIgnoreCase(param.getKey())) { searchModel.setLimit(Integer.parseInt(param.getValue().get(0))); } else if ("_offset".equalsIgnoreCase(param.getKey())) { searchModel.setOffset(Integer.parseInt(param.getValue().get(0))); } else if ("_fields".equalsIgnoreCase(param.getKey())) { searchModel.setFields(param.getValue().get(0).split(",")); } else if ("_sort".equalsIgnoreCase(param.getKey())) { searchModel.setSort(param.getValue().get(0).split(",")); } else if ("_filter".equalsIgnoreCase(param.getKey())) { searchModel.setFilterExpression(param.getValue().get(0)); } } } return searchModel; }
java
{ "resource": "" }
q177803
Transaction.success
test
private void success() { org.hibernate.Transaction txn = session.getTransaction(); if (txn != null && txn.getStatus().equals(TransactionStatus.ACTIVE)) { txn.commit(); } }
java
{ "resource": "" }
q177804
Transaction.error
test
private void error() { org.hibernate.Transaction txn = session.getTransaction(); if (txn != null && txn.getStatus().equals(TransactionStatus.ACTIVE)) { txn.rollback(); } }
java
{ "resource": "" }
q177805
Transaction.start
test
private void start() { try { before(); transactionWrapper.wrap(); success(); } catch (Exception e) { error(); if (exceptionHandler != null) { exceptionHandler.onException(e); } else { throw e; } } finally { finish(); } }
java
{ "resource": "" }
q177806
Query.configureFieldByName
test
public static <E> Holder<E> configureFieldByName(Criteria<E> criteria, String name){ if(Validations.isEmptyOrNull(name)) return null; // parse x.y name as [x, y] String[] names = name.split("\\."); // uses to keep current name by names index. String currentName; // init start index of names. int step = 0; // always will be current criteria CriteriaParent<E> currentCriteria = criteria; FieldMeta currentFieldMeta; // use aliasJoiner to use as alias. StringJoiner aliasJoiner = new StringJoiner("$"); do { // get current name of field by index. like x.y.z => if step = 1 then currentName = y currentName = names[step]; if(Validations.isEmptyOrNull(currentName)) { throw new RuntimeException(currentName + " defined name is wrong ! "); } currentFieldMeta = criteria.getMeta().getFieldMap().get(currentName); step++; aliasJoiner.add(currentCriteria.getAlias()); if(step >= names.length) { break; } if(currentFieldMeta.getReference() == null) { throw new RuntimeException("" + currentName + " join field of " + name + "'s reference target information must defined ! "); } CriteriaJoin<E> criteriaJoin = currentCriteria.getJoin(currentName); if(criteriaJoin == null) { currentCriteria.createJoin(currentName, currentFieldMeta.getReference().getTargetEntity(), currentFieldMeta.getReference().getReferenceId()); } currentCriteria = criteriaJoin; }while (step >= names.length); Holder<E> holder = new Holder<>(); holder.currentFieldName = currentName; holder.currentCriteria = currentCriteria; holder.currentFieldMeta = currentFieldMeta; return holder; }
java
{ "resource": "" }
q177807
TokenFactory.isAuthorized
test
private boolean isAuthorized(BasicToken token, List<UriTemplate> matchedTemplates, String method) { StringBuilder path = new StringBuilder(); // Merge all path templates and generate a path. for (UriTemplate template : matchedTemplates) { path.insert(0, template.getTemplate()); } path.append(":").append(method); //Look at user permissions to see if the service is permitted. return token.getPermissions().contains(path.toString()); }
java
{ "resource": "" }
q177808
ParseDate.parse
test
@Override public Date parse(Object o, Field field) { if (!isValid(o)) { return null; } JsonFormat formatAnn = field.getAnnotation(JsonFormat.class); if (formatAnn == null) { throw new RuntimeException("JsonFormat with pattern needed for: " + field.getName()); } try { return new SimpleDateFormat(formatAnn.pattern(), Locale.getDefault()).parse(o.toString()); } catch (ParseException e) { throw new RuntimeException("JsonFormat with pattern is wrong for: " + field.getName() + " pattern: " + formatAnn.pattern()); } }
java
{ "resource": "" }
q177809
RobeRuntimeException.getResponse
test
public Response getResponse() { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(builder.build()).build(); }
java
{ "resource": "" }
q177810
Restrictions.eq
test
public static Restriction eq(String name, Object value) { return new Restriction(Operator.EQUALS, name, value); }
java
{ "resource": "" }
q177811
Restrictions.ne
test
public static Restriction ne(String name, Object value){ return new Restriction(Operator.NOT_EQUALS, name, value); }
java
{ "resource": "" }
q177812
Restrictions.lt
test
public static Restriction lt(String name, Object Object){ return new Restriction(Operator.LESS_THAN, name, Object); }
java
{ "resource": "" }
q177813
Restrictions.le
test
public static Restriction le(String name, Object value){ return new Restriction(Operator.LESS_OR_EQUALS_THAN, name, value); }
java
{ "resource": "" }
q177814
Restrictions.gt
test
public static Restriction gt(String name, Object value){ return new Restriction(Operator.GREATER_THAN, name, value); }
java
{ "resource": "" }
q177815
Restrictions.ge
test
public static Restriction ge(String name, Object value){ return new Restriction(Operator.GREATER_OR_EQUALS_THAN, name, value); }
java
{ "resource": "" }
q177816
Restrictions.ilike
test
public static Restriction ilike(String name, Object value){ return new Restriction(Operator.CONTAINS, name, value); }
java
{ "resource": "" }
q177817
Restrictions.in
test
public static Restriction in(String name, Object value){ return new Restriction(Operator.IN, name, value); }
java
{ "resource": "" }
q177818
NamespaceManager.withNamespace
test
public NamespaceManager withNamespace(String namespace, String href) { if (namespaces.containsKey(namespace)) { throw new RepresentationException( format("Duplicate namespace '%s' found for representation factory", namespace)); } if (!href.contains("{rel}")) { throw new RepresentationException( format("Namespace '%s' does not include {rel} URI template argument.", namespace)); } return new NamespaceManager(namespaces.put(namespace, href)); }
java
{ "resource": "" }
q177819
ResourceRepresentation.withContent
test
public ResourceRepresentation<V> withContent(ByteString content) { return new ResourceRepresentation<>( Option.of(content), links, rels, namespaceManager, value, resources); }
java
{ "resource": "" }
q177820
ResourceRepresentation.withRel
test
public ResourceRepresentation<V> withRel(Rel rel) { if (rels.containsKey(rel.rel())) { throw new IllegalStateException(String.format("Rel %s is already declared.", rel.rel())); } final TreeMap<String, Rel> updatedRels = rels.put(rel.rel(), rel); return new ResourceRepresentation<>( content, links, updatedRels, namespaceManager, value, resources); }
java
{ "resource": "" }
q177821
ResourceRepresentation.withValue
test
public <R> ResourceRepresentation<R> withValue(R newValue) { return new ResourceRepresentation<>( Option.none(), links, rels, namespaceManager, newValue, resources); }
java
{ "resource": "" }
q177822
ResourceRepresentation.withNamespace
test
public ResourceRepresentation<V> withNamespace(String namespace, String href) { if (!rels.containsKey("curies")) { rels = rels.put("curies", Rels.collection("curies")); } final NamespaceManager updatedNamespaceManager = namespaceManager.withNamespace(namespace, href); return new ResourceRepresentation<>( content, links, rels, updatedNamespaceManager, value, resources); }
java
{ "resource": "" }
q177823
UTF8.canDecode
test
public static boolean canDecode(byte[] input, int off, int len) { try { decode(input, off, len); } catch (IllegalArgumentException ex) { return false; } return true; }
java
{ "resource": "" }
q177824
UTF8.encode
test
public static byte[] encode(String str, int off, int len) { return encode(str.substring(off, off + len)); }
java
{ "resource": "" }
q177825
CharStreams.equal
test
public static boolean equal(Reader in1, Reader in2) throws IOException { if (in1 == in2) { return true; } if (in1 == null || in2 == null) { return false; } in1 = buffer(in1); in2 = buffer(in2); int c1 = in1.read(); int c2 = in2.read(); while (c1 != -1 && c2 != -1 && c1 == c2) { c1 = in1.read(); c2 = in2.read(); } return in1.read() == -1 && in2.read() == -1; }
java
{ "resource": "" }
q177826
XFiles.mv
test
public static void mv(File src, File dst) throws IOException { Parameters.checkNotNull(dst); if (!src.equals(dst)) { cp(src, dst); try { rm(src); } catch (IOException e) { rm(dst); throw new IOException("Can't move " + src, e); } } }
java
{ "resource": "" }
q177827
XFiles.touch
test
public static void touch(File... files) throws IOException { long now = System.currentTimeMillis(); for (File f : files) { if (!f.createNewFile() && !f.setLastModified(now)) { throw new IOException("Failed to touch " + f); } } }
java
{ "resource": "" }
q177828
XFiles.getBaseName
test
public static String getBaseName(File f) { String fileName = f.getName(); int index = fileName.lastIndexOf('.'); return index == -1 ? fileName : fileName.substring(0, index); }
java
{ "resource": "" }
q177829
MD4.addPadding
test
private void addPadding() { int len = BLOCK_LENGTH - bufferLen; if (len < 9) { len += BLOCK_LENGTH; } byte[] buf = new byte[len]; buf[0] = (byte) 0x80; for (int i = 1; i < len - 8; i++) { buf[i] = (byte) 0x00; } counter = (counter + (long) bufferLen) * 8L; LittleEndian.encode(counter, buf, len - 8); update(buf); }
java
{ "resource": "" }
q177830
Classes.getShortName
test
public static String getShortName(Class<?> c) { String qname = getQualifiedName(c); int start = qname.lastIndexOf('$'); if (start == -1) { start = qname.lastIndexOf('.'); } return qname.substring(start + 1); }
java
{ "resource": "" }
q177831
Classes.getSuperTypes
test
public static Set<Class<?>> getSuperTypes(Class<?> c) { Set<Class<?>> classes = new HashSet<Class<?>>(); for (Class<?> clazz : c.getInterfaces()) { classes.add(clazz); classes.addAll(getSuperTypes(clazz)); } Class<?> sup = c.getSuperclass(); if (sup != null) { classes.add(sup); classes.addAll(getSuperTypes(sup)); } return Collections.unmodifiableSet(classes); }
java
{ "resource": "" }
q177832
Passwords.verify
test
public static boolean verify(String password, byte[] hash) { byte[] h = Arrays.copyOf(hash, HASH_LENGTH + SALT_LENGTH + 3); int n = 1 << (h[HASH_LENGTH + SALT_LENGTH] & 0xFF); int r = h[HASH_LENGTH + SALT_LENGTH + 1] & 0xFF; int p = h[HASH_LENGTH + SALT_LENGTH + 2] & 0xFF; if (n > N || n < N_MIN || r > R || r < R_MIN || p > P || p < P_MIN) { n = N; r = R; p = P; } byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(h, HASH_LENGTH, salt, 0, SALT_LENGTH); byte[] expected = hash(password, salt, r, n, p); int result = 0; for (int i = 0; i < h.length; i++) { result |= h[i] ^ expected[i]; } return result == 0; }
java
{ "resource": "" }
q177833
Scanf.readString
test
public static String readString(Charset charset) throws IOException { Reader in = new InputStreamReader(System.in, charset); BufferedReader reader = new BufferedReader(in); try { return reader.readLine(); } finally { reader.close(); } }
java
{ "resource": "" }
q177834
ByteBuffer.append
test
public ByteBuffer append(byte b) { int newCount = count + 1; ensureCapacity(newCount); buf[count] = b; count = newCount; return this; }
java
{ "resource": "" }
q177835
ByteBuffer.append
test
public ByteBuffer append(byte[] bytes, int off, int len) { int newCount = count + len; ensureCapacity(newCount); System.arraycopy(bytes, off, buf, count, len); count = newCount; return this; }
java
{ "resource": "" }
q177836
XArrays.copyOf
test
public static <T> T[] copyOf(T[] original) { return Arrays.copyOf(original, original.length); }
java
{ "resource": "" }
q177837
Fraction.plus
test
public Fraction plus(Fraction f) { return new Fraction(n.multiply(f.d).add(f.n.multiply(d)), d.multiply(f.d)).reduced(); }
java
{ "resource": "" }
q177838
Fraction.minus
test
public Fraction minus(Fraction f) { return new Fraction(n.multiply(f.d).subtract(f.n.multiply(d)), d.multiply(f.d)).reduced(); }
java
{ "resource": "" }
q177839
Fraction.multipliedBy
test
public Fraction multipliedBy(Fraction f) { return new Fraction(n.multiply(f.n), d.multiply(f.d)).reduced(); }
java
{ "resource": "" }
q177840
Fraction.dividedBy
test
public Fraction dividedBy(Fraction f) { if (ZERO.equals(f)) { throw new ArithmeticException("Division by zero"); } return new Fraction(n.multiply(f.d), d.multiply(f.n)).reduced(); }
java
{ "resource": "" }
q177841
Numbers.max
test
public static long max(long... values) { Parameters.checkCondition(values.length > 0); long max = values[0]; for (int i = 1; i < values.length; i++) { max = Math.max(max, values[i]); } return max; }
java
{ "resource": "" }
q177842
Numbers.min
test
public static long min(long... values) { Parameters.checkCondition(values.length > 0); long min = values[0]; for (int i = 1; i < values.length; i++) { min = Math.min(min, values[i]); } return min; }
java
{ "resource": "" }
q177843
Parameters.checkCondition
test
public static void checkCondition(boolean condition, String msg, Object... args) { if (!condition) { throw new IllegalArgumentException(format(msg, args)); } }
java
{ "resource": "" }
q177844
LocationforecastLTSService.fetchContent
test
public MeteoData<LocationForecast> fetchContent(double longitude, double latitude, int altitude) throws MeteoException { MeteoResponse response = getMeteoClient().fetchContent( createServiceUriBuilder() .addParameter(PARAM_LATITUDE, latitude) .addParameter(PARAM_LONGITUDE, longitude) .addParameter(PARAM_ALTITUDE, altitude).build() ); return new MeteoData<>(parser.parse(response.getData()), response); }
java
{ "resource": "" }
q177845
SunriseService.fetchContent
test
public MeteoData<Sunrise> fetchContent(double longitude, double latitude, LocalDate date) throws MeteoException { MeteoResponse response = getMeteoClient().fetchContent( createServiceUriBuilder() .addParameter(PARAM_LATITUDE, latitude) .addParameter(PARAM_LONGITUDE, longitude) .addParameter(PARAM_DATE, zonedDateTimeToYyyyMMdd(date)).build()); return new MeteoData<>(parser.parse(response.getData()), response); }
java
{ "resource": "" }
q177846
SunriseService.fetchContent
test
public MeteoData<Sunrise> fetchContent(double longitude, double latitude, LocalDate from, LocalDate to) throws MeteoException { MeteoResponse response = getMeteoClient().fetchContent( createServiceUriBuilder() .addParameter(PARAM_LATITUDE, latitude) .addParameter(PARAM_LONGITUDE, longitude) .addParameter(PARAM_FROM, zonedDateTimeToYyyyMMdd(from)) .addParameter(PARAM_TO, zonedDateTimeToYyyyMMdd(to)).build() ); return new MeteoData<>(parser.parse(response.getData()), response); }
java
{ "resource": "" }
q177847
LocationForecastHelper.findHourlyPointForecastsFromNow
test
public List<MeteoExtrasForecast> findHourlyPointForecastsFromNow(int hoursAhead) { List<MeteoExtrasForecast> pointExtrasForecasts = new ArrayList<>(); ZonedDateTime now = getNow(); for (int i = 0; i < hoursAhead; i++) { ZonedDateTime ahead = now.plusHours(i); Optional<PointForecast> pointForecast = getIndexer().getPointForecast(ahead); pointForecast.ifPresent(pof -> { Optional<PeriodForecast> periodForecast = getIndexer().getTightestFitPeriodForecast(pof.getFrom()); periodForecast.ifPresent(pef -> pointExtrasForecasts .add(new MeteoExtrasForecast(pof, pef))); }); } return pointExtrasForecasts; }
java
{ "resource": "" }
q177848
LocationForecastHelper.findNearestForecast
test
public Optional<MeteoExtrasForecast> findNearestForecast(ZonedDateTime dateTime) { ZonedDateTime dt = toZeroMSN(dateTime.withZoneSameInstant(METZONE)); PointForecast chosenForecast = null; for (Forecast forecast : getLocationForecast().getForecasts()) { if (forecast instanceof PointForecast) { PointForecast pointForecast = (PointForecast) forecast; if (isDateMatch(dt, cloneZonedDateTime(pointForecast.getFrom()))) { chosenForecast = pointForecast; break; } else if (chosenForecast == null) { chosenForecast = pointForecast; } else if (isNearerDate(pointForecast.getFrom(), dt, chosenForecast.getFrom())) { chosenForecast = pointForecast; } } } if (chosenForecast == null) { return Optional.empty(); } return Optional.of( new MeteoExtrasForecast( chosenForecast, getIndexer().getWidestFitPeriodForecast(chosenForecast.getFrom()).orElse(null))); }
java
{ "resource": "" }
q177849
TextforecastService.fetchContent
test
public MeteoData<Weather> fetchContent(ForecastQuery query) throws MeteoException { MeteoResponse response = getMeteoClient().fetchContent( createServiceUriBuilder() .addParameter("forecast", query.getName()) .addParameter("language", query.getLanguage().getValue()) .build()); return new MeteoData<>(parser.parse(response.getData()), response); }
java
{ "resource": "" }
q177850
LongtermForecastHelper.createSimpleLongTermForecast
test
public MeteoExtrasLongTermForecast createSimpleLongTermForecast() throws MeteoException { List<MeteoExtrasForecastDay> forecastDays = new ArrayList<>(); ZonedDateTime dt = getNow(); for (int i = 0; i <= 6; i++) { ZonedDateTime dti = dt.plusDays(i); if (getIndexer().hasForecastsForDay(dti)) { MeteoExtrasForecastDay mefd = createSimpleForcastForDay(dti); if (mefd != null && mefd.getForecasts().size() > 0) { forecastDays.add(mefd); } } } return new MeteoExtrasLongTermForecast(forecastDays); }
java
{ "resource": "" }
q177851
LongtermForecastHelper.createLongTermForecast
test
public MeteoExtrasLongTermForecast createLongTermForecast() { List<MeteoExtrasForecastDay> forecastDays = new ArrayList<>(); ZonedDateTime dt = toZeroHMSN(getLocationForecast().getCreated().plusDays(1)); for (int i = 0; i < series.getSeries().size(); i++) { createLongTermForecastDay(dt.plusDays(i), series.getSeries().get(i)) .ifPresent(forecastDays::add); } return new MeteoExtrasLongTermForecast(forecastDays); }
java
{ "resource": "" }
q177852
Location.fromCoordinates
test
public static Location fromCoordinates(String coordinates) { if (coordinates == null) { throw new IllegalArgumentException("Cannot create Location from null input."); } Matcher m = P.matcher(coordinates); if (!m.matches()) { throw new IllegalArgumentException( coordinates + " must be on the pattern (longitude,latitude,altitude) : " + P.pattern()); } try { Double longitude = Double.valueOf(m.group(1)); Double latitude = Double.valueOf(m.group(2)); Integer altitude = 0; if (m.group(3) != null) { altitude = Integer.valueOf(m.group(3).substring(1)); } return new Location(longitude, latitude, altitude, ""); } catch (NumberFormatException e) { throw new IllegalArgumentException( coordinates + " must be on the pattern (longitude,latitude,altitude) : " + P.pattern()); } }
java
{ "resource": "" }
q177853
AvailableTextforecastsService.fetchContent
test
public MeteoData<Available> fetchContent() throws MeteoException { MeteoResponse response = getMeteoClient().fetchContent( createServiceUriBuilder().addParameter("available", null).skipQuestionMarkInUrl().build()); return new MeteoData<>(parser.parse(response.getData()), response); }
java
{ "resource": "" }
q177854
WindSymbolHelper.createWindSymbolName
test
public static Optional<String> createWindSymbolName(PointForecast pointForecast) { if (pointForecast == null || pointForecast.getWindDirection() == null || pointForecast.getWindSpeed() == null) { return Optional.empty(); } return Optional.of( pointForecast.getWindDirection().getName().toLowerCase() + idFormat.format(pointForecast.getWindSpeed().getBeaufort())); }
java
{ "resource": "" }
q177855
WindSymbolHelper.findBeaufortLevel
test
public static Optional<BeaufortLevel> findBeaufortLevel(PointForecast pointForecast) { if (pointForecast == null || pointForecast.getWindSpeed() == null) { return Optional.empty(); } return Optional.ofNullable(findUnitById(pointForecast.getWindSpeed().getBeaufort())); }
java
{ "resource": "" }
q177856
MeteoNetUtils.createUri
test
public static URI createUri(String uri) throws MeteoException { if (uri == null) { throw new MeteoException("URI is null"); } try { return new URI(uri); } catch (URISyntaxException e) { throw new MeteoException(e); } }
java
{ "resource": "" }
q177857
SunriseDate.isSun
test
public boolean isSun(ZonedDateTime currentDate) { if (getSun().getNeverRise()) { return false; } else if (getSun().getNeverSet()) { return true; } return timeWithinPeriod(currentDate); }
java
{ "resource": "" }
q177858
MeteoForecastIndexer.getPointForecast
test
Optional<PointForecast> getPointForecast(ZonedDateTime dateTime) { for (Forecast forecast : forecasts) { if (forecast instanceof PointForecast) { PointForecast pointForecast = (PointForecast) forecast; if (createHourIndexKey(dateTime) .equals(createHourIndexKey(cloneZonedDateTime(pointForecast.getFrom())))) { return Optional.of(pointForecast); } } } return Optional.empty(); }
java
{ "resource": "" }
q177859
MeteoForecastIndexer.getBestFitPeriodForecast
test
Optional<PeriodForecast> getBestFitPeriodForecast(ZonedDateTime from, ZonedDateTime to) { if (from == null || to == null) { return Optional.empty(); } // Making sure that we remove minutes, seconds and milliseconds from the request timestamps ZonedDateTime requestFrom = toZeroMSN(from); ZonedDateTime requestTo = toZeroMSN(to); // Get list of period forecasts for the requested day. Return empty if date isn't present List<PeriodForecast> forecastsList = dayIndex.get(new DayIndexKey(requestFrom)); if (forecastsList == null) { return Optional.empty(); } PeriodForecast chosenForecast = null; long score = 0; long tmpScore = 0; for (PeriodForecast forecast : forecastsList) { ZonedDateTime actualFrom = cloneZonedDateTime(forecast.getFrom()); ZonedDateTime actualTo = cloneZonedDateTime(forecast.getTo()); if (requestFrom.equals(actualFrom) && requestTo.equals(actualTo)) { return Optional.of(forecast); } else if ( (requestFrom.isBefore(actualFrom) && requestTo.isBefore(actualFrom)) || (requestFrom.isAfter(actualTo) && requestTo.isAfter(actualTo)) || actualTo.isEqual(actualFrom)) { continue; // this period is outside the requested period or this is a point forecast. } else if (requestFrom.isBefore(actualFrom) && requestTo.isBefore(actualTo)) { tmpScore = hoursBetween(requestTo, actualFrom); } else if ((actualFrom.isBefore(requestFrom) || actualFrom.isEqual(requestFrom)) && actualTo.isBefore(requestTo)) { tmpScore = hoursBetween(actualTo, requestFrom); } else if (actualFrom.isAfter(requestFrom) && (actualTo.isBefore(requestTo) || actualTo.isEqual(requestTo))) { tmpScore = hoursBetween(actualTo, actualFrom); } else if (actualFrom.isBefore(requestFrom) && actualTo.isAfter(requestTo)) { tmpScore = hoursBetween(requestTo, requestFrom); } else { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm"); log.warn("Unhandled forecast Requested period:" + requestFrom.format(formatter) + "--" + requestTo.format(formatter) + ", Actual period: " + actualFrom.format(formatter) + "--" + actualTo.format(formatter)); } tmpScore = Math.abs(tmpScore); if ((score == 0 && tmpScore > 0) || tmpScore > score) { score = tmpScore; chosenForecast = forecast; } } return Optional.ofNullable(chosenForecast); }
java
{ "resource": "" }
q177860
TextLocationService.fetchContent
test
public MeteoData<TextLocationWeather> fetchContent(double longitude, double latitude) throws MeteoException { return fetchContent(longitude, latitude, TextLocationLanguage.NB); }
java
{ "resource": "" }
q177861
TextLocationService.fetchContent
test
public MeteoData<TextLocationWeather> fetchContent(double longitude, double latitude, TextLocationLanguage language) throws MeteoException { MeteoResponse response = getMeteoClient().fetchContent( createServiceUriBuilder() .addParameter("latitude", latitude) .addParameter("longitude", longitude) .addParameter("language", language.getValue()) .build()); return new MeteoData<>(parser.parse(response.getData()), response); }
java
{ "resource": "" }
q177862
Application.updateDB
test
private void updateDB() throws SQLException, LiquibaseException { System.out.println("About to perform DB update."); try (BasicDataSource dataSource = new BasicDataSource()) { dataSource.setUrl(fullConnectionString); dataSource.setUsername(username); dataSource.setPassword(password); try (java.sql.Connection c = dataSource.getConnection()) { Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c)); // Check that the Database does indeed exist before we try to run the liquibase update. Liquibase liquibase = null; ClassLoaderResourceAccessor accessor = new ClassLoaderResourceAccessor(); try { if (accessor.getResourcesAsStream("changelog-master.xml") != null) { liquibase = new Liquibase("changelog-master.xml", new ClassLoaderResourceAccessor(), database); } else if (accessor.getResourcesAsStream("changelog.xml") != null) { liquibase = new Liquibase("changelog.xml", new ClassLoaderResourceAccessor(), database); } else { String errorMessage = "No liquibase changelog-master.xml or changelog.xml could be located"; Logger.getLogger(Application.class.getName()).log(Level.SEVERE, errorMessage, this); throw new RuntimeException(errorMessage); } } catch (final IOException ioe) { Logger.getLogger(Application.class.getName()).log(Level.SEVERE, ioe.getMessage(), ioe); } liquibase.getLog().setLogLevel(logLevel); liquibase.update(new Contexts()); System.out.println("DB update finished."); } } }
java
{ "resource": "" }
q177863
JavascriptDecoder.invokeStringMethod
test
private static String invokeStringMethod(final ScriptEngine jsEngine, final Object thiz, final String name, final Object... args) throws NoSuchMethodException, ScriptException { return (String) ((Invocable) jsEngine).invokeMethod(thiz, name, args); }
java
{ "resource": "" }
q177864
ReferencedObject.acquire
test
public synchronized T acquire(final DataSource source) throws DataSourceException { if (object == null) { if (getReference() == null) { throw new IllegalStateException("No reference or object present"); } else { object = source.getObject(getReference(), objectClass); } } return object; }
java
{ "resource": "" }
q177865
ReferencedObject.getReferencedObject
test
public static <T> ReferencedObject<T> getReferencedObject(final Class<T> clazz, final String ref) { return new ReferencedObject<>(clazz, ref, null); }
java
{ "resource": "" }
q177866
ReferencedObject.getWrappedObject
test
public static <T> ReferencedObject<T> getWrappedObject(final Class<T> clazz, final T obj) { return new ReferencedObject<>(clazz, null, obj); }
java
{ "resource": "" }
q177867
CafConfigurationSource.getConfig
test
private <T> T getConfig(final Class<T> configClass) throws ConfigurationException { Iterator<Name> it = getServicePath().descendingPathIterator(); while (it.hasNext()) { try (InputStream in = getConfigurationStream(configClass, it.next())) { return decoder.deserialise(in, configClass); } catch (final ConfigurationException e) { LOG.trace("No configuration at this path level", e); } catch (final CodecException | IOException e) { incrementErrors(); throw new ConfigurationException("Failed to get configuration for " + configClass.getSimpleName(), e); } } incrementErrors(); throw new ConfigurationException("No configuration found for " + configClass.getSimpleName()); }
java
{ "resource": "" }
q177868
CafConfigurationSource.getIsSubstitutorEnabled
test
private static boolean getIsSubstitutorEnabled(final BootstrapConfiguration bootstrapConfig) { final String ENABLE_SUBSTITUTOR_CONFIG_KEY = "CAF_CONFIG_ENABLE_SUBSTITUTOR"; final boolean ENABLE_SUBSTITUTOR_CONFIG_DEFAULT = true; // Return the default if the setting is not configured if (!bootstrapConfig.isConfigurationPresent(ENABLE_SUBSTITUTOR_CONFIG_KEY)) { return ENABLE_SUBSTITUTOR_CONFIG_DEFAULT; } // Return the configured setting. // The ConfigurationException should never happen since isConfigurationPresent() has already been called. try { return bootstrapConfig.getConfigurationBoolean(ENABLE_SUBSTITUTOR_CONFIG_KEY); } catch (final ConfigurationException ex) { throw new RuntimeException(ex); } }
java
{ "resource": "" }
q177869
Jersey2ServiceIteratorProvider.createClassIterator
test
@Override public <T> Iterator<Class<T>> createClassIterator( final Class<T> service, final String serviceName, final ClassLoader loader, final boolean ignoreOnClassNotFound ) { final Iterator<Class<T>> delegateClassIterator = delegate.createClassIterator( service, serviceName, loader, ignoreOnClassNotFound); Stream<Class<T>> stream = StreamSupport.stream( Spliterators.spliteratorUnknownSize(delegateClassIterator, Spliterator.ORDERED), false); return stream.filter(t -> !t.getPackage().getName().startsWith("com.sun.jersey")).collect(Collectors.toList()).iterator(); }
java
{ "resource": "" }
q177870
CafConfigurationDecoderProvider.getDecoder
test
@Override public Decoder getDecoder(final BootstrapConfiguration bootstrap, final Decoder defaultDecoder) { final String DECODER_CONFIG_KEY = "CAF_CONFIG_DECODER"; final String decoder; try { // Return the specified default Decoder if none has been configured if (!bootstrap.isConfigurationPresent(DECODER_CONFIG_KEY)) { return defaultDecoder; } // Lookup the Decoder to use decoder = bootstrap.getConfiguration(DECODER_CONFIG_KEY); } catch (final ConfigurationException ex) { // Throw a RuntimeException since this shouldn't happen // (since isConfigurationPresent() has already been called) throw new RuntimeException(ex); } try { // Retrieve the Decoder using the ModuleProvider return ModuleProvider.getInstance().getModule(Decoder.class, decoder); } catch (final NullPointerException ex) { throw new RuntimeException("Unable to get Decoder using " + DECODER_CONFIG_KEY + " value: " + decoder, ex); } }
java
{ "resource": "" }
q177871
ModuleLoader.getServices
test
public static <T> List<T> getServices(final Class<T> intf) { Objects.requireNonNull(intf); List<T> ret = new LinkedList<>(); for (final T t : ServiceLoader.load(intf)) { ret.add(t); } return ret; }
java
{ "resource": "" }
q177872
ModuleProvider.getModule
test
public <T> T getModule(final Class<T> interfaceImplemented, final String moduleType) throws NullPointerException { //check for this type in the map Map<String, Object> computedValue = loadedModules.computeIfAbsent(interfaceImplemented, ModuleProvider::loadModules); Object moduleInstance = computedValue.get(moduleType); Objects.requireNonNull( moduleInstance, "Unable to find implementation of " + interfaceImplemented.getName() + " with moduleType " + moduleType); return (T) moduleInstance; }
java
{ "resource": "" }
q177873
ReferencedData.acquire
test
public synchronized InputStream acquire(final DataSource source) throws DataSourceException { InputStream ret; if (data == null) { if (getReference() == null) { throw new IllegalStateException("No data or reference present"); } else { ret = source.getStream(getReference()); } } else { ret = new ByteArrayInputStream(data); } return ret; }
java
{ "resource": "" }
q177874
ReferencedData.size
test
public synchronized long size(final DataSource source) throws DataSourceException { if (data == null) { if (getReference() == null) { throw new IllegalStateException("No data or reference present"); } else { return source.getDataSize(getReference()); } } else { return data.length; } }
java
{ "resource": "" }
q177875
ReferencedData.getWrappedData
test
public static ReferencedData getWrappedData(final String ref, final byte[] data) { return new ReferencedData(Objects.requireNonNull(ref), data); }
java
{ "resource": "" }
q177876
Name.getIndex
test
public String getIndex(final int index) { if (index < 0 || index >= components.size()) { throw new IllegalArgumentException("Index out of bounds"); } return components.get(index); }
java
{ "resource": "" }
q177877
Name.getPrefix
test
public Name getPrefix(final int upperIndex) { if (upperIndex < 0 || upperIndex > components.size()) { throw new IllegalArgumentException("Index out of bounds"); } return new Name(components.subList(0, upperIndex)); }
java
{ "resource": "" }
q177878
Arc.colored
test
boolean colored() { return type == Compiler.PLAIN || type == Compiler.AHEAD || type == Compiler.BEHIND; }
java
{ "resource": "" }
q177879
Runtime.exec
test
boolean exec(HsrePattern re, CharSequence data, EnumSet<ExecFlags> execFlags) throws RegexException { /* sanity checks */ /* setup */ if (0 != (re.guts.info & Flags.REG_UIMPOSSIBLE)) { throw new RegexException("Regex marked impossible"); } eflags = 0; for (ExecFlags ef : execFlags) { switch (ef) { case NOTBOL: eflags |= Flags.REG_NOTBOL; break; case NOTEOL: eflags |= Flags.REG_NOTEOL; break; case LOOKING_AT: eflags |= Flags.REG_LOOKING_AT; break; default: throw new RuntimeException("impossible exec flag"); } } this.re = re; this.g = re.guts; this.data = data; this.dataLength = this.data.length(); if (this.match != null) { this.match.clear(); } else { this.match = Lists.newArrayList(); } match.add(null); // make room for 1. if (0 != (g.info & Flags.REG_UBACKREF)) { while (match.size() < g.nsub + 1) { match.add(null); } } if (mem != null && mem.length >= g.ntree) { Arrays.fill(mem, 0); } else { mem = new int[g.ntree]; } /* do it */ assert g.tree != null; if (0 != (g.info & Flags.REG_UBACKREF)) { return cfind(g.tree.machine); } else { return find(g.tree.machine); } }
java
{ "resource": "" }
q177880
Runtime.cfindloop
test
private boolean cfindloop(Dfa d, Dfa s, int[] coldp) { int begin; int end; int cold; int open; /* open and close of range of possible starts */ int close; int estart; int estop; boolean shorter = 0 != (g.tree.flags & Subre.SHORTER); boolean hitend[] = new boolean[1]; boolean lookingAt = 0 != (eflags & Flags.REG_LOOKING_AT); assert d != null && s != null; close = 0; do { int[] cold0 = new int[1]; /* * Call search NFA to see if this is possible at all. */ if (lookingAt) { // in the looking at case, we use the un-search-ified RE. close = d.shortest(close, close, data.length(), cold0, null); cold = 0; } else { close = s.shortest(close, close, data.length(), cold0, null); cold = cold0[0]; } if (close == -1) { break; /* NOTE BREAK */ } assert cold != -1; open = cold; cold = -1; for (begin = open; begin <= close; begin++) { if (begin > 0 && lookingAt) { // Is this possible given the looking-at constraint in the call to shortest above? return false; } estart = begin; estop = data.length(); for (;;) { if (shorter) { end = d.shortest(begin, estart, estop, null, hitend); } else { end = d.longest(begin, estop, hitend); } if (hitend[0] && cold == -1) { cold = begin; } if (end == -1) { break; /* NOTE BREAK OUT */ } for (int x = 0; x < match.size(); x++) { match.set(x, null); } int maxsubno = getMaxSubno(g.tree, 0); mem = new int[maxsubno + 1]; boolean matched = cdissect(g.tree, begin, end); if (matched) { // indicate the full match bounds. match.set(0, new RegMatch(begin, end)); coldp[0] = cold; return true; } if (shorter ? end == estop : end == begin) { /* no point in trying again */ coldp[0] = cold; return false; } /* go around and try again */ if (shorter) { estart = end + 1; } else { estop = end - 1; } } } } while (close < data.length()); coldp[0] = cold; return false; }
java
{ "resource": "" }
q177881
Runtime.subset
test
private void subset(RuntimeSubexpression sub, int begin, int end) { int n = sub.number; assert n > 0; while (match.size() < (n + 1)) { match.add(null); } match.set(n, new RegMatch(begin, end)); }
java
{ "resource": "" }
q177882
Runtime.crevdissect
test
private boolean crevdissect(RuntimeSubexpression t, int begin, int end) { Dfa d; Dfa d2; int mid; assert t.op == '.'; assert t.left != null && t.left.machine.states.length > 0; assert t.right != null && t.right.machine.states.length > 0; assert 0 != (t.left.flags & Subre.SHORTER); /* concatenation -- need to split the substring between parts */ d = new Dfa(this, t.left.machine); d2 = new Dfa(this, t.right.machine); /* pick a tentative midpoint */ if (mem[t.retry] == 0) { mid = d.shortest(begin, begin, end, null, null); if (mid == -1) { return false; } mem[t.retry] = (mid - begin) + 1; } else { mid = begin + (mem[t.retry] - 1); } /* iterate until satisfaction or failure */ for (;;) { /* try this midpoint on for size */ boolean cdmatch = cdissect(t.left, begin, mid); if (cdmatch && d2.longest(mid, end, null) == end && (cdissect(t.right, mid, end))) { break; /* NOTE BREAK OUT */ } /* that midpoint didn't work, find a new one */ if (mid == end) { /* all possibilities exhausted */ return false; } mid = d.shortest(begin, mid + 1, end, null, null); if (mid == -1) { /* failed to find a new one */ return false; } mem[t.retry] = (mid - begin) + 1; zapmem(t.left); zapmem(t.right); } /* satisfaction */ return true; }
java
{ "resource": "" }
q177883
Runtime.cbrdissect
test
private boolean cbrdissect(RuntimeSubexpression t, int begin, int end) { int i; int n = t.number; int len; int paren; int p; int stop; int min = t.min; int max = t.max; assert t.op == 'b'; assert n >= 0; //TODO: could this get be out of range? if (match.get(n) == null) { return false; } paren = match.get(n).start; len = match.get(n).end - match.get(n).start; /* no room to maneuver -- retries are pointless */ if (0 != mem[t.retry]) { return false; } mem[t.retry] = 1; /* special-case zero-length string */ if (len == 0) { return begin == end; } /* and too-short string */ assert end >= begin; if ((end - begin) < len) { return false; } stop = end - len; /* count occurrences */ i = 0; for (p = begin; p <= stop && (i < max || max == Compiler.INFINITY); p += len) { // paren is index of if (g.compare.compare(data, paren, p, len) != 0) { break; } i++; } /* and sort it out */ if (p != end) { /* didn't consume all of it */ return false; } return min <= i && (i <= max || max == Compiler.INFINITY); }
java
{ "resource": "" }
q177884
Compiler.cloneouts
test
private void cloneouts(Nfa nfa, State old, State from, State to, int type) { Arc a; assert old != from; for (a = old.outs; a != null; a = a.outchain) { nfa.newarc(type, a.co, from, to); } }
java
{ "resource": "" }
q177885
Compiler.optst
test
private void optst(Subre t) { if (t == null) { return; } /* recurse through children */ if (t.left != null) { optst(t.left); } if (t.right != null) { optst(t.right); } }
java
{ "resource": "" }
q177886
Compiler.markst
test
private void markst(Subre t) { assert t != null; t.flags |= Subre.INUSE; if (t.left != null) { markst(t.left); } if (t.right != null) { markst(t.right); } }
java
{ "resource": "" }
q177887
Compiler.nfanode
test
private long nfanode(Subre t) throws RegexException { long ret; assert t.begin != null; if (LOG.isDebugEnabled() && IS_DEBUG) { LOG.debug(String.format("========= TREE NODE %s ==========", t.shortId())); } Nfa newNfa = new Nfa(nfa); newNfa.dupnfa(t.begin, t.end, newNfa.init, newNfa.finalState); newNfa.specialcolors(); ret = newNfa.optimize(); t.cnfa = newNfa.compact(); // freenfa ... depend on our friend the GC. return ret; }
java
{ "resource": "" }
q177888
Compiler.parse
test
private Subre parse(int stopper, int type, State initState, State finalState) throws RegexException { State left; /* scaffolding for branch */ State right; Subre branches; /* top level */ Subre branch; /* current branch */ Subre t; /* temporary */ int firstbranch; /* is this the first branch? */ assert stopper == ')' || stopper == EOS; branches = new Subre('|', Subre.LONGER, initState, finalState); branch = branches; firstbranch = 1; do { /* a branch */ if (0 == firstbranch) { /* need a place to hang it */ branch.right = new Subre('|', Subre.LONGER, initState, finalState); branch = branch.right; } firstbranch = 0; left = nfa.newstate(); right = nfa.newstate(); nfa.emptyarc(initState, left); nfa.emptyarc(right, finalState); branch.left = parsebranch(stopper, type, left, right, false); branch.flags |= up(branch.flags | branch.left.flags); if ((branch.flags & ~branches.flags) != 0) /* new flags */ { for (t = branches; t != branch; t = t.right) { t.flags |= branch.flags; } } } while (eat('|')); assert see(stopper) || see(EOS); if (!see(stopper)) { assert stopper == ')' && see(EOS); //ERR(REG_EPAREN); throw new RegexException("Unbalanced parentheses."); } /* optimize out simple cases */ if (branch == branches) { /* only one branch */ assert branch.right == null; t = branch.left; branch.left = null; branches = t; } else if (!messy(branches.flags)) { /* no interesting innards */ branches.left = null; branches.right = null; branches.op = '='; } return branches; }
java
{ "resource": "" }
q177889
Compiler.deltraverse
test
private void deltraverse(Nfa nfa, State leftend, State s) { Arc a; State to; if (s.nouts == 0) { return; /* nothing to do */ } if (s.tmp != null) { return; /* already in progress */ } s.tmp = s; /* mark as in progress */ while ((a = s.outs) != null) { to = a.to; deltraverse(nfa, leftend, to); assert to.nouts == 0 || to.tmp != null; nfa.freearc(a); if (to.nins == 0 && to.tmp == null) { assert to.nouts == 0; nfa.freestate(to); } } assert s.no != State.FREESTATE; /* we're still here */ assert s == leftend || s.nins != 0; /* and still reachable */ assert s.nouts == 0; /* but have no outarcs */ s.tmp = null; /* we're done here */ }
java
{ "resource": "" }
q177890
Compiler.nonword
test
private void nonword(int dir, State lp, State rp) { int anchor = (dir == AHEAD) ? '$' : '^'; assert dir == AHEAD || dir == BEHIND; nfa.newarc(anchor, (short)1, lp, rp); nfa.newarc(anchor, (short)0, lp, rp); cm.colorcomplement(nfa, dir, wordchrs, lp, rp); /* (no need for special attention to \n) */ }
java
{ "resource": "" }
q177891
Compiler.word
test
private void word(int dir, State lp, State rp) { assert dir == AHEAD || dir == BEHIND; cloneouts(nfa, wordchrs, lp, rp, dir); /* (no need for special attention to \n) */ }
java
{ "resource": "" }
q177892
Compiler.scannum
test
private int scannum() throws RegexException { int n = 0; while (see(DIGIT) && n < DUPMAX) { n = n * 10 + nextvalue; lex.next(); } if (see(DIGIT) || n > DUPMAX) { throw new RegexException("Unvalid reference number."); } return n; }
java
{ "resource": "" }
q177893
Compiler.bracket
test
private void bracket(State lp, State rp) throws RegexException { assert see('['); lex.next(); while (!see(']') && !see(EOS)) { brackpart(lp, rp); } assert see(']'); cm.okcolors(nfa); }
java
{ "resource": "" }
q177894
Compiler.scanplain
test
private String scanplain() throws RegexException { int startp = now; int endp; assert see(COLLEL) || see(ECLASS) || see(CCLASS); lex.next(); endp = now; while (see(PLAIN)) { endp = now; lex.next(); } String ret = new String(pattern, startp, endp - startp); assert see(END); lex.next(); return ret; }
java
{ "resource": "" }
q177895
Compiler.newlacon
test
private int newlacon(State begin, State end, int pos) { if (lacons.size() == 0) { // skip 0 lacons.add(null); } Subre sub = new Subre((char)0, 0, begin, end); sub.subno = pos; lacons.add(sub); return lacons.size() - 1; // it's the index into the array, -1. }
java
{ "resource": "" }
q177896
Compiler.onechr
test
private void onechr(int c, State lp, State rp) throws RegexException { if (0 == (cflags & Flags.REG_ICASE)) { nfa.newarc(PLAIN, cm.subcolor(c), lp, rp); return; } /* rats, need general case anyway... */ dovec(Locale.allcases(c), lp, rp); }
java
{ "resource": "" }
q177897
Compiler.dovec
test
private void dovec(UnicodeSet set, State lp, State rp) throws RegexException { int rangeCount = set.getRangeCount(); for (int rx = 0; rx < rangeCount; rx++) { int rangeStart = set.getRangeStart(rx); int rangeEnd = set.getRangeEnd(rx); /* * Note: ICU operates in UTF-32 here, and the ColorMap is happy to play along. */ if (LOG.isDebugEnabled() && IS_DEBUG) { LOG.debug(String.format("%s %d %4x %4x", set, rx, rangeStart, rangeEnd)); } //TODO: this arc is probably redundant. if (rangeStart == rangeEnd) { nfa.newarc(PLAIN, cm.subcolor(rangeStart), lp, rp); } cm.subrange(rangeStart, rangeEnd, lp, rp); } }
java
{ "resource": "" }
q177898
ColorMap.getcolor
test
private short getcolor(int c) { try { return map.get(c); } catch (NullPointerException npe) { throw new RegexRuntimeException(String.format("Failed to map codepoint U+%08X.", c)); } }
java
{ "resource": "" }
q177899
ColorMap.pseudocolor
test
short pseudocolor() { short co = newcolor(); ColorDesc cd = colorDescs.get(co); cd.setNChars(1); cd.markPseudo(); return co; }
java
{ "resource": "" }